Core

Writing an adapter

Turn any agent stack's tool loop into a Viewport trajectory with TrajectoryRecorder, spans and recorded tools.

An adapter translates one agent stack (a framework's callbacks, a provider's message stream, a plain tool-use loop) into core shapes. Evals, HITL and Context then work on top of it unchanged. Three pieces cover most adapters:

  1. Wrap the stack's tools with wrap_tool / wrapTool so tool calls record themselves and middlewares apply.
  2. Emit a model_call event per model round trip, with usage normalized (input_tokens includes cache reads and writes).
  3. Collect with trace(), or with a TrajectoryRecorder you own when the stack drives the lifecycle.

This guide builds an adapter for a plain tool-use loop around a scripted model, so it runs with no API key. The same shape works for any provider SDK.

main.py
import asyncio
from typing import Any

from viewportai.core import (
    ModelCallEvent,
    ToolContext,
    TrajectoryRecorder,
    Usage,
    emit,
    stable_json,
    tool,
    with_sink,
    wrap_tool,
)

# A scripted "model": first asks for a tool, then answers.
SCRIPT: list[dict[str, Any]] = [
    {"tool": {"id": "toolu_1", "name": "lookup_order", "input": {"order_id": "A-1001"}}, "usage": (120, 12, 100)},
    {"text": "Your order shipped.", "usage": (180, 8, 120)},
]


@tool
async def lookup_order(order_id: str) -> dict[str, str]:
    """Look up an order."""
    return {"order_id": order_id, "status": "shipped"}


async def run_agent(prompt: str, recorder: TrajectoryRecorder) -> str:
    tools = {"lookup_order": wrap_tool(lookup_order)}
    with with_sink(recorder):
        for step, reply in enumerate(SCRIPT):
            fresh, output, cached = reply["usage"]
            usage = Usage(input_tokens=fresh + cached, output_tokens=output, cache_read_tokens=cached)
            emit(ModelCallEvent(model="scripted-1", provider="example", turn=0, step=step, usage=usage))
            if "tool" in reply:
                call = reply["tool"]
                await tools[call["name"]].execute(call["input"], ToolContext(call_id=call["id"]))
            else:
                return reply["text"]
    raise RuntimeError("model never answered")


async def main() -> None:
    recorder = TrajectoryRecorder(input="Where is A-1001?")
    answer = await run_agent("Where is A-1001?", recorder)
    t = recorder.finish(output=answer)
    print(stable_json([e.type for e in t.events]))  # ["model_call","tool_call","model_call"]
    print(t.tool_calls()[0].call_id)  # toolu_1
    print(t.summarize().input_tokens)  # 520: cache reads included


asyncio.run(main())
main.ts
import { defineTool, emit, stableJson, summarize, type Tool, TrajectoryRecorder, toolCalls, withSink, wrapTool } from "@viewportai/core";

type Reply = { tool?: { id: string; name: string; input: Record<string, unknown> }; text?: string; usage: [number, number, number] };
const SCRIPT: Reply[] = [
  { tool: { id: "toolu_1", name: "lookup_order", input: { order_id: "A-1001" } }, usage: [120, 12, 100] },
  { text: "Your order shipped.", usage: [180, 8, 120] },
];

const lookupOrder = defineTool({
  name: "lookup_order",
  input_schema: { type: "object", properties: { order_id: { type: "string" } }, required: ["order_id"] },
  execute: async ({ order_id }) => ({ order_id, status: "shipped" }),
});

async function runAgent(recorder: TrajectoryRecorder): Promise<string> {
  const tools: Record<string, Tool> = { lookup_order: wrapTool(lookupOrder) };
  return withSink(recorder, async () => {
    for (const [step, reply] of SCRIPT.entries()) {
      const [fresh, output, cached] = reply.usage;
      emit({
        type: "model_call",
        model: "scripted-1",
        provider: "example",
        turn: 0,
        step,
        usage: { input_tokens: fresh + cached, output_tokens: output, cache_read_tokens: cached },
      });
      if (reply.tool) await tools[reply.tool.name]?.execute(reply.tool.input, { callId: reply.tool.id });
      else return reply.text ?? "";
    }
    throw new Error("model never answered");
  });
}

const recorder = new TrajectoryRecorder({ input: "Where is A-1001?" });
const t = recorder.finish({ output: await runAgent(recorder) });
console.log(stableJson(t.events.map((e) => e.type))); // ["model_call","tool_call","model_call"]
console.log(toolCalls(t)[0]?.call_id); // toolu_1
console.log(summarize(t).input_tokens); // 520: cache reads included

Checklist for a production adapter:

  • Normalize usage once, in the adapter: Anthropic reports cache reads separately from input_tokens; add them.
  • Keep the provider's ids: call_id on tool calls, response_id on model calls (used to dedupe).
  • Set turn (conversation turn) and step (round trip within the turn) when the stack exposes them.
  • Never transform user payloads: tool args and result go in as the stack produced them.
  • Ship a scripted fake of the stack's model client in your package's testing module, so users can test offline.