Skip to content

The platform for continuously improving AI agents.

6.3 KB
Raw Blame
/**
 * One agent run: OpenRouter (`openai/gpt-5-mini`) under the Overmind tracer.
 *
 *   OPENROUTER_API_KEY=... OVERMIND_API_KEY=... bun examples/agent.ts
 *
 * With no OTLP endpoint set, traces go to http://127.0.0.1:4318/v1/traces.
 * `init()` throws when `OVERMIND_API_KEY` is empty.
 */

if (!process.env.OTEL_EXPORTER_OTLP_ENDPOINT) {
  process.env.OTEL_EXPORTER_OTLP_ENDPOINT = "http://127.0.0.1:4318";
  process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT = "/v1/traces";
  process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT = "/v1/metrics";
  process.env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT = "/v1/logs";
}

const { init } = await import("../src/index.ts");
const { SpanStatusCode } = await import("@opentelemetry/api");

const MODEL = "openai/gpt-5-mini";
const question =
  process.argv[2] ??
  "How many words are in this sentence: traces should be cheap to read? Use the word_count tool.";

type ToolCall = {
  id: string;
  function: { name: string; arguments: string };
};

type ChatMessage = {
  role: string;
  content?: string | null;
  tool_calls?: ToolCall[];
  tool_call_id?: string;
};

const tools = [
  {
    type: "function",
    function: {
      name: "word_count",
      description: "Count the words in a piece of text.",
      parameters: {
        type: "object",
        properties: { text: { type: "string" } },
        required: ["text"],
      },
    },
  },
];

function wordCount(text: string): number {
  const trimmed = text.trim();
  return trimmed === "" ? 0 : trimmed.split(/\s+/).length;
}

async function complete(messages: ChatMessage[]): Promise<ChatMessage> {
  const apiKey = process.env.OPENROUTER_API_KEY;
  if (!apiKey) throw new Error("Set OPENROUTER_API_KEY");

  const response = await fetch("https://openrouter.ai/api/v1/chat/completions", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${apiKey}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ messages, model: MODEL, tools }),
  });
  const body = (await response.json()) as {
    error?: { message?: string };
    choices?: { message: ChatMessage }[];
    usage?: { prompt_tokens?: number; completion_tokens?: number };
  };
  if (!response.ok) {
    throw new Error(body.error?.message ?? `OpenRouter HTTP ${response.status}`);
  }
  const message = body.choices?.[0]?.message;
  if (!message) throw new Error("OpenRouter returned no message");
  message.usage = body.usage;
  return message;
}

const { tracer, meter, logger, flush, shutdown } = init({
  serviceDescription: "Single-script agent that calls OpenRouter.",
  serviceName: "openrouter-agent",
});
const calls = meter.createCounter("agent.llm.calls");

const endpoint = `${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}${process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT}`;
console.log(`otlp ${endpoint}`);
console.log(`question ${question}`);

try {
  await tracer.startActiveSpan("agent", async (agent) => {
    agent.setAttribute("overmind.span.type", "entry_point");
    agent.setAttribute("overmind.span.kind", "agent");
    agent.setAttribute("overmind.capability.id", "openrouter-agent");
    agent.setAttribute("gen_ai.request.model", MODEL);
    logger.emit({ body: "agent started", severityText: "INFO" });

    const messages: ChatMessage[] = [{ role: "user", content: question }];
    try {
      for (let step = 0; step < 4; step += 1) {
        const reply = await tracer.startActiveSpan("llm", async (span) => {
          span.setAttribute("overmind.span.type", "llm_call");
          span.setAttribute("overmind.span.kind", "llm");
          span.setAttribute("gen_ai.request.model", MODEL);
          span.setAttribute("gen_ai.operation.name", "chat");
          try {
            const message = await complete(messages);
            const usage = (message as ChatMessage & { usage?: { prompt_tokens?: number; completion_tokens?: number } }).usage;
            if (usage?.prompt_tokens !== undefined) {
              span.setAttribute("gen_ai.usage.input_tokens", usage.prompt_tokens);
            }
            if (usage?.completion_tokens !== undefined) {
              span.setAttribute("gen_ai.usage.output_tokens", usage.completion_tokens);
            }
            calls.add(1, { model: MODEL });
            return message;
          } catch (error) {
            span.recordException(error as Error);
            span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error).message });
            throw error;
          } finally {
            span.end();
          }
        });

        messages.push({
          content: reply.content,
          role: "assistant",
          tool_calls: reply.tool_calls,
        });

        const toolCalls = reply.tool_calls ?? [];
        if (toolCalls.length === 0) {
          console.log(reply.content ?? "");
          agent.setAttribute("overmind.delivery", "true");
          break;
        }

        for (const call of toolCalls) {
          await tracer.startActiveSpan("tool", async (span) => {
            span.setAttribute("overmind.span.type", "tool_call");
            span.setAttribute("overmind.span.kind", "tool");
            span.setAttribute("gen_ai.tool.name", call.function.name);
            try {
              const args = JSON.parse(call.function.arguments) as { text?: string };
              if (call.function.name !== "word_count") {
                throw new Error(`Unknown tool ${call.function.name}`);
              }
              const count = wordCount(args.text ?? "");
              span.setAttribute("overmind.output", String(count));
              messages.push({
                content: JSON.stringify({ count }),
                role: "tool",
                tool_call_id: call.id,
              });
              console.log(`tool ${call.function.name} ${count}`);
            } catch (error) {
              span.recordException(error as Error);
              span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error).message });
              throw error;
            } finally {
              span.end();
            }
          });
        }
      }
    } catch (error) {
      agent.recordException(error as Error);
      agent.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error).message });
      throw error;
    } finally {
      agent.end();
    }
  });
} finally {
  try {
    await flush();
    console.log("flushed");
  } catch (error) {
    console.error(`flush failed: ${(error as Error).message}`);
  }
  await shutdown();
}