# OpenAI 함수 호출 (Function Calling)

안녕하세요! 오늘은 **OpenAI Function Calling**을 사용해서 AI가 외부 API와 상호작용하는 방법을 알아봅니다! 🔌
## Function Calling이란?
Function Calling은 AI가 미리 정의된 함수를 호출해서 외부 시스템과 통신할 수 있게 하는 기능입니다.
**예시:**
– 날씨 API 호출
– 데이터베이스 쿼리
– 이메일 전송
– 알림 생성
—
## 1. 기본 구조
“`typescript
// 1. 함수 정의
const tools = [{
type: “function”,
function: {
name: “get_weather”,
description: “현재 날씨 정보 가져오기”,
parameters: {
type: “object”,
properties: {
city: {
type: “string”,
description: “도시 이름”
}
},
required: [“city”]
}
}
}];
// 2. API 요청
const response = await openai.chat.completions.create({
model: “gpt-4o”,
messages: [
{ role: “user”, content: “서울 날씨 어때?” }
],
tools: tools,
});
// 3. 함수 호출
const functionCall = response.choices[0].message.tool_calls[0];
“`
—
## 2. 날씨 API 예제
“`typescript
import OpenAI from “openai”;
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
// 함수 정의
const tools = [{
type: “function”,
function: {
name: “get_current_weather”,
description: “현재 날씨 정보 반환”,
parameters: {
type: “object”,
properties: {
location: {
type: “string”,
description: “도시 이름 (예: Seoul, Busan)”
},
unit: {
type: “string”,
enum: [“celsius”, “fahrenheit”],
description: “온도 단위”
}
},
required: [“location”]
}
}
}];
// 날씨 API 함수 구현
async function getCurrentWeather(location: string, unit: string = “celsius”) {
// 실제 API 호출 (예: OpenWeatherMap)
const apiKey = process.env.WEATHER_API_KEY;
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${location}&units=${unit}&appid=${apiKey}`
);
return await response.json();
}
// 메인 함수
async function chatWithWeather() {
const messages = [
{ role: “user”, content: “서울 날씨 알려줘” }
];
// 1. 함수 호출 요청
const response = await openai.chat.completions.create({
model: “gpt-4o”,
messages,
tools,
});
// 2. 함수 실행
const toolCall = response.choices[0].message.tool_calls?.[0];
if (toolCall) {
const { location, unit } = JSON.parse(toolCall.function.arguments);
const weatherData = await getCurrentWeather(location, unit);
// 3. 결과를 AI에 다시 전달
messages.push({
role: “assistant”,
content: JSON.stringify(weatherData),
});
const finalResponse = await openai.chat.completions.create({
model: “gpt-4o”,
messages,
});
return finalResponse.choices[0].message.content;
}
}
chatWithWeather();
“`
—
## 3. 데이터베이스 쿼리
“`typescript
const tools = [{
type: “function”,
function: {
name: “query_database”,
description: “데이터베이스에서 정보 조회”,
parameters: {
type: “object”,
properties: {
table: {
type: “string”,
description: “테이블 이름”
},
filters: {
type: “object”,
description: “필터 조건”
}
},
required: [“table”]
}
}
}];
async function queryDatabase(table: string, filters?: any) {
const { data, error } = await supabase
.from(table)
.select(‘*’)
.match(filters || {});
return data;
}
“`
—
## 4. 이메일 전송
“`typescript
const tools = [{
type: “function”,
function: {
name: “send_email”,
description: “이메일 전송”,
parameters: {
type: “object”,
properties: {
to: {
type: “string”,
description: “받는 사람 이메일”
},
subject: {
type: “string”,
description: “제목”
},
body: {
type: “string”,
description: “본문”
}
},
required: [“to”, “subject”, “body”]
}
}
}];
async function sendEmail(to: string, subject: string, body: string) {
await sgMail.send({
to,
from: “noreply@yourdomain.com”,
subject,
text: body,
});
}
“`
—
## 5. 여러 함수 사용
“`typescript
const tools = [
{
name: “search_products”,
description: “제품 검색”,
parameters: {
type: “object”,
properties: {
query: { type: “string” },
category: { type: “string” }
}
}
},
{
name: “add_to_cart”,
description: “장바구니에 추가”,
parameters: {
type: “object”,
properties: {
product_id: { type: “string” },
quantity: { type: “integer” }
},
required: [“product_id”, “quantity”]
}
}
];
“`
—
## 6. 에러 처리
“`typescript
try {
const response = await openai.chat.completions.create({
model: “gpt-4o”,
messages,
tools,
});
const toolCall = response.choices[0].message.tool_calls?.[0];
if (toolCall) {
try {
const result = await executeFunction(toolCall);
messages.push({
role: “tool”,
content: JSON.stringify(result),
tool_call_id: toolCall.id,
});
} catch (error) {
messages.push({
role: “tool”,
content: JSON.stringify({ error: error.message }),
tool_call_id: toolCall.id,
});
}
}
} catch (error) {
console.error(“OpenAI API 오류:”, error);
}
“`
—
## 7. 스트리밍과 결합
“`typescript
const stream = await openai.chat.completions.create({
model: “gpt-4o”,
messages,
tools,
stream: true,
});
for await (const chunk of stream) {
const toolCall = chunk.choices[0]?.delta?.tool_calls?.[0];
if (toolCall) {
// 함수 호출 감지
}
}
“`
—
## 8. 최적화 팁
1. **함수 설명 명확하게**: AI가 언제 호출할지 알 수 있도록
2. **파라미터 구체화**: 타입, 설명, 예시 포함
3. **필수 vs 선택적**: required로 명시
4. **에러 메시지 친절하게**: AI가 이해하기 쉽게
—
## 결론
Function Calling은 AI와 실제 세계를 연결하는 강력한 도구입니다!
**핵심 포인트:**
– ✅ 명확한 함수 정의
– ✅ 적절한 파라미터 구조
– ✅ 에러 처리
– ✅ 여러 함수 조합
—
## 다음 단계
– 🔌 실제 API와 연동
– 🔒 인증 및 보안
– 📊 사용량 모니터링
## 참고 자료
– [OpenAI Function Calling 문서](https://platform.openai.com/docs/guides/function-calling)
– [API Reference](https://platform.openai.com/docs/api-reference)
—
질문이 있나요? 댓글로 남겨주세요! 😊
**다음 포스팅:** 오픈소스 LLM: Llama 3 로컬 실행