ai-startup
CHAPTER 28 / 100
읽기 약 2분
FUNCTION
AI 기능 구현: OpenAI/Claude API 연동
핵심 개념
Vercel AI SDK·streamText·tool calling·모델 라우팅.
본문
Vercel AI SDK (표준)
// app/api/chat/route.ts
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';
import { anthropic } from '@ai-sdk/anthropic';
export async function POST(req: Request) {
const { messages, model = 'claude-sonnet-4-6' } = await req.json();
const result = streamText({
model: model.startsWith('claude')
? anthropic(model)
: openai(model),
messages,
maxTokens: 2000,
temperature: 0.7,
system: 'You are a helpful AI assistant.',
});
return result.toDataStreamResponse();
}클라이언트 — useChat
'use client';
import { useChat } from 'ai/react';
export function Chat() {
const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({
api: '/api/chat',
});
return (
<div>
<div className="space-y-4">
{messages.map(m => (
<div key={m.id} className={m.role === 'user' ? 'text-right' : ''}>
<div className="inline-block px-4 py-2 rounded-lg bg-muted">
{m.content}
</div>
</div>
))}
{isLoading && <Skeleton />}
</div>
<form onSubmit={handleSubmit} className="mt-4">
<input
value={input}
onChange={handleInputChange}
placeholder="메시지..."
disabled={isLoading}
/>
<button disabled={isLoading}>전송</button>
</form>
</div>
);
}Tool Calling (Function Calling)
import { streamText, tool } from 'ai';
import { z } from 'zod';
const result = streamText({
model: anthropic('claude-sonnet-4-6'),
messages,
tools: {
searchDatabase: tool({
description: 'Search the database for user data',
parameters: z.object({
query: z.string(),
limit: z.number().default(10),
}),
execute: async ({ query, limit }) => {
const results = await db.user.findMany({
where: { name: { contains: query } },
take: limit,
});
return { results };
},
}),
sendEmail: tool({
description: 'Send email to user',
parameters: z.object({
to: z.string().email(),
subject: z.string(),
body: z.string(),
}),
execute: async ({ to, subject, body }) => {
await resend.emails.send({ to, subject, text: body });
return { sent: true };
},
}),
},
});모델 라우팅 (비용 최적화)
function selectModel(task: string, complexity: 'simple' | 'medium' | 'complex') {
if (complexity === 'simple') {
return google('gemini-2.5-flash'); // 무료~저렴
}
if (complexity === 'medium') {
return anthropic('claude-sonnet-4-6'); // 표준
}
return anthropic('claude-opus-4-7'); // 가장 강력
}
// 자동 분류
async function classifyComplexity(message: string) {
const result = await generateText({
model: google('gemini-2.5-flash'),
prompt: `Classify: simple, medium, complex\n${message}`,
});
return result.text.trim() as any;
}비용 비교 (1M 토큰)
Gemini 2.5 Flash: $0.10 input / $0.40 output
GPT-4o-mini: $0.15 / $0.60
Claude Haiku 4.5: $0.80 / $4
GPT-4o: $2.50 / $10
Claude Sonnet 4.6: $3 / $15
Claude Opus 4.7: $15 / $75
→ 80% 작업은 Flash/Mini로 충분
→ 복잡한 작업만 Sonnet/Opus
→ 비용 1/10~1/100 절감에러 처리
try {
const result = streamText({ model, messages });
return result.toDataStreamResponse();
} catch (err: any) {
if (err.statusCode === 429) {
return new Response('Rate limit exceeded', { status: 429 });
}
if (err.statusCode === 402) {
return new Response('Quota exceeded', { status: 402 });
}
Sentry.captureException(err);
return new Response('AI 일시 오류', { status: 503 });
}다음 챕터
CH.29 "프롬프트 엔지니어링: 서비스용 프롬프트 설계".
AI 프롬프트
🤖 AI에게 잘 물어보는 법 — 모델·전략별 프롬프트
무료
월 $0 — 검증·시작 단계
AI API 연동을 무료 도구만으로 시작하는 방법을 알려줘.
소자본
월 $20~50 — MVP·초기 운영
월 $20~50 예산으로 AI API 연동을 검증·MVP 단계까지 진행하는 전략은?
프로덕션
월 $200~500 — 성장 단계
AI API 연동을 프로덕션 단계로 확장할 때 필요한 도구·운영 체계는?
스택
풀스택 — 도구 조합 분석
2026년 AI API 연동 관련 도구 5개를 조합한 추천 스택을 알려줘.
⭐ 이것만 기억하세요
AI 기능 구현: OpenAI/Claude API 연동은 이 3가지만 확실히 잡으세요
1.Vercel AI SDK = OpenAI/Anthropic/Google 통합 인터페이스
2.Tool Calling으로 AI가 DB·이메일·외부 API 자동 호출
3.모델 라우팅 (Flash → Sonnet → Opus) = 비용 1/10 절감
공유하기
진행도 28 / 100