content/cookbook/00-guides/23-gpt-5.mdx
With the release of OpenAI's GPT-5 model, there has never been a better time to start building AI applications with advanced capabilities like verbosity control, web search, and native multi-modal understanding.
The AI SDK is a powerful TypeScript toolkit for building AI applications with large language models (LLMs) like OpenAI GPT-5 alongside popular frameworks like React, Next.js, Vue, Svelte, Node.js, and more.
OpenAI's GPT-5 represents their latest advancement in language models, offering powerful new features including verbosity control for tailored response lengths, integrated web search capabilities, reasoning summaries for transparency, and native support for text, images, audio, and PDFs. The model is available in three variants: gpt-5, gpt-5-mini for faster, more cost-effective processing, and gpt-5-nano for ultra-efficient operations.
Here are the key strategies for effective prompting:
1. Agentic Workflow Control
reasoningEffort parameter to calibrate model autonomy// Example with reasoning effort control
const result = await generateText({
model: openai('gpt-5'),
prompt: 'Analyze this complex dataset and provide insights.',
providerOptions: {
openai: {
reasoningEffort: 'high', // Increases autonomous exploration
},
},
});
2. Structured Prompt Format Use XML-like tags to organize your prompts:
<context_gathering>
Goal: Extract key performance metrics from the report
Method: Focus on quantitative data and year-over-year comparisons
Early stop criteria: Stop after finding 5 key metrics
</context_gathering>
<task>
Analyze the attached financial report and identify the most important metrics.
</task>
3. Tool Calling Best Practices
4. Verbosity Control
textVerbosity parameter to control response length programmatically5. Optimization Workflow
The AI SDK is the TypeScript toolkit designed to help developers build AI-powered applications with React, Next.js, Vue, Svelte, Node.js, and more. Integrating LLMs into applications is complicated and heavily dependent on the specific model provider you use.
The AI SDK abstracts away the differences between model providers, eliminates boilerplate code for building chatbots, and allows you to go beyond text output to generate rich, interactive components.
At the center of the AI SDK is AI SDK Core, which provides a unified API to call any LLM. The code snippet below is all you need to call OpenAI GPT-5 with the AI SDK:
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
const { text } = await generateText({
model: openai('gpt-5'),
prompt: 'Explain the concept of quantum entanglement.',
});
While text generation can be useful, you might want to generate structured JSON data. For example, you might want to extract information from text, classify data, or generate synthetic data. AI SDK Core provides generateText and streamText with Output to generate structured data, allowing you to constrain model outputs to a specific schema.
import { generateText, Output } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';
const { output } = await generateText({
model: openai('gpt-5'),
output: Output.object({
schema: z.object({
recipe: z.object({
name: z.string(),
ingredients: z.array(
z.object({ name: z.string(), amount: z.string() }),
),
steps: z.array(z.string()),
}),
}),
}),
prompt: 'Generate a lasagna recipe.',
});
This code snippet will generate a type-safe recipe that conforms to the specified zod schema.
One of GPT-5's new features is verbosity control, allowing you to adjust response length without modifying your prompt:
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
// Concise response
const { text: conciseText } = await generateText({
model: openai('gpt-5'),
prompt: 'Explain quantum computing.',
providerOptions: {
openai: {
textVerbosity: 'low', // Produces terse, minimal responses
},
},
});
// Detailed response
const { text: detailedText } = await generateText({
model: openai('gpt-5'),
prompt: 'Explain quantum computing.',
providerOptions: {
openai: {
textVerbosity: 'high', // Produces comprehensive, detailed responses
},
},
});
GPT-5 can access real-time information through the integrated web search tool:
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
const result = await generateText({
model: openai('gpt-5'),
prompt: 'What are the latest developments in AI this week?',
tools: {
web_search: openai.tools.webSearch({
searchContextSize: 'high',
}),
},
});
// Access URL sources
const sources = result.sources;
For transparency into GPT-5's thought process, enable reasoning summaries:
import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';
const result = streamText({
model: openai('gpt-5'),
prompt:
'Solve this logic puzzle: If all roses are flowers and some flowers fade quickly, do all roses fade quickly?',
providerOptions: {
openai: {
reasoningSummary: 'detailed', // 'auto' for condensed or 'detailed' for comprehensive
},
},
});
// Stream reasoning and text separately
for await (const part of result.fullStream) {
if (part.type === 'reasoning') {
console.log(part.textDelta);
} else if (part.type === 'text-delta') {
process.stdout.write(part.textDelta);
}
}
GPT-5 supports tool calling out of the box, allowing it to interact with external systems and perform discrete tasks. Here's an example of using tool calling with the AI SDK:
import { generateText, tool } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';
const { toolResults } = await generateText({
model: openai('gpt-5'),
prompt: 'What is the weather like today in San Francisco?',
tools: {
getWeather: tool({
description: 'Get the weather in a location',
inputSchema: z.object({
location: z.string().describe('The location to get the weather for'),
}),
execute: async ({ location }) => ({
location,
temperature: 72 + Math.floor(Math.random() * 21) - 10,
}),
}),
},
});
AI SDK Core can be paired with AI SDK UI, another powerful component of the AI SDK, to streamline the process of building chat, completion, and assistant interfaces with popular frameworks like Next.js, Nuxt, and SvelteKit.
AI SDK UI provides robust abstractions that simplify the complex tasks of managing chat streams and UI updates on the frontend, enabling you to develop dynamic AI-driven interfaces more efficiently.
With four main hooks — useChat, useCompletion, and useObject — you can incorporate real-time chat capabilities, text completions, streamed JSON, and interactive assistant features into your app.
Let's explore building a chatbot with Next.js, the AI SDK, and OpenAI GPT-5:
In a new Next.js application, first install the AI SDK and the OpenAI provider:
<Snippet text="pnpm install ai @ai-sdk/openai @ai-sdk/react" />Then, create a route handler for the chat endpoint:
import { openai } from '@ai-sdk/openai';
import { convertToModelMessages, streamText, UIMessage } from 'ai';
// Allow responses up to 30 seconds
export const maxDuration = 30;
export async function POST(req: Request) {
const { messages }: { messages: UIMessage[] } = await req.json();
const result = streamText({
model: openai('gpt-5'),
messages: await convertToModelMessages(messages),
});
return result.toUIMessageStreamResponse();
}
Finally, update the root page (app/page.tsx) to use the useChat hook:
'use client';
import { useChat } from '@ai-sdk/react';
import { useState } from 'react';
export default function Page() {
const [input, setInput] = useState('');
const { messages, sendMessage } = useChat({});
return (
<>
{messages.map(message => (
<div key={message.id}>
{message.role === 'user' ? 'User: ' : 'AI: '}
{message.parts.map((part, index) => {
if (part.type === 'text') {
return <span key={index}>{part.text}</span>;
}
return null;
})}
</div>
))}
<form
onSubmit={e => {
e.preventDefault();
if (input.trim()) {
sendMessage({ text: input });
setInput('');
}
}}
>
<input
name="prompt"
value={input}
onChange={e => setInput(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
</>
);
}
The useChat hook on your root page (app/page.tsx) will make a request to your AI provider endpoint (app/api/chat/route.ts) whenever the user submits a message. The messages are then displayed in the chat UI.
Ready to get started? Here's how you can dive in: