Chat Agent
Install the AI SDK packages.
pnpm add ai @ai-sdk/react zodCreate the agent. The ToolLoopAgent class from the AI SDK provides a declarative way to define an agent that can use tools in a loop until it's done.
import { ToolLoopAgent } from "ai";
export const myAgent = new ToolLoopAgent({ model: "openai/gpt-5.4-mini" });That's it - three lines for a working agent. It doesn't have any tools yet, but it can already generate text responses.
Create an API route to expose the agent over HTTP. The createAgentUIStreamResponse helper streams the agent's responses back to the client.
import { createAgentUIStreamResponse } from "ai";
import { myAgent } from "@/lib/agent";
export const POST = async (req: Request) => {
const { messages } = await req.json();
return createAgentUIStreamResponse({ agent: myAgent, uiMessages: messages });
};Replace the default Next.js homepage with a chat interface. The useChat hook from @ai-sdk/react handles message state, streaming, and the connection to our API route.
"use client";
import { useChat } from "@ai-sdk/react";
import { useState } from "react";
export default function Chat() {
const [input, setInput] = useState("");
const { messages, error, sendMessage } = useChat();
if (error) return <div>{error.message}</div>;
return (
<div className="flex flex-col w-full max-w-md py-24 mx-auto stretch">
<div className="space-y-4">
{messages.map((m) =>
m.parts.map((p, i) => {
switch (p.type) {
case "text":
return (
<div key={i} className="whitespace-pre-wrap">
<div>
<div className="font-bold">{m.role}</div>
<p>{p.text}</p>
</div>
</div>
);
default:
return null;
}
}),
)}
</div>
<form
onSubmit={(e) => {
e.preventDefault();
sendMessage({ text: input });
setInput("");
}}
>
<input
className="fixed bottom-0 w-full max-w-md p-2 mb-8 border border-gray-300 rounded shadow-xl"
value={input}
placeholder="Say something..."
onChange={(e) => setInput(e.currentTarget.value)}
/>
</form>
</div>
);
}Start the development server and open your browser to http://localhost:3000. You should see the agent respond in real time.
pnpm run devCustomize the agent's behavior by adding instructions. This acts as a system prompt that shapes every response.
import { ToolLoopAgent } from "ai";
export const myAgent = new ToolLoopAgent({
model: "openai/gpt-5.4-mini",
instructions: "Respond like a cowboy.",
});Try sending a message now - the agent should respond with a cowboy personality. Instructions are a simple but powerful way to control agent behavior. We'll replace this with something more useful in the next section.