翻篇收录说明
翻篇网页快照

UI | AI SDK

https://ai-sdk.dev/docs/ai-sdk-harnesses/ui

最近抓取:2026-12-04 03:03:14(北京时间)

最近内容变化:2026-11-30 23:36:48(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Use AI SDK harnesses with useChat.

正文摘录

AI SDK HarnessesMenuUICopy for LLMView MarkdownAsk AI about this pageHarness streams are compatible with AI SDK UI message streams. You can use useChat() on the client and stream HarnessAgent output from a server route. The important difference from model-based chat routes is session management. A harness owns its conversation state, so the route should resume or create a HarnessAgentSession for the chat id instead of replaying the whole UI message history into a model. Client app/page.tsx'use client'; import { useChat } from '@ai-sdk/react'; import { DefaultChatTransport } from 'ai'; import { useState } from 'react'; export default function Page() { const [input, setInput] = useState(''); const { error, messages, sendMessage, status } = useChat({ id: 'example-chat', transport: new DefaultChatTransport({ api: '/api/chat', }), }); return ( <> {messages.map(message => ( <div key={message.id}> <strong>{message.role === 'user' ? 'You: ' : 'AI: '}</strong> {message.parts.map((part, index) => { if (part.type === 'text') { return <span key={index}>{part.text}</span>; } if (part.type.startsWith('tool-') || part.type === 'dynamic-tool') { return <pre key={index}>{JSON.stringify(part, null, 2)}</pre>; } return null; })} </div> ))} {error && <div>{error.message}</div>} <form onSubmit={event => { event.preventDefault(); if (input.trim()) { sendMessage({ text: input }); setInput(''); } }} > <input value={input} onChange={event => setInput(event.target.value)} disabled={status !== 'ready'} /> <button type="submit" disabled={status !== 'ready'}> Send </button> </form> </> ); } Agent Define the HarnessAgent on the server: app/api/chat/agent.tsimport { HarnessAgent } from '@ai-sdk/harness/agent'; import { claudeCode } from '@ai-sdk/harness-claude-code'; export const agent = new HarnessAgent({ harness: claudeCode, instructions: 'You are a helpful coding assistant.', }); Session Store Persist the opaque resume state returned by session.detach(). If the turn paused for approval or was otherwise interrupted, that resume state carries the continuation state internally. The chat ID can also be the harness sessionId. Here we derive a stable sandboxId from that known chat id. If you do not derive one, persist the returned sandboxSession.id separately. app/api/chat/session-store.tsimport type { HarnessAgentResumeSessionState } from '@ai-sdk/harness/agent'; import { createVercelNetworkSandboxSession, resumeVercelNetworkSandboxSession, } from '@ai-sdk/sandbox-vercel'; const states: Record<string, HarnessAgentResumeSessionState | undefined> = {}; export async function resumeOrCreateSession({ agent, chatId, }: { agent: typeof import('./agent').agent; chatId: string; }) { const resumeFrom = states[chatId]; const sandboxId = `harness-${chatId}`; const sandboxSession = resumeFrom ? await resumeVercelNetworkSandboxSession({ sandboxId }) : await createVercelNetworkSandboxSession({ sandboxId, runtime: 'node24', ports: [4000], template: await agent.getSandboxTemplate(), }); const session = await agent.createSession({ sessionId: chatId, resumeFrom, sandboxSession, }); return { session, sandboxSession }; } export async function detachAndPersist({ chatId, session, }: { chatId: string; session: Awaited<ReturnType<typeof resumeOrCreateSession>>['session']; }) { states[chatId] = await session.detach(); } Use durable storage instead of an in-memory map in production. The creator always creates a new sandbox and fails on a conflicting sandboxId; only the resume function reattaches an existing one. Route Convert UI messages to model messages, run the harness turn, and convert the result stream back to a UI message stream: app/api/chat/route.tsimport { agent } from './agent'; import { detachAndPersist, resumeOrCreateSession } from './session-store'; import { getHarnessErrorMessage } from '@ai-sdk/harness/agent'; import { convertToModelMessages, createUIMessageStream, createUIMessageStreamResponse, toUIMessageStream, type UIMessage, } from 'ai'; export async function POST(request: Request) { const body: { id?: string; messages: UIMessage[]; } = await request.json(); if (!body.id) { return new Response('Missing chat ID', { status: 400 }); } const chatId = body.id; const messages = await convertToModelMessages(body.messages); return createUIMessageStreamResponse({ stream: createUIMessageStream({ execute: async ({ writer }) => { const { session } = await resumeOrCreateSession({ agent, chatId }); const result = await agent.stream({ session, messages }); writer.merge( toUIMessageStream({ stream: result.stream, onError: getHarnessErrorMessage, onEnd: async () => { await detachAndPersist({ chatId, session }); }, }), ); }, onError: getHarnessErrorMessage, }), }); } Creating the UI message stream before acquiring the session ensures sandbox, bootstrap, and harness startup failures are sent as UI error parts instead of becoming generic HTTP errors. getHarnessErrorMessage preserves reviewed, client-safe harness messages and masks unknown server errors. Because the route passes onError, it also formats the errors of failed host tool calls that the harness reports itself. Set redactToolErrors: false to send those error texts unchanged. See Errors for details. Do not use createAgentUIStreamResponse directly with HarnessAgent unless you wrap the agent to inject the required session. HarnessAgent.stream() requires session on every call. Detach or Stop Use session.detach() when you want to park the harness runtime and keep the sandbox warm for the next request. Bridge-backed adapters can usually reattach or replay efficiently. If the turn is unfinished, detach() includes the turn continuation state in the returned resume state. session.stop() saves resume state and stops the harness runtime, but does not stop a supplied sandbox. The caller owns that network session and should call its destroy() method when the chat ends, not while a later request needs to reattach. Preserve the chosen sandboxId across processes. Rendering Harness Parts Harness output contains the same UI message part shapes used by AI SDK model streams: text and reasoning parts for generated content. typed tool parts such as tool-bash, tool-read, or a host tool like tool-weather. dynamic-tool parts for dynamic events such as fileChange and compaction. Render typed harness built-ins the same way you render normal AI SDK tool parts. Check part.state for input-streaming, input-available, and output-available. Type-Safe Tool Parts Until HarnessAgent session options are part of the base Agent call parameters, infer UI tools from agent.tools: import type { InferUITools, UIMessage } from 'ai'; import { agent } from './agent'; export type HarnessMessage = UIMessage< unknown, never, InferUITools<typeof agent.tools> >; Then use useChat<HarnessMessage>() on the client.PreviousWorkflow UtilitiesNextTerminal UI