camelAI Documentation

Start Here

Build an AI agent chat app with camelRun v2

Stream a camelRun v2 agent into a web app using server routes, SSE (?after=...&follow=1), scoped agent tokens, and human inputs.

View as Markdown

To build a chat UI backed by camelRun v2, map each user conversation or thread to a keyed agent (PUT /v2/agents/:key), start runs with wait: false from your backend, and stream live events to the browser over Server-Sent Events (SSE) or WebSocket.

Your tenant API key (cr_live_...) always stays on your server.

Architecture

  1. Provision the thread's agent on your server with client.agents.upsert("thread-" + threadId, config). Upserting is idempotent and returns the agent's id and scoped agentToken (agt_tok_...).
  2. Load chat history from GET /v2/agents/:idOrKey/history?before=latest&limit=50.
  3. Send messages through your server (POST /v2/agents/:idOrKey/runs with wait: false, an idempotencyKey, and optional actor and spendLimitUsd).
  4. Stream live events from GET /v2/agents/:idOrKey/events?after=<cursor>&follow=1 with Accept: text/event-stream.
  5. Answer pending approvals or questions through your server via POST /v2/agents/:idOrKey/inputs/:inputId.

Use a server-side proxy for browser requests whenever you set actor on runs or respond to signed MCP tool approvals (auth: { type: "runtime" }). Those operations require your tenant API key (cr_live_...), which must never be exposed to browsers. Scoped agent tokens (agt_tok_...) can read history, stream events, start non-actor runs, and answer standard ask_human / requiresApproval inputs for that single agent, and cannot delete the agent or modify its configuration.

1. Server routes

Below is a minimal backend (Next.js App Router, Cloudflare Worker, or Express) using @camelai/run for mutations and proxying SSE cleanly to the browser:

server/chat-routes.ts
import { CamelRun } from "@camelai/run";

const BASE_URL = process.env.CAMELRUN_BASE_URL ?? "https://run.camelai.com";
const API_KEY = process.env.CAMELRUN_API_KEY!;
const client = new CamelRun({ baseUrl: BASE_URL, apiKey: API_KEY });

async function ensureThreadAgent(userId: string, threadId: string) {
  return client.agents.upsert(`thread-${threadId}`, {
    model: "azure/gpt-6.2-sol",
    instructions: "You are a helpful product assistant.",
    builtins: ["files", "web_search", "human"],
    toolIdentity: {
      subject: userId,
      context: { threadId },
    },
    queue: { mode: "each" },
  });
}

// GET /api/threads/:threadId/history
export async function getHistory(userId: string, threadId: string, before?: string) {
  const agent = await ensureThreadAgent(userId, threadId);
  const messages = await agent.history({
    before: before ? (before === "latest" ? "latest" : Number(before)) : "latest",
    limit: 50,
  });
  return Response.json({ agentId: agent.id, messages });
}

// POST /api/threads/:threadId/messages
export async function sendMessage(
  userId: string,
  threadId: string,
  body: { prompt: string; idempotencyKey?: string; whileRunning?: "queue" | "steer" },
) {
  const agent = await ensureThreadAgent(userId, threadId);
  const run = await agent.submit(body.prompt, {
    actor: userId,
    idempotencyKey: body.idempotencyKey,
    whileRunning: body.whileRunning ?? "queue",
    // Per-run spendLimitUsd requires whileRunning: "queue"
    ...(body.whileRunning !== "steer" ? { spendLimitUsd: 0.5 } : {}),
  });
  return Response.json(run);
}

// GET /api/threads/:threadId/events?after=0
export async function streamThreadEvents(
  request: Request,
  userId: string,
  threadId: string,
) {
  const agent = await ensureThreadAgent(userId, threadId);
  const url = new URL(request.url);
  const after = request.headers.get("Last-Event-ID") ?? url.searchParams.get("after") ?? "0";

  const upstream = await fetch(
    `${BASE_URL}/v2/agents/${encodeURIComponent(agent.id)}/events?after=${encodeURIComponent(after)}&follow=1`,
    {
      headers: {
        Authorization: `Bearer ${API_KEY}`,
        Accept: "text/event-stream",
      },
      signal: request.signal,
    },
  );

  return new Response(upstream.body, {
    status: upstream.status,
    headers: {
      "Content-Type": "text/event-stream; charset=utf-8",
      "Cache-Control": "no-cache, no-transform",
      "X-Accel-Buffering": "no",
    },
  });
}

// POST /api/threads/:threadId/inputs/:inputId
export async function answerInput(
  userId: string,
  threadId: string,
  inputId: string,
  body: { approved?: boolean; answer?: unknown },
) {
  const agent = await ensureThreadAgent(userId, threadId);
  const run = await agent.answerInput(inputId, {
    approved: body.approved,
    answer: body.answer,
    actor: userId,
    wait: false,
  });
  return Response.json(run);
}

Direct browser streaming with a scoped agent token

If your app does not need server-enforced actor claims or signed MCP tool approvals, your backend can hand the browser the agent's scoped token (agent.agentToken) and let the browser open EventSource directly using the ?token= query parameter supported on /v2/agents/:idOrKey/events and /v2/agents/:idOrKey/ws:

ts
const es = new EventSource(
  `https://run.camelai.com/v2/agents/${encodeURIComponent(agentId)}/events?after=${cursor}&follow=1&token=${encodeURIComponent(agentToken)}`,
);

2. Browser client

Subscribe to the SSE endpoint using standard EventSource. Each SSE frame includes id: <seq>, event: <type>, and data: <JSON AgentEventRecord>. Reconnecting with Last-Event-ID or ?after=<lastSeq> replays missed events without gaps.

components/ThreadChat.tsx
import { useEffect, useRef, useState } from "react";

type ChatMessage = {
  seq?: number;
  role: "user" | "assistant" | "tool" | "system";
  content: { text?: string };
};

export function ThreadChat({ threadId }: { threadId: string }) {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [draft, setDraft] = useState("");
  const [streamingText, setStreamingText] = useState("");
  const [pendingInput, setPendingInput] = useState<{
    id: string;
    kind: string;
    prompt: Record<string, unknown>;
  } | null>(null);
  const lastSeqRef = useRef(0);

  useEffect(() => {
    let active = true;

    async function loadAndConnect() {
      const histRes = await fetch(`/api/threads/${threadId}/history`);
      const hist = await histRes.json();
      if (!active) return;
      setMessages(hist.messages ?? []);

      const es = new EventSource(
        `/api/threads/${threadId}/events?after=${lastSeqRef.current}`,
      );

      es.addEventListener("text_delta", (ev) => {
        const parsed = JSON.parse((ev as MessageEvent).data);
        lastSeqRef.current = Math.max(lastSeqRef.current, parsed.seq ?? 0);
        setStreamingText((prev) => prev + (parsed.data?.delta ?? ""));
      });

      es.addEventListener("input_required", (ev) => {
        const parsed = JSON.parse((ev as MessageEvent).data);
        lastSeqRef.current = Math.max(lastSeqRef.current, parsed.seq ?? 0);
        setPendingInput(parsed.data?.input ?? null);
      });

      es.addEventListener("run_completed", (ev) => {
        const parsed = JSON.parse((ev as MessageEvent).data);
        lastSeqRef.current = Math.max(lastSeqRef.current, parsed.seq ?? 0);
        const finalText = parsed.data?.text ?? "";
        setStreamingText("");
        setPendingInput(null);
        if (finalText) {
          setMessages((prev) => [...prev, { role: "assistant", content: { text: finalText } }]);
        }
      });

      return () => es.close();
    }

    let cleanup: (() => void) | undefined;
    void loadAndConnect().then((fn) => {
      cleanup = fn;
    });
    return () => {
      active = false;
      cleanup?.();
    };
  }, [threadId]);

  async function onSend(e: React.FormEvent) {
    e.preventDefault();
    const text = draft.trim();
    if (!text) return;
    setDraft("");
    setMessages((prev) => [...prev, { role: "user", content: { text } }]);

    await fetch(`/api/threads/${threadId}/messages`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ prompt: text, idempotencyKey: crypto.randomUUID() }),
    });
  }

  async function onAnswer(approved: boolean, answer?: unknown) {
    if (!pendingInput) return;
    await fetch(`/api/threads/${threadId}/inputs/${pendingInput.id}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ approved, answer }),
    });
    setPendingInput(null);
  }

  return (
    <div>
      {messages.map((m, i) => (
        <div key={m.seq ?? i}>
          <strong>{m.role}:</strong> {m.content?.text}
        </div>
      ))}
      {streamingText && (
        <div>
          <strong>assistant:</strong> {streamingText}
        </div>
      )}
      {pendingInput && (
        <div>
          <p>{String(pendingInput.prompt?.question ?? "Approval required")}</p>
          <button onClick={() => onAnswer(true, "Approved")}>Approve</button>
          <button onClick={() => onAnswer(false)}>Decline</button>
        </div>
      )}
      <form onSubmit={onSend}>
        <input value={draft} onChange={(e) => setDraft(e.target.value)} placeholder="Ask something..." />
        <button type="submit">Send</button>
      </form>
    </div>
  );
}

Handling reconnects and active runs

  • Initial cursor: If you only want new events after loading history, query GET /v2/agents/:idOrKey/events?after=latest (without Accept: text/event-stream) to get { events: [], nextAfter }, then connect SSE with ?after=<nextAfter>&follow=1.
  • In-flight state: Call GET /v2/agents/:idOrKey/runs on page load to get { cursor, activeRunId, runs } and GET /v2/agents/:idOrKey/inputs to show any pending approvals or questions from an earlier session.
  • Attachments: Upload user files to the agent's CamelFS repo first via POST /v2/repos/:repoId/write, then pass files: [{ path, commit, contentType }] in POST /v2/agents/:idOrKey/runs. See Files and CamelFS.
  • Aborting a reply: Wire a Stop button to POST /v2/agents/:idOrKey/abort (agent.abort()).