ChatGPT API Integration: Building AI-Powered Applications
ChatGPT API Integration: Building AI-Powered Applications
The ChatGPT API opens up powerful possibilities for building AI-powered applications.
Getting Started
npm install openai
Basic Chat Completion
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
async function chat(message: string) {
const completion = await openai.chat.completions.create({
model: 'gpt-4',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: message },
],
});
return completion.choices[0].message.content;
}
Streaming Responses
async function streamChat(message: string) {
const stream = await openai.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: message }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || '');
}
}
Conversation History
interface Message {
role: 'system' | 'user' | 'assistant';
content: string;
}
async function chatWithHistory(
message: string,
history: Message[]
): Promise<Message[]> {
const messages: Message[] = [
{ role: 'system', content: 'You are a helpful assistant.' },
...history,
{ role: 'user', content: message },
];
const completion = await openai.chat.completions.create({
model: 'gpt-4',
messages,
});
const assistantMessage = completion.choices[0].message;
return [...messages, assistantMessage];
}
Function Calling
const functions = [
{
name: 'get_weather',
description: 'Get the current weather',
parameters: {
type: 'object',
properties: {
location: {
type: 'string',
description: 'City and country',
},
},
required: ['location'],
},
},
];
async function chatWithFunctions(message: string) {
const completion = await openai.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: message }],
functions,
});
const messageResponse = completion.choices[0].message;
if (messageResponse.function_call) {
const functionName = messageResponse.function_call.name;
const args = JSON.parse(messageResponse.function_call.arguments);
if (functionName === 'get_weather') {
const weather = await getWeather(args.location);
return weather;
}
}
return messageResponse.content;
}
Next.js API Route
// app/api/chat/route.ts
import OpenAI from 'openai';
import { OpenAIStream, StreamingTextResponse } from 'ai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
export async function POST(req: Request) {
const { messages } = await req.json();
const response = await openai.chat.completions.create({
model: 'gpt-4',
messages,
stream: true,
});
const stream = OpenAIStream(response);
return new StreamingTextResponse(stream);
}
React Hook for Chat
import { useChat } from 'ai/react';
function ChatComponent() {
const { messages, input, handleInputChange, handleSubmit } = useChat();
return (
<div>
{messages.map(m => (
<div key={m.id}>
{m.role}: {m.content}
</div>
))}
<form onSubmit={handleSubmit}>
<input value={input} onChange={handleInputChange} />
<button type="submit">Send</button>
</form>
</div>
);
}
Best Practices
- Use streaming for better UX
- Implement rate limiting
- Cache responses when appropriate
- Handle errors gracefully
- Use system prompts effectively
Conclusion
The ChatGPT API enables building intelligent applications with natural language capabilities. With proper integration, you can create powerful AI-powered features.