Get started with GPT-5
Get started with GPT-5 using the AI TOOLKIT.
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 TOOLKIT 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.
Run it locally
$ npm install aiOpenAI GPT-5
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.
### Prompt Engineering for GPT-5
Here are the key strategies for effective prompting:
#### Core Principles
1. Be precise and unambiguous: Avoid contradictory or ambiguous instructions. GPT-5 performs best with clear, explicit guidance.
2. Use structured prompts: Leverage XML-like tags to organize different sections of your instructions for better clarity.
3. Natural language works best: While being precise, write prompts as you would explain to a skilled colleague.
#### Prompting Techniques
1. Agentic Workflow Control
- Adjust the reasoningEffort parameter to calibrate model autonomy
- Set clear stop conditions and define explicit tool call budgets
- Provide guidance on exploration depth and persistence
// 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
- Use tool preambles to provide clear upfront plans
- Define safe vs. unsafe actions for different tools
- Create structured updates about tool call progress
4. Verbosity Control
- Use the textVerbosity parameter to control response length programmatically
- Override with natural language when needed for specific contexts
- Balance between conciseness and completeness
5. Optimization Workflow
- Start with a clear, simple prompt
- Test and identify areas of ambiguity or confusion
- Iteratively refine by removing contradictions
- Consider using OpenAI's Prompt Optimizer tool for complex prompts
- Document successful patterns for reuse
- 1// Example with reasoning effort control
- 2const result = await generateText({
- 3 model: openai('gpt-5'),
- 4 prompt: 'Analyze this complex dataset and provide insights.',
- 5 providerOptions: {
- 6 openai: {
- 7 reasoningEffort: 'high', // Increases autonomous exploration
- 8 },
- 9 },
- 10});
- 1<context_gathering>
- 2Goal: Extract key performance metrics from the report
- 3Method: Focus on quantitative data and year-over-year comparisons
- 4Early stop criteria: Stop after finding 5 key metrics
- 5</context_gathering>
- 6<task>
- 7Analyze the attached financial report and identify the most important metrics.
- 8</task>
Getting Started with the AI TOOLKIT
The AI TOOLKIT 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 TOOLKIT 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 TOOLKIT is AI TOOLKIT 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 TOOLKIT:
import { generateText } from 'ai-toolkit';
import { openai } from '@ai-toolkit/openai';
const { text } = await generateText({
model: openai('gpt-5'),
prompt: 'Explain the concept of quantum entanglement.',
});
### Generating Structured Data
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 TOOLKIT Core provides two functions (`generateObject` and `streamObject`) to generate structured data, allowing you to constrain model outputs to a specific schema.
import { generateObject } from 'ai-toolkit';
import { openai } from '@ai-toolkit/openai';
import { z } from 'zod';
const { object } = await generateObject({
model: openai('gpt-5'),
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.
### Verbosity Control
One of GPT-5's new features is verbosity control, allowing you to adjust response length without modifying your prompt:
import { generateText } from 'ai-toolkit';
import { openai } from '@ai-toolkit/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
},
},
});
### Web Search
GPT-5 can access real-time information through the integrated web search tool:
import { generateText } from 'ai-toolkit';
import { openai } from '@ai-toolkit/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;
### Reasoning Summaries
For transparency into GPT-5's thought process, enable reasoning summaries:
import { openai } from '@ai-toolkit/openai';
import { streamText } from 'ai-toolkit';
const result = streamText({
model: openai.responses('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);
}
}
### Using Tools with the AI TOOLKIT
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 TOOLKIT:
import { generateText, tool } from 'ai-toolkit';
import { openai } from '@ai-toolkit/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,
}),
}),
},
});
### Building Interactive Interfaces
AI TOOLKIT Core can be paired with AI TOOLKIT UI, another powerful component of the AI TOOLKIT, to streamline the process of building chat, completion, and assistant interfaces with popular frameworks like Next.js, Nuxt, and SvelteKit.
AI TOOLKIT 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 TOOLKIT, and OpenAI GPT-5:
In a new Next.js application, first install the AI TOOLKIT and the OpenAI provider:
<Snippet text="pnpm install ai @ai-toolkit/openai @ai-toolkit/react" />
Then, create a route handler for the chat endpoint:
import { openai } from '@ai-toolkit/openai';
import { convertToModelMessages, streamText, UIMessage } from 'ai-toolkit';
// 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-toolkit/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.
- 1import { generateText } from 'ai-toolkit';
- 2import { openai } from '@ai-toolkit/openai';
- 3const { text } = await generateText({
- 4 model: openai('gpt-5'),
- 5 prompt: 'Explain the concept of quantum entanglement.',
- 6});
- 1import { generateObject } from 'ai-toolkit';
- 2import { openai } from '@ai-toolkit/openai';
- 3import { z } from 'zod';
- 4const { object } = await generateObject({
- 5 model: openai('gpt-5'),
- 6 schema: z.object({
- 7 recipe: z.object({
- 8 name: z.string(),
- 9 ingredients: z.array(z.object({ name: z.string(), amount: z.string() })),
- 10 steps: z.array(z.string()),
- 11 }),
- 12 }),
- 13 prompt: 'Generate a lasagna recipe.',
- 14});
- 1import { generateText } from 'ai-toolkit';
- 2import { openai } from '@ai-toolkit/openai';
- 3// Concise response
- 4const { text: conciseText } = await generateText({
- 5 model: openai('gpt-5'),
- 6 prompt: 'Explain quantum computing.',
- 7 providerOptions: {
- 8 openai: {
- 9 textVerbosity: 'low', // Produces terse, minimal responses
- 10 },
- 11 },
- 12});
- 13// Detailed response
- 14const { text: detailedText } = await generateText({
- 15 model: openai('gpt-5'),
- 16 prompt: 'Explain quantum computing.',
- 17 providerOptions: {
- 18 openai: {
- 19 textVerbosity: 'high', // Produces comprehensive, detailed responses
- 20 },
- 21 },
- 22});
- 1import { generateText } from 'ai-toolkit';
- 2import { openai } from '@ai-toolkit/openai';
- 3const result = await generateText({
- 4 model: openai('gpt-5'),
- 5 prompt: 'What are the latest developments in AI this week?',
- 6 tools: {
- 7 web_search: openai.tools.webSearch({
- 8 searchContextSize: 'high',
- 9 }),
- 10 },
- 11});
- 12// Access URL sources
- 13const sources = result.sources;
- 1import { openai } from '@ai-toolkit/openai';
- 2import { streamText } from 'ai-toolkit';
- 3const result = streamText({
- 4 model: openai.responses('gpt-5'),
- 5 prompt:
- 6 'Solve this logic puzzle: If all roses are flowers and some flowers fade quickly, do all roses fade quickly?',
- 7 providerOptions: {
- 8 openai: {
- 9 reasoningSummary: 'detailed', // 'auto' for condensed or 'detailed' for comprehensive
- 10 },
- 11 },
- 12});
- 13// Stream reasoning and text separately
- 14for await (const part of result.fullStream) {
- 15 if (part.type === 'reasoning') {
- 16 console.log(part.textDelta);
- 17 } else if (part.type === 'text-delta') {
- 18 process.stdout.write(part.textDelta);
- 19 }
- 20}
- 1import { generateText, tool } from 'ai-toolkit';
- 2import { openai } from '@ai-toolkit/openai';
- 3import { z } from 'zod';
- 4const { toolResults } = await generateText({
- 5 model: openai('gpt-5'),
- 6 prompt: 'What is the weather like today in San Francisco?',
- 7 tools: {
- 8 getWeather: tool({
- 9 description: 'Get the weather in a location',
- 10 inputSchema: z.object({
- 11 location: z.string().describe('The location to get the weather for'),
- 12 }),
- 13 execute: async ({ location }) => ({
- 14 location,
- 15 temperature: 72 + Math.floor(Math.random() * 21) - 10,
- 16 }),
- 17 }),
- 18 },
- 19});
- 1import { openai } from '@ai-toolkit/openai';
- 2import { convertToModelMessages, streamText, UIMessage } from 'ai-toolkit';
- 3// Allow responses up to 30 seconds
- 4export const maxDuration = 30;
- 5export async function POST(req: Request) {
- 6 const { messages }: { messages: UIMessage[] } = await req.json();
- 7 const result = streamText({
- 8 model: openai('gpt-5'),
- 9 messages: await convertToModelMessages(messages),
- 10 });
- 11 return result.toUIMessageStreamResponse();
- 12}
- 1'use client';
- 2import { useChat } from '@ai-toolkit/react';
- 3import { useState } from 'react';
- 4export default function Page() {
- 5 const [input, setInput] = useState('');
- 6 const { messages, sendMessage } = useChat({});
- 7 return (
- 8 <>
- 9 {messages.map(message => (
- 10 <div key={message.id}>
- 11 {message.role === 'user' ? 'User: ' : 'AI: '}
- 12 {message.parts.map((part, index) => {
- 13 if (part.type === 'text') {
- 14 return <span key={index}>{part.text}</span>;
- 15 }
- 16 return null;
- 17 })}
- 18 </div>
- 19 ))}
- 20 <form
- 21 onSubmit={e => {
- 22 e.preventDefault();
- 23 if (input.trim()) {
- 24 sendMessage({ text: input });
- 25 setInput('');
- 26 }
- 27 }}
- 28 >
- 29 <input
- 30 name="prompt"
- 31 value={input}
- 32 onChange={e => setInput(e.target.value)}
- 33 />
- 34 <button type="submit">Submit</button>
- 35 </form>
- 36 </>
- 37 );
- 38}
Get Started
Ready to get started? Here's how you can dive in:
1. Explore the documentation at studio.khulnasoft.com/docs to understand the full capabilities of the AI TOOLKIT.
2. Check out practical examples at studio.khulnasoft.com/cookbook to see the SDK in action and get inspired for your own projects.
3. Dive deeper with advanced guides on topics like Retrieval-Augmented Generation (RAG) and multi-modal chat at studio.khulnasoft.com/cookbook/guides.
4. Check out ready-to-deploy AI templates at vercel.com/templates?type=ai.