Open History to see the last commit
SolidJS primitives for TanStack AI, providing convenient SolidJS bindings for the headless client.
Installation#
npm install @tanstack/ai-solid
useChat(options?)#
Main primitive for managing chat state in SolidJS with full type safety.
import { useChat, fetchServerSentEvents } from "@tanstack/ai-solid";
import {
createChatClientOptions,
type InferChatMessages
} from "@tanstack/ai-client";
import { toolDefinition } from "@tanstack/ai";
import { z } from "zod";
import { createSignal } from "solid-js";
const updateUIDef = toolDefinition({
name: "updateUI",
description: "Show a notification in the UI",
inputSchema: z.object({ message: z.string() }),
});
function ChatComponent() {
const [, setNotification] = createSignal<string | null>(null);
// Create client tool implementations
const updateUI = updateUIDef.client((input) => {
setNotification(input.message);
return { success: true };
});
// Create typed tools array (no 'as const' needed!)
const tools = [updateUI];
const chatOptions = createChatClientOptions({
connection: fetchServerSentEvents("/api/chat"),
tools,
});
// Fully typed messages!
type ChatMessages = InferChatMessages<typeof chatOptions>;
const { messages, sendMessage, isLoading, error, addToolApprovalResponse } =
useChat(chatOptions);
return <div>{/* Chat UI with typed messages */}</div>;
}
Options#
Extends ChatClientOptions from @tanstack/ai-client:
connection- Connection adapter (required)tools?- Array of client tool implementations (with.client()method)initialMessages?- Initial messages arrayid?- Unique identifier for this chat instancethreadId?- Thread ID for AG-UI run correlation. Persists across sends; auto-generated if omittedforwardedProps?- Arbitrary client-controlled JSON forwarded to the server in the AG-UIRunAgentInput.forwardedPropsfield (e.g.,{ provider: 'openai', model: 'gpt-4o' })body?- Deprecated. UseforwardedPropsinstead. Still works for backward compatibility; values are merged intoforwardedPropson the wirecontext?- Typed client-local runtime context passed to client tool implementations. This value is not serialized to the serveronResponse?- Callback when response is receivedonChunk?- Callback when stream chunk is receivedonFinish?- Callback when response finishesonError?- Callback when error occursstreamProcessor?- Stream processing configuration
Note: Client tools are now automatically executed - no onToolCall callback needed!
Returns#
import type { Accessor } from "solid-js";
import type { UIMessage } from "@tanstack/ai-solid";
import type { ModelMessage } from "@tanstack/ai/client";
interface UseChatReturn {
messages: Accessor<UIMessage[]>;
sendMessage: (content: string) => Promise<void>;
append: (message: ModelMessage | UIMessage) => Promise<void>;
addToolResult: (result: {
toolCallId: string;
tool: string;
output: any;
state?: "output-available" | "output-error";
errorText?: string;
}) => Promise<void>;
addToolApprovalResponse: (response: {
id: string;
approved: boolean;
}) => Promise<void>;
reload: () => Promise<void>;
stop: () => void;
isLoading: Accessor<boolean>;
error: Accessor<Error | undefined>;
setMessages: (messages: UIMessage[]) => void;
clear: () => void;
}
Note: Unlike React, messages, isLoading, and error are SolidJS Accessor functions, so you need to call them to get their values (e.g., messages() instead of just messages).
Connection Adapters#
Re-exported from @tanstack/ai-client for convenience:
import {
fetchServerSentEvents,
fetchHttpStream,
stream,
type ConnectionAdapter,
} from "@tanstack/ai-solid";
Example: Basic Chat#
import { createSignal, For } from "solid-js";
import { useChat, fetchServerSentEvents } from "@tanstack/ai-solid";
export function Chat() {
const [input, setInput] = createSignal("");
const { messages, sendMessage, isLoading } = useChat({
connection: fetchServerSentEvents("/api/chat"),
});
const handleSubmit = (e: Event) => {
e.preventDefault();
if (input().trim() && !isLoading()) {
sendMessage(input());
setInput("");
}
};
return (
<div>
<div>
<For each={messages()}>
{(message) => (
<div>
<strong>{message.role}:</strong>
<For each={message.parts}>
{(part) => {
if (part.type === "thinking") {
return (
<div class="text-sm text-gray-500 italic">
π Thinking: {part.content}
</div>
);
}
if (part.type === "text") {
return <span>{part.content}</span>;
}
return null;
}}
</For>
</div>
)}
</For>
</div>
<form onSubmit={handleSubmit}>
<input
value={input()}
onInput={(e) => setInput(e.currentTarget.value)}
disabled={isLoading()}
/>
<button type="submit" disabled={isLoading()}>
Send
</button>
</form>
</div>
);
}
Example: Tool Approval#
import { For, Show } from "solid-js";
import { useChat, fetchServerSentEvents } from "@tanstack/ai-solid";
export function ChatWithApproval() {
const { messages, sendMessage, addToolApprovalResponse } = useChat({
connection: fetchServerSentEvents("/api/chat"),
});
return (
<div>
<For each={messages()}>
{(message) => (
<For each={message.parts}>
{(part) => {
if (
part.type === "tool-call" &&
part.state === "approval-requested" &&
part.approval
) {
return (
<div>
<p>Approve: {part.name}</p>
<button
onClick={() =>
addToolApprovalResponse({
id: part.approval!.id,
approved: true,
})
}
>
Approve
</button>
<button
onClick={() =>
addToolApprovalResponse({
id: part.approval!.id,
approved: false,
})
}
>
Deny
</button>
</div>
);
}
return null;
}}
</For>
)}
</For>
</div>
);
}
Example: Client Tools with Type Safety#
import { useChat, fetchServerSentEvents } from "@tanstack/ai-solid";
import {
createChatClientOptions,
type InferChatMessages
} from "@tanstack/ai-client";
import { toolDefinition } from "@tanstack/ai";
import { z } from "zod";
import { createSignal, For } from "solid-js";
const updateUIDef = toolDefinition({
name: "updateUI",
description: "Show a notification in the UI",
inputSchema: z.object({ message: z.string(), type: z.string() }),
});
const saveToStorageDef = toolDefinition({
name: "saveToStorage",
description: "Save a value to localStorage",
inputSchema: z.object({ key: z.string(), value: z.string() }),
});
export function ChatWithClientTools() {
const [notification, setNotification] = createSignal<{ message: string; type: string } | null>(null);
// Create client implementations
const updateUI = updateUIDef.client((input) => {
// β
input is fully typed!
setNotification({ message: input.message, type: input.type });
return { success: true };
});
const saveToStorage = saveToStorageDef.client((input) => {
localStorage.setItem(input.key, input.value);
return { saved: true };
});
// Create typed tools array (no 'as const' needed!)
const tools = [updateUI, saveToStorage];
const { messages, sendMessage } = useChat({
connection: fetchServerSentEvents("/api/chat"),
tools, // β
Automatic execution, full type safety
});
return (
<div>
<For each={messages()}>
{(message) => (
<For each={message.parts}>
{(part) => {
if (part.type === "tool-call" && part.name === "updateUI") {
// β
part.input and part.output are fully typed!
return <div>Tool executed: {part.name}</div>;
}
return null;
}}
</For>
)}
</For>
</div>
);
}
createChatClientOptions(options)#
Helper to create typed chat options (re-exported from @tanstack/ai-client).
import {
createChatClientOptions,
type InferChatMessages
} from "@tanstack/ai-client";
import { fetchServerSentEvents } from "@tanstack/ai-solid";
import { tool1, tool2 } from "./tools";
// Create typed tools array (no 'as const' needed!)
const tools = [tool1, tool2];
const chatOptions = createChatClientOptions({
connection: fetchServerSentEvents("/api/chat"),
tools,
});
type Messages = InferChatMessages<typeof chatOptions>;
Types#
Re-exported from @tanstack/ai-client:
UIMessage<TTools>- Message type with tool type parameterMessagePart<TTools>- Message part with tool type parameterTextPart- Text content partThinkingPart- Thinking content partToolCallPart<TTools>- Tool call part (discriminated union)ToolResultPart- Tool result partChatClientOptions<TTools, TContext>- Chat client options with typed client runtime contextConnectionAdapter- Connection adapter interfaceInferChatMessages<T>- Extract message type from optionsChatRequestBody- Request body type
Re-exported from @tanstack/ai:
toolDefinition()- Create isomorphic tool definitionToolDefinitionInstance- Tool definition typeClientTool- Client tool typeServerTool- Server tool type
Next Steps#
- Getting Started - Learn the basics
- Tools Guide - Learn about the isomorphic tool system
- Client Tools - Learn about client-side tools