Open History to see the last commit
1---
2title: "@tanstack/ai"
3id: tanstack-ai-api
4order: 1
5description: "API reference for @tanstack/ai, the core TanStack AI library providing chat(), decide(), generateImage(), toolDefinition(), and streaming utilities."
6keywords:
7 - tanstack ai
8 - "@tanstack/ai"
9 - api reference
10 - chat
11 - toolDefinition
12 - generateImage
13 - decide
14 - core library
15---
16
17The core AI library for TanStack AI.
18
19## Installation
20
21<!-- ::start:tabs variant="package-manager" mode="install" -->
22
23react: @tanstack/ai
24vue: @tanstack/ai
25solid: @tanstack/ai
26svelte: @tanstack/ai
27preact: @tanstack/ai
28angular: @tanstack/ai
29vanilla: @tanstack/ai
30octane: @tanstack/ai
31
32<!-- ::end:tabs -->
33
34## `chat(options)`
35
36Creates a streaming chat response.
37
38```typescript
39import { chat, maxIterations } from "@tanstack/ai";
40import { openaiText } from "@tanstack/ai-openai";
41import { myTool } from "./tools";
42
43const stream = chat({
44 adapter: openaiText("gpt-5.2"),
45 messages: [{ role: "user", content: "Hello!" }],
46 tools: [myTool],
47 systemPrompts: ["You are a helpful assistant"],
48 agentLoopStrategy: maxIterations(20),
49});
50```
51
52### Parameters
53
54- `adapter` - An AI adapter instance with model (e.g., `openaiText('gpt-5.2')`, `anthropicText('claude-sonnet-4-5')`)
55- `messages` - Array of chat messages. Accepts mixed `UIMessage | ModelMessage` arrays — internal conversion handles AG-UI fan-out dedup, drops `reasoning`/`activity`, and collapses `developer` → `system`
56- `tools?` - Array of tools for function calling
57- `context?` - Typed runtime context passed to server tools and middleware. If a tool or middleware declares a concrete context type, `chat()` requires a compatible value here
58- `systemPrompts?` - System prompts to prepend to messages
59- `agentLoopStrategy?` - Strategy for agent loops (default: `maxIterations(5)`). Strategies receive `{ iterationCount, finishReason, messages, toolCallCount, lastTurnToolCallCount }` and run between model turns. Iterations are model turns, not tool calls — for tool-call budgets use middleware (`onBeforeToolCall` + `onShouldContinue`); see [Tool-call budgets](../chat/agentic-cycle#tool-call-budgets-middleware-recipe).
60- `middleware?` - Array of chat middleware. Use `onShouldContinue` / `onBeforeToolCall` for app-owned tool budgets.
61- `abortController?` - AbortController for cancellation
62- `modelOptions?` - Provider-native model options. This is where sampling parameters live — `temperature`, `top_p`/`topP`, and the provider's token-limit key (`max_output_tokens`, `max_tokens`, `maxOutputTokens`, …) — under each provider's canonical name, rather than as generic root-level props. See [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options). (Renamed from `providerOptions`.)
63- `threadId?` - AG-UI thread identifier propagated into `RUN_STARTED` events for run correlation
64- `runId?` - AG-UI run identifier (auto-generated if omitted)
65- `parentRunId?` - AG-UI parent run identifier for nested runs
66
67### Returns
68
69An async iterable of `StreamChunk`.
70
71## `summarize(options)`
72
73Creates a text summarization.
74
75```typescript
76import { summarize } from "@tanstack/ai";
77import { openaiSummarize } from "@tanstack/ai-openai";
78
79const result = await summarize({
80 adapter: openaiSummarize("gpt-5.2"),
81 text: "Long text to summarize...",
82 maxLength: 100,
83 style: "concise",
84});
85```
86
87### Parameters
88
89- `adapter` - An AI adapter instance with model
90- `text` - Text to summarize
91- `maxLength?` - Maximum length of summary
92- `style?` - Summary style ("concise" | "detailed")
93- `modelOptions?` - Model-specific options
94
95### Returns
96
97A `SummarizationResult` with the summary text.
98
99## `decide(options)`
100
101Asks typed questions about a shared state and returns answers your code can
102branch on. This call is async. There is no stream.
103
104```typescript
105import { decide, choice, score, boolean } from "@tanstack/ai";
106import { typesafeDecider } from "@tanstack/ai-typesafe";
107
108const ticket = {
109 subject: "Charged twice for the same invoice",
110 body: "Please refund the extra payment.",
111};
112
113const result = await decide({
114 adapter: typesafeDecider("jev-latest"),
115 state: ticket,
116 questions: {
117 queue: choice({
118 instructions: "Which team should handle this ticket?",
119 options: {
120 billing: "Payments, invoices, refunds",
121 tech: "Bugs, outages, integrations",
122 sales: "Pricing, upgrades, new accounts",
123 },
124 }),
125 urgency: score({
126 instructions: "How urgent is this ticket?",
127 levels: ["low", "medium", "high"],
128 }),
129 refund: boolean({
130 instructions: "Is the customer asking for a refund?",
131 }),
132 },
133});
134
135console.log(result.queue.value);
136console.log(result.queue.probability);
137console.log(result.queue.confidence);
138console.log(result.meta.usage);
139```
140
141### Parameters (`decide`)
142
143Required:
144
145- `adapter` - An evaluate adapter created with a model (for example `typesafeDecider('jev-latest')`)
146- `state` - Shared content every question judges. A string, an object, or an array. An array is one state, not a batch.
147- `questions` - Map of `choice`, `score`, and `boolean` questions. The key `meta` is reserved.
148
149Optional:
150
151- `abortSignal?` - Cancel the in-flight request
152- `modelOptions?` - Provider-specific options
153- `middleware?` - Observe-only generation middleware
154- `debug?` - Debug logging
155
156### Returns
157
158Each question key is a top-level answer. `meta.model` and `meta.usage` hold the resolved model id and token usage. When the adapter returns them, `meta.id` holds the provider response id and `meta.provider` names the upstream provider.
159
160- `choice`: `.value` is the selected option key. `.probability` is P(selected). `.confidence` is a number from 0 to 1. `.probabilities` is the full map.
161- `score`: `.value` is the nearest level label. `.score` is the raw fraction. `.probability` is P(that level). `.confidence` is a number from 0 to 1. `.legend` maps each level index to its label. `.probabilities` is the full map, keyed by level index.
162- `boolean`: When `.probability` is 0.5 or more, `.value` is `true`. No `.confidence`.
163
164### Helpers
165
166- `choice({ instructions, options })` - Pick one key from `options`
167- `score({ instructions, levels })` - Rate `state` on ordered `levels` (at least two)
168- `boolean({ instructions, criteria? })` - Yes or no. When P(true) is 0.5 or more, `.value` is `true`
169
170See [Evaluate](../evaluate/evaluate) for adapters, abort, and middleware.
171
172## `toolDefinition(config)`
173
174Creates an isomorphic tool definition that can be instantiated for server or client execution.
175
176```typescript
177import { chat, toolDefinition } from "@tanstack/ai";
178import { openaiText } from "@tanstack/ai-openai";
179import { z } from "zod";
180
181const myToolDef = toolDefinition({
182 name: "my_tool",
183 description: "Tool description",
184 inputSchema: z.object({
185 param: z.string(),
186 }),
187 outputSchema: z.object({
188 result: z.string(),
189 }),
190 needsApproval: false, // Optional
191});
192
193// Or create client implementation
194const myClientTool = myToolDef.client(async ({ param }) => {
195 // Client-side implementation
196 return { result: "..." };
197});
198
199// Use directly in chat() (server-side, no execute)
200chat({
201 adapter: openaiText("gpt-5.2"),
202 tools: [myToolDef],
203 messages: [{ role: "user", content: "..." }],
204});
205
206// Or create server implementation
207const myServerTool = myToolDef.server(async ({ param }) => {
208 // Server-side implementation
209 return { result: "..." };
210});
211
212// Use directly in chat() (server-side, no execute)
213chat({
214 adapter: openaiText("gpt-5.2"),
215 tools: [myServerTool],
216 messages: [{ role: "user", content: "..." }],
217});
218```
219
220Tools can declare typed runtime context for request-scoped dependencies:
221
222```typescript
223import { chat, toolDefinition, toServerSentEventsResponse } from "@tanstack/ai";
224import { openaiText } from "@tanstack/ai-openai";
225import { session, db } from "./app";
226
227type AppContext = {
228 userId: string;
229 db: { users: { findName(id: string): Promise<string> } };
230};
231
232const currentUser = toolDefinition({
233 name: "current_user",
234 description: "Get the current user",
235}).server<AppContext>(async (_input: unknown, ctx) => {
236 return { name: await ctx.context.db.users.findName(ctx.context.userId) };
237});
238
239export async function POST(request: Request) {
240 const { messages } = await request.json();
241 const stream = chat({
242 adapter: openaiText("gpt-5.2"),
243 messages,
244 tools: [currentUser],
245 context: { userId: session.user.id, db },
246 });
247 return toServerSentEventsResponse(stream);
248}
249```
250
251### Parameters
252
253- `name` - Tool name (must be unique)
254- `description` - Tool description for the model
255- `inputSchema` - Zod schema for input validation
256- `outputSchema?` - Zod schema for output validation
257- `needsApproval?` - Whether tool requires user approval
258- `metadata?` - Additional metadata
259
260### Returns
261
262A `ToolDefinition` object with `.server()` and `.client()` methods for creating concrete implementations.
263
264## `toServerSentEventsStream(stream, abortController?)`
265
266Converts a stream to a ReadableStream in Server-Sent Events format.
267
268```typescript
269import { chat, toServerSentEventsStream } from "@tanstack/ai";
270import { openaiText } from "@tanstack/ai-openai";
271
272const stream = chat({
273 adapter: openaiText("gpt-5.2"),
274 messages: [{ role: "user", content: "Hello!" }],
275});
276const readableStream = toServerSentEventsStream(stream);
277```
278
279### Parameters
280
281- `stream` - Async iterable of `StreamChunk`
282- `abortController?` - Optional AbortController to abort when stream is cancelled
283
284### Returns
285
286A `ReadableStream<Uint8Array>` in Server-Sent Events format. Each chunk is:
287- Prefixed with `"data: "`
288- Followed by `"\n\n"`
289- Stream ends with `"data: [DONE]\n\n"`
290
291## `toServerSentEventsResponse(stream, init?)`
292
293Converts a stream to an HTTP Response with proper SSE headers.
294
295```typescript
296import { chat, toServerSentEventsResponse } from "@tanstack/ai";
297import { openaiText } from "@tanstack/ai-openai";
298
299async function POST() {
300 const stream = chat({
301 adapter: openaiText("gpt-5.2"),
302 messages: [{ role: "user", content: "Hello!" }],
303 });
304 return toServerSentEventsResponse(stream);
305}
306```
307
308### Parameters
309
310- `stream` - Async iterable of `StreamChunk`
311- `init?` - Optional ResponseInit options (including `abortController`)
312
313### Returns
314
315A `Response` object suitable for HTTP endpoints with SSE headers (`Content-Type: text/event-stream`, `Cache-Control: no-cache`, `Connection: keep-alive`).
316
317## `chatParamsFromRequest(req)`
318
319Reads an HTTP `Request`, parses its JSON body, and validates it against AG-UI `RunAgentInputSchema`. Returns parsed chat parameters ready to spread into `chat()`. On a malformed body, **throws a 400 `Response`** that frameworks like TanStack Start, SolidStart, Remix, and React Router 7 return to the client automatically.
320
321```typescript
322import { chat, chatParamsFromRequest, toServerSentEventsResponse } from "@tanstack/ai";
323import { openaiText } from "@tanstack/ai-openai";
324import { serverTools } from "./tools";
325
326export async function POST(req: Request) {
327 const params = await chatParamsFromRequest(req);
328 const stream = chat({
329 adapter: openaiText("gpt-5.5"),
330 messages: params.messages,
331 tools: serverTools,
332 });
333 return toServerSentEventsResponse(stream);
334}
335```
336
337### Parameters
338
339- `req` - An incoming `Request` whose JSON body conforms to AG-UI `RunAgentInput`
340
341### Returns
342
343A promise resolving to `{ messages, threadId, runId, parentRunId?, tools, forwardedProps, state, aguiContext, context }`.
344
345The returned `aguiContext` is the AG-UI protocol `RunAgentInput.context` field. It is not the same as TanStack AI runtime `chat({ context })`; validate and map it explicitly if you want those values available to tools or middleware.
346
347The returned `context` field is a deprecated alias of `aguiContext` kept for backward compatibility. Prefer `aguiContext` in new code.
348
349> **Framework note.** Next.js Route Handlers, SvelteKit, Hono, and raw Node do not auto-handle thrown `Response` objects. In those, wrap with try/catch or use `chatParamsFromRequestBody(await req.json())` directly.
350
351## `chatParamsFromRequestBody(body)`
352
353Lower-level variant of `chatParamsFromRequest` that validates an already-parsed body. Rejects with an `AGUIError` on malformed input. Use this when you need explicit error handling control.
354
355```typescript
356import { chatParamsFromRequestBody } from "@tanstack/ai";
357
358async function handler(req: Request): Promise<Response> {
359 const body = await req.json();
360 try {
361 const params = await chatParamsFromRequestBody(body);
362 // ...
363 return new Response("ok");
364 } catch (error) {
365 const message = error instanceof Error ? error.message : String(error);
366 return new Response(message, { status: 400 });
367 }
368}
369```
370
371## `mergeAgentTools(serverTools, clientTools)`
372
373Merges a server-side tool registry with the AG-UI client-declared tools received in the request payload. Server tools win on name collision; client-only tools become no-execute stubs that the runtime dispatches via `ClientToolRequest` events.
374
375```typescript
376import { chat, chatParamsFromRequest, mergeAgentTools } from "@tanstack/ai";
377import { openaiText } from "@tanstack/ai-openai";
378import { serverTools } from "./tools";
379
380async function handler(req: Request) {
381 const params = await chatParamsFromRequest(req);
382 const stream = chat({
383 adapter: openaiText("gpt-5.5"),
384 messages: params.messages,
385 tools: mergeAgentTools(serverTools, params.tools),
386 });
387}
388```
389
390### Parameters
391
392- `serverTools` - The server's `toolDefinition().server(...)` registry, keyed by tool name
393- `clientTools` - The `tools` array from `chatParamsFromRequest`'s return value
394
395### Returns
396
397A merged tool record suitable for `chat({ tools })`.
398
399## `maxIterations(count)`
400
401Creates an agent loop strategy that limits **model turns** (iterations), not tool calls. One turn can still emit many parallel tool calls — use middleware for tool-call budgets ([recipe](../chat/agentic-cycle#tool-call-budgets-middleware-recipe)).
402
403```typescript
404import { chat, maxIterations } from "@tanstack/ai";
405import { openaiText } from "@tanstack/ai-openai";
406
407const stream = chat({
408 adapter: openaiText("gpt-5.2"),
409 messages: [{ role: "user", content: "Hello!" }],
410 agentLoopStrategy: maxIterations(20),
411});
412```
413
414### Parameters
415
416- `count` - Maximum number of model turns
417
418### Returns
419
420An `AgentLoopStrategy` function.
421
422## `defineByokProvider({ id, label, env?, with? })`
423
424Declare a BYOK provider from an adapter package. `id` is the `x-byok-<id>` slug and is **required** — an optional or missing `id` does not type-check.
425
426```typescript
427import { defineByokProvider } from "@tanstack/ai/byok";
428
429export const openaiByok = defineByokProvider({
430 id: "openai",
431 label: "OpenAI",
432 env: "OPENAI_API_KEY",
433});
434```
435
436Import the object from the adapter `/byok` subpath (`openaiByok` from `@tanstack/ai-openai/byok`). Pass it to `getByokKey` on the relay. Do not import it from the adapter main entry. That pulls in the provider SDK. Import `getByokKey` from `@tanstack/ai/byok/server`. That entry is the only BYOK module that reads `process.env`.
437
438### Parameters
439
440- `id` - Required slug (`[a-z][a-z0-9-]{0,63}`)
441- `label` - Display name
442- `env?` - Env var **name**, or a list of names tried in order. A string is stored as a one-element array. Names only — this object is imported on the client, so do not put `process.env` values here
443- `with?` - Other descriptors this credential needs, for example an account id next to a token. A store created with `defineByok({ providers })` sends their headers and prompts for them together with this one. Read them on the relay with `getByokKeys`
444
445### Returns
446
447A `{ id, label, env?, with? }` object. `id` is the literal slug type.
448
449## `getByokKey(request, provider)`
450
451Read a key on the relay. Import from `@tanstack/ai/byok/server` so `process.env` is not in the client graph. Works in any API route — it is not a TanStack Start server function.
452
453The header wins. A `ByokProvider` then tries `provider.env` in order. A slug is header-only. Returns `null` when both are empty. The JSON body is ignored.
454
455```typescript
456import { getByokKey } from "@tanstack/ai/byok/server";
457import { openaiByok } from "@tanstack/ai-openai/byok";
458
459export async function POST(request: Request) {
460 const apiKey = getByokKey(request, openaiByok);
461 return new Response(apiKey ? "ok" : "missing");
462}
463```
464
465### Parameters
466
467- `request` - Incoming `Request`
468- `provider` - A `ByokProvider` or a provider slug (`[a-z][a-z0-9-]{0,63}`). Becomes the `x-byok-<slug>` header. Not a fixed catalog.
469
470### Returns
471
472`string | null`
473
474## `getByokKeys(request, providers)`
475
476Read several keys at once. Each entry obeys the same rules as `getByokKey`. Use it when one credential is made of more than one value.
477
478```typescript
479import { byokMissing, getByokKeys } from "@tanstack/ai/byok/server";
480import {
481 cloudflareAccountByok,
482 cloudflareByok,
483} from "@tanstack/ai-cloudflare/byok";
484
485export async function POST(request: Request) {
486 const { apiKey, accountId } = getByokKeys(request, {
487 apiKey: cloudflareByok,
488 accountId: cloudflareAccountByok,
489 });
490 if (!apiKey) return byokMissing(cloudflareByok);
491 if (!accountId) return byokMissing(cloudflareAccountByok);
492 return new Response("ok");
493}
494```
495
496### Parameters
497
498- `request` - Incoming `Request`
499- `providers` - An object whose values are a `ByokProvider` or a provider slug. The keys name the result.
500
501### Returns
502
503An object with the same keys, each `string | null`.
504
505## `byokMissing(provider)`
506
507Return a `401` JSON `Response` with `{ error: { type: "byok_missing", provider, message } }`. The chat and generation clients read this body and set `snapshot.prompt`. Import from `@tanstack/ai/byok` or `@tanstack/ai/byok/server`.
508
509```typescript
510import { byokMissing, getByokKey } from "@tanstack/ai/byok/server";
511import { openaiByok } from "@tanstack/ai-openai/byok";
512
513export async function POST(request: Request) {
514 const apiKey = getByokKey(request, openaiByok);
515 if (!apiKey) return byokMissing(openaiByok);
516 return new Response("ok");
517}
518```
519
520### Parameters
521
522- `provider` - A `ByokProvider` or a provider slug to put on the error body
523
524### Returns
525
526A `Response` with status `401` and `content-type: application/json`.
527
528## `maskKey(key)`
529
530Return the last four characters of a key. Keys of four characters or fewer become `"••"`.
531
532```typescript
533import { maskKey } from "@tanstack/ai/byok";
534
535maskKey("sk-abcdefghij"); // "ghij"
536```
537
538## `scrubSecrets(input, secrets)`
539
540Replace each listed secret in `input` with `[redacted]`. Use this before you log an error string.
541
542```typescript
543import { scrubSecrets } from "@tanstack/ai/byok";
544
545scrubSecrets("failed sk-live extra", ["sk-live"]);
546// "failed [redacted] extra"
547```
548
549See [Bring Your Own Key](../advanced/byok) for the client store and a full relay.
550
551## Types
552
553### `ModelMessage`
554
555```typescript
556import type {
557 ContentPart,
558 StructuredOutputPart,
559 ToolCall,
560} from "@tanstack/ai";
561
562interface ModelMessage<
563 TContent extends string | null | ContentPart[] =
564 | string
565 | null
566 | ContentPart[],
567> {
568 role: "user" | "assistant" | "tool";
569 content: TContent;
570 name?: string;
571 toolCalls?: ToolCall[];
572 toolCallId?: string;
573 thinking?: Array<{ content: string; signature?: string }>;
574 structuredOutput?: StructuredOutputPart;
575 id?: string;
576 createdAt?: Date;
577}
578```
579
580### `StreamChunk`
581
582```typescript ignore
583type StreamChunk =
584 | ContentStreamChunk
585 | ThinkingStreamChunk
586 | ToolCallStreamChunk
587 | ToolResultStreamChunk
588 | DoneStreamChunk
589 | ErrorStreamChunk;
590
591interface ThinkingStreamChunk {
592 type: "thinking";
593 id: string;
594 model: string;
595 timestamp: number;
596 delta?: string; // Incremental thinking token
597 content: string; // Accumulated thinking content
598}
599```
600
601Stream chunks represent different types of data in the stream:
602
603- **Content chunks** - Text content being generated
604- **Thinking chunks** - Model's reasoning process (when supported by the model)
605- **Tool call chunks** - When the model calls a tool
606- **Tool result chunks** - Results from tool execution
607- **Done chunks** - Stream completion
608- **Error chunks** - Stream errors
609
610### `Tool`
611
612```typescript
613import type { SchemaInput, ToolExecutionContext } from "@tanstack/ai";
614
615interface Tool<TContext = unknown> {
616 name: string;
617 description: string;
618 inputSchema?: SchemaInput;
619 outputSchema?: SchemaInput;
620 execute?: (
621 args: any,
622 context?: ToolExecutionContext<TContext>
623 ) => Promise<any> | any;
624 needsApproval?: boolean;
625 lazy?: boolean;
626 metadata?: Record<string, any>;
627}
628```
629
630### `ToolExecutionContext<TContext>`
631
632```typescript ignore
633type ToolExecutionContext<TContext = unknown> = {
634 toolCallId?: string;
635 emitCustomEvent: (
636 eventName: string,
637 value: Record<string, any>,
638 options?: { batch?: boolean },
639 ) => void;
640} & (unknown extends TContext ? { context?: TContext } : { context: TContext });
641```
642
643`context` is the runtime value from `chat({ context })` for server tools, or from `ChatClient` / framework hook options for client tools. It is required when a tool declares a concrete `TContext` and optional for untyped tools where the context type is `unknown`.
644
645### `ChatMiddleware<TContext>`
646
647```typescript
648import type {
649 StreamChunk,
650 ChatMiddlewarePhase,
651 ToolCallHookContext,
652 BeforeToolCallDecision,
653 AfterToolCallInfo,
654 FinishInfo,
655 AbortInfo,
656 ErrorInfo,
657} from "@tanstack/ai";
658
659interface ChatMiddlewareContext<TContext = unknown> {
660 requestId: string;
661 streamId: string;
662 threadId: string;
663 phase: ChatMiddlewarePhase;
664 iteration: number;
665 context: TContext;
666 abort(reason?: string): void;
667 defer(promise: Promise<unknown>): void;
668}
669
670interface ChatMiddleware<TContext = unknown> {
671 name?: string;
672 onStart?: (ctx: ChatMiddlewareContext<TContext>) => void | Promise<void>;
673 onChunk?: (
674 ctx: ChatMiddlewareContext<TContext>,
675 chunk: StreamChunk
676 ) => void | StreamChunk | StreamChunk[] | null | Promise<void | StreamChunk | StreamChunk[] | null>;
677 onBeforeToolCall?: (
678 ctx: ChatMiddlewareContext<TContext>,
679 hookCtx: ToolCallHookContext
680 ) => BeforeToolCallDecision | Promise<BeforeToolCallDecision>;
681 onAfterToolCall?: (
682 ctx: ChatMiddlewareContext<TContext>,
683 info: AfterToolCallInfo
684 ) => void | Promise<void>;
685 onFinish?: (
686 ctx: ChatMiddlewareContext<TContext>,
687 info: FinishInfo
688 ) => void | Promise<void>;
689 onAbort?: (
690 ctx: ChatMiddlewareContext<TContext>,
691 info: AbortInfo
692 ) => void | Promise<void>;
693 onError?: (
694 ctx: ChatMiddlewareContext<TContext>,
695 info: ErrorInfo
696 ) => void | Promise<void>;
697}
698```
699
700See [Runtime Context](../advanced/runtime-context) for the recommended context patterns.
701
702## Usage Examples
703
704```typescript
705import { chat, summarize, generateImage, toolDefinition } from "@tanstack/ai";
706import {
707 openaiText,
708 openaiSummarize,
709 openaiImage,
710} from "@tanstack/ai-openai";
711import { z } from "zod";
712
713// --- Streaming chat
714const stream = chat({
715 adapter: openaiText("gpt-5.2"),
716 messages: [{ role: "user", content: "Hello!" }],
717});
718
719// --- Structured response with tools
720const weatherTool = toolDefinition({
721 name: "getWeather",
722 description: "Get the current weather for a city",
723 inputSchema: z.object({
724 city: z.string(),
725 }),
726}).server(async ({ city }) => {
727 // Implementation that fetches weather info
728 return JSON.stringify({ temperature: 72, condition: "Sunny" });
729});
730
731async function examples() {
732 // --- One-shot chat response (stream: false)
733 const response = await chat({
734 adapter: openaiText("gpt-5.2"),
735 messages: [{ role: "user", content: "What's the capital of France?" }],
736 stream: false, // Returns a Promise<string> instead of AsyncIterable
737 });
738
739 // --- Structured response with outputSchema
740 const parsed = await chat({
741 adapter: openaiText("gpt-5.2"),
742 messages: [{ role: "user", content: "Summarize this text in JSON with keys 'summary' and 'keywords': ... " }],
743 outputSchema: z.object({
744 summary: z.string(),
745 keywords: z.array(z.string()),
746 }),
747 });
748
749 const toolResult = await chat({
750 adapter: openaiText("gpt-5.2"),
751 messages: [
752 { role: "user", content: "What's the weather in Paris?" }
753 ],
754 tools: [weatherTool],
755 outputSchema: z.object({
756 answer: z.string(),
757 weather: z.object({
758 temperature: z.number(),
759 condition: z.string(),
760 }),
761 }),
762 });
763
764 // --- Summarization
765 const summary = await summarize({
766 adapter: openaiSummarize("gpt-5.2"),
767 text: "Long text to summarize...",
768 maxLength: 100,
769 });
770
771 // --- Image generation
772 const image = await generateImage({
773 adapter: openaiImage("dall-e-3"),
774 prompt: "A futuristic city skyline at sunset",
775 numberOfImages: 1,
776 size: "1024x1024",
777 });
778}
779```
780
781## Next Steps
782
783- [Getting Started](../getting-started/quick-start) - Learn the basics
784- [Bring Your Own Key](../advanced/byok) - Read user keys on the relay
785- [Evaluate](../evaluate/evaluate) - Ask typed questions about shared state
786- [Tools Guide](../tools/tools) - Learn about tools
787- [Adapters](../adapters/openai) - Explore adapter options