Your First Agent

easy5 minfirst-agent.ts

You want an agent that answers questions with your own data: a tool with a Zod schema, a normal run, a streamed run and the token usage.

What it shows

  • Define a tool with tool() and a Zod schema
  • Run an agent with cog.run() and read output and toolCalls
  • Stream tokens with stream: true and onToken

The code

first-agent.ts
import { Agent, Cogitator, tool } from '@cogitator-ai/core';
import { z } from 'zod';

const apiKey = process.env.GOOGLE_API_KEY;
if (!apiKey) throw new Error('Set GOOGLE_API_KEY');

const dictionary: Record<string, string> = {
  petrichor: 'The pleasant earthy smell after rain.',
  sonder: 'The realization that each passerby has a life as vivid and complex as your own.',
};

const lookupWord = tool({
  name: 'lookup_word',
  description: 'Look up the definition of a word in the dictionary',
  parameters: z.object({
    word: z.string().describe('The word to look up'),
  }),
  execute: async ({ word }) => {
    const definition = dictionary[word.toLowerCase().trim()];
    return definition ? { found: true, word, definition } : { found: false, word };
  },
});

const cog = new Cogitator({ llm: { providers: { google: { apiKey } } } });

const agent = new Agent({
  name: 'lexicon',
  model: 'google/gemini-3.5-flash-lite',
  instructions: 'You are a helpful language assistant. Use your tools to look up words. Be concise.',
  tools: [lookupWord],
  temperature: 0.3,
  maxIterations: 5,
});

const result = await cog.run(agent, { input: 'What does "petrichor" mean?' });
console.log(result.output);
console.log('Tool calls:', result.toolCalls.map((call) => call.name));

process.stdout.write('Streaming: ');
const streamed = await cog.run(agent, {
  input: 'What does "sonder" mean? Explain in one sentence.',
  stream: true,
  onToken: (token) => process.stdout.write(token),
});
console.log('\nTokens:', streamed.usage.inputTokens, 'in /', streamed.usage.outputTokens, 'out');

await cog.close();

Run it

install · bash
pnpm add @cogitator-ai/core zod
EnvironmentGOOGLE_API_KEY
run · bash
GOOGLE_API_KEY=your-key npx tsx first-agent.ts

Or run the full example from a clone of the repository (keys in .env):

repository · bash
npx tsx examples/core/01-basic-agent.ts

Learn more