Skip to main content
Turn a short contact description into a typed object that your application can validate. The complete code is below. You can also browse the project on GitHub or open its JavaScript source.

1. Create the project

Use Node.js 22 or newer, npm, and an OpenAI API key with access to gpt-4.1-mini. Model requests use your provider account and can incur charges.
Keep npm optional dependencies enabled; they include the runtime for your platform. You do not need a separately installed runtime.

2. Configure the environment

Create a file named .env in this directory:
Replace the placeholder with your key. Add .env and node_modules/ to .gitignore. Existing shell environment values take precedence over this file. To use Anthropic instead, set COGNITIO_MODEL=anthropic/claude-sonnet-4-5 and ANTHROPIC_API_KEY to your Anthropic key; the code forwards either provider’s credential.

3. Create index.mjs

4. Run it

The fixed input should produce:
The application prints the object only after a successful result and contactSchema.parse(). A schema error or an unsuccessful model result exits with an error. Replace the contact sentence passed to agent.run() with your own input.

How it works

defineOutputFormat(modelSchema) supplies a simple model-facing shape. The stricter local contactSchema checks the actual email address after the response. This keeps provider-facing schema constraints separate from application validation. Read result.structuredOutput; do not parse result.text as a substitute. allowedTools: ["StructuredOutput"] permits only the runtime’s schema-output tool. Its name is case-sensitive. disallowedTools: ["*"] would block this tool too. This example allows three turns and one schema retry; retries also consume turns and model usage. The estimated $0.03 budget is not a provider billing limit. The explicit spawn configuration creates a dedicated runtime, which agent.close() stops in finally. Each request has a 90-second cancellation deadline. A valid object can still contain an incorrect extracted fact, so validate any additional rules your application requires. See structured output.

Use the existing project

If you prefer the complete GitHub project, copy that directory, run npm ci, copy .env.example to .env, set your key, and run npm start. On PowerShell, use Copy-Item .env.example .env; in a Unix shell, use cp .env.example .env.