Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

mid-conversation-changes.md

160 lines6.0 KB

1---
2title: Mid-Conversation Changes
3id: mid-conversation-changes
4order: 18
5description: "Add tools or system prompts during a conversation and keep the prompt cache. On GPT and Claude models with a mid-conversation channel, TanStack AI sends the change inside the conversation."
6keywords:
7 - tanstack ai
8 - prompt caching
9 - mid-conversation changes
10 - dynamic tools
11 - additional_tools
12 - tool_addition
13---
14​
15Put a stable tool list at the start of each request so the provider can keep its prompt cache. Add a tool that appears mid-chat after that prefix.
16​
17On some GPT and Claude models, TanStack AI sends the added tool inside the conversation. The start stays the same, and the cache keeps working. You change no code.
18​
19## Quick setup
20​
21This setup takes about 5 minutes.
22​
23### 1. Pick a model with a channel
24​
25The channel exists on these models:
26​
27| Adapter | Models |
28|---|---|
29| `openaiText` | `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6-astra`, `gpt-6-luna`, `gpt-6-sol` |
30| `anthropicText` | `claude-opus-4-8`, `claude-opus-5`, `claude-opus-5-5`, `claude-fable-5`, `claude-fable-5-1` |
31​
32Every other model and adapter sends the full lists on each call.
33​
34### 2. Add a tool during the run
35​
36This route starts with one tool. A middleware adds a second tool after the first model call:
37​
38```typescript
39import {
40 chat,
41 chatParamsFromRequest,
42 toServerSentEventsResponse,
43 toolDefinition,
44} from "@tanstack/ai";
45import type { ChatMiddleware } from "@tanstack/ai";
46import { openaiText } from "@tanstack/ai-openai";
47import { z } from "zod";
48​
49const getWeather = toolDefinition({
50 name: "get_weather",
51 description: "Get the current weather for a city",
52 inputSchema: z.object({ city: z.string() }),
53}).server(async ({ city }) => ({ city, temperature: 21 }));
54​
55const getForecast = toolDefinition({
56 name: "get_forecast",
57 description: "Get the forecast for a city",
58 inputSchema: z.object({ city: z.string() }),
59}).server(async ({ city }) => ({ city, tomorrow: "sunny" }));
60​
61const addForecast: ChatMiddleware = {
62 name: "add-forecast",
63 onConfig: (ctx, config) => {
64 if (ctx.phase !== "beforeModel" || ctx.iteration === 0) return;
65 if (config.tools.some((tool) => tool.name === "get_forecast")) return;
66 return { tools: [...config.tools, getForecast] };
67 },
68};
69​
70export async function POST(request: Request) {
71 const { messages, threadId } = await chatParamsFromRequest(request);
72 const stream = chat({
73 adapter: openaiText("gpt-6-astra"),
74 messages,
75 threadId,
76 tools: [getWeather],
77 middleware: [addForecast],
78 });
79 return toServerSentEventsResponse(stream);
81```
82​
83The client does not change. Ask about the weather, and the second model call reads the start of the request from the cache.
84​
85## How it works
86​
87The second model call of the example sends this:
88​
89| Model | `tools` | The new tool |
90|---|---|---|
91| `gpt-6-astra` | `get_weather` only | An `additional_tools` item after the tool result |
92| `claude-opus-5-5` | `get_weather`, a placeholder tool, then `get_forecast` with `defer_loading: true` | A `system` message with a `tool_addition` block after the tool result |
93| A model with no channel, such as `gpt-6.1-sol` | `get_weather` and `get_forecast` | Nothing extra |
94​
95Some more rules:
96​
97- The channel works only when the first call already had a tool.
98- A system prompt that you add at the end of the list works the same way. It goes into the conversation as a `developer` message (GPT) or a `system` message (Claude).
99​
100## Advanced
101​
102### Check your model
103​
104To check in code, read `midConversationChannels` on the adapter:
105​
106```typescript
107import { openaiText } from "@tanstack/ai-openai";
108​
109const adapter = openaiText("gpt-6-astra");
110console.log(adapter.midConversationChannels); // { tools: true, systemPrompts: true }
111```
112​
113It is `undefined` when the model has no channel, or when the channels are off.
114​
115### Turn it on or off
116​
117The channels are on by default only when the adapter talks to the API of the provider directly. A gateway or a proxy can drop the extra fields. So the channels are off with:
118​
119- a custom `baseURL` or a custom `fetch`.
120- a proxy URL in `OPENAI_BASE_URL` or `ANTHROPIC_BASE_URL`.
121- an Anthropic adapter on your own client (`createAnthropicChatWithClient`, `anthropicVertexText`).
122​
123Set `midConversationChannels` in the adapter config to choose:
124​
125```typescript
126import { anthropicText } from "@tanstack/ai-anthropic";
127import { openaiText } from "@tanstack/ai-openai";
128​
129// Send the full lists on every call.
130export const fullLists = openaiText("gpt-6-astra", {
131 midConversationChannels: false,
132});
133​
134// Use the channels behind a proxy that sends the request on with no change.
135export const throughProxy = anthropicText("claude-opus-5-5", {
136 baseURL: "https://llm-proxy.example.com",
137 midConversationChannels: true,
138});
139```
140​
141On a model with no channel, `true` changes nothing.
142​
143### Keep the record when you store messages
144​
145Before each model call, `chat()` compares the tools and the system prompts with the earlier calls. It saves a small record on the first assistant message of the call, in the `midConversationChange` field. The record holds tool names and short prompt hashes, not tool definitions.
146​
147The next turn reads these records:
148​
149- If you save messages yourself, keep the `midConversationChange` field.
150- With [`withPersistence`](../persistence/chat-persistence), you do nothing. The store keeps the record, also when `useChat` sends the same message back without it.
151- With plain `useChat` and no store, the records last for one `chat()` call. Each new turn starts with no record, and the cache breaks one time for each turn.
152​
153### Limits
154​
155These changes still break the cache one time:
156​
157- A tool that you remove, or a tool that keeps its name but gets a new definition.
158- A system prompt that you edit, move, or add anywhere but the end.
159- A provider tool, such as `webSearchTool()`, in the request. That request sends the full `tools` list. Prompt changes still go into the conversation.
160- The first tool, when the recorded start had no tools. That request sends the full tool list.