このチュートリアルで学ぶこと
✓ APIキー取得
✓ Chat Completions API
✓ ストリーミング
✓ Function Calling
✓ エラーハンドリング
Step 1: セットアップ
npm install openai
// lib/openai.ts
import OpenAI from 'openai';
export const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
Step 2: 基本的なチャット
// app/api/chat/route.ts
import { openai } from '@/lib/openai';
import { NextResponse } from 'next/server';
export async function POST(request: Request) {
const { message } = await request.json();
const completion = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: message },
],
max_tokens: 1000,
});
return NextResponse.json({
reply: completion.choices[0].message.content,
});
}
Step 3: ストリーミング
// app/api/chat/stream/route.ts
import { openai } from '@/lib/openai';
export async function POST(request: Request) {
const { message } = await request.json();
const stream = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: message }],
stream: true,
});
const encoder = new TextEncoder();
return new Response(
new ReadableStream({
async start(controller) {
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || '';
controller.enqueue(encoder.encode(content));
}
controller.close();
},
}),
{ headers: { 'Content-Type': 'text/plain' } }
);
}
Step 4: クライアント(ストリーミング)
'use client';
import { useState } from 'react';
export function Chat() {
const [input, setInput] = useState('');
const [response, setResponse] = useState('');
const handleSubmit = async () => {
setResponse('');
const res = await fetch('/api/chat/stream', {
method: 'POST',
body: JSON.stringify({ message: input }),
});
const reader = res.body?.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader!.read();
if (done) break;
setResponse((prev) => prev + decoder.decode(value));
}
};
return (
<div>
<input value={input} onChange={(e) => setInput(e.target.value)} />
<button onClick={handleSubmit}>Send</button>
<p>{response}</p>
</div>
);
}
Step 5: Function Calling
const tools = [
{
type: 'function' as const,
function: {
name: 'get_weather',
description: 'Get the current weather in a location',
parameters: {
type: 'object',
properties: {
location: { type: 'string', description: 'City name' },
},
required: ['location'],
},
},
},
];
const completion = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: '東京の天気は?' }],
tools,
});
const toolCall = completion.choices[0].message.tool_calls?.[0];
if (toolCall?.function.name === 'get_weather') {
const args = JSON.parse(toolCall.function.arguments);
const weather = await getWeather(args.location);
// 結果を返す
}
Step 6: 画像生成
const image = await openai.images.generate({
model: 'dall-e-3',
prompt: 'A cute cat in a space suit',
n: 1,
size: '1024x1024',
});
console.log(image.data[0].url);
Step 7: エラーハンドリング
import OpenAI from 'openai';
try {
const completion = await openai.chat.completions.create({...});
} catch (error) {
if (error instanceof OpenAI.APIError) {
console.log(error.status); // 429, 500, etc.
console.log(error.message);
}
}
まとめ
OpenAI APIでChatGPTをアプリに統合できます。ストリーミングでUXを向上させ、Function Callingで機能を拡張しましょう。
← 一覧に戻る