Self-Reflection

medium10 minreflection.ts

The agent should notice its own mistakes — like an unknown ticker — and keep insights for next time.

What it shows

  • Turn on reflection in the Cogitator config
  • Read per-run reflections, stored insights and the summary

The code

reflection.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 prices: Record<string, number> = { AAPL: 242.35, NVDA: 137.71, MSFT: 432.67 };

const getStockPrice = tool({
  name: 'get_stock_price',
  description: 'Get the current stock price for a ticker symbol',
  parameters: z.object({ ticker: z.string().describe('Stock ticker symbol, e.g. AAPL') }),
  execute: async ({ ticker }) => {
    const price = prices[ticker.toUpperCase()];
    return price
      ? { ticker, price, currency: 'USD' }
      : { error: `Unknown ticker: ${ticker}. Available: ${Object.keys(prices).join(', ')}` };
  },
});

const calculateReturn = tool({
  name: 'calculate_return',
  description: 'Calculate the return on investment given buy price, current price and shares',
  parameters: z.object({ buyPrice: z.number(), currentPrice: z.number(), shares: z.number() }),
  execute: async ({ buyPrice, currentPrice, shares }) => {
    const invested = buyPrice * shares;
    const profit = currentPrice * shares - invested;
    return { invested, profit, returnPercent: (profit / invested) * 100 };
  },
});

const cog = new Cogitator({
  llm: { providers: { google: { apiKey } } },
  reflection: {
    enabled: true,
    reflectAfterToolCall: true,
    reflectAfterError: true,
    reflectAtEnd: true,
    storeInsights: true,
    minConfidenceToStore: 0.3,
    reflectionModel: 'google/gemini-3.5-flash-lite',
  },
});

const analyst = new Agent({
  name: 'portfolio-analyst',
  model: 'google/gemini-3.5-flash-lite',
  instructions: 'You are a portfolio analyst. Use your tools to look up prices and calculate returns.',
  tools: [getStockPrice, calculateReturn],
  temperature: 0.3,
  maxIterations: 15,
});

const result = await cog.run(analyst, {
  input: 'I bought 50 AAPL at $185 and 30 ZZZZ at $95. What are my returns?',
});
console.log(result.output);

for (const reflection of result.reflections ?? []) {
  console.log(
    `[${reflection.action.type}] success=${reflection.analysis.wasSuccessful} ` +
      `confidence=${reflection.analysis.confidence.toFixed(2)}: ${reflection.analysis.reasoning.slice(0, 100)}`
  );
}

const insights = await cog.getInsights(analyst.id);
for (const insight of insights.slice(0, 5)) {
  console.log(`insight [${insight.type}] ${insight.content}`);
}

const summary = await cog.getReflectionSummary(analyst.id);
if (summary) {
  console.log(`success rate ${(summary.successRate * 100).toFixed(0)}%, learned:`, summary.learnedPatterns);
}

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 reflection.ts

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

repository · bash
npx tsx examples/core/06-reflection.ts

Learn more