GPT API Tool 예시 (get_local_kst_time)
OpenAI GPT API의 tool(function calling) 기능을 간단히 살펴보는 예제입니다.
현재 KST 시간을 반환하는 함수를 정의하고, 모델이 이를 자동으로 호출하는 흐름을 보여줍니다.
zod를 사용한 이유는 tool(function) 파라미터를 명확하고 안전하게 정의하기 위해서입니다.
스키마 기반으로 JSON Schema를 자동 생성할 수 있어, GPT가 호출할 수 있는 함수의 입력 형식을 정확히 전달하고 타입 안정성을 유지할 수 있습니다.
또한 GPT API는 stateless 방식으로 동작하기 때문에, 이전 대화 맥락을 유지하려면 매 요청마다 이전 메시지들을 함께 전달해야 합니다.
이 예제에서는 messages 배열에 사용자·어시스턴트·tool 응답을 누적하여 대화 흐름을 이어가도록 구성했습니다.
import OpenAI from "openai";
import dotenv from "dotenv";
import { z } from "zod";
dotenv.config();
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
const tools = [
{
type: "function",
function: {
name: "get_local_kst_time",
description: "Return the current KST (Korea Standard Time) in YYYY-MM-DDTHH:mm:ss format.",
parameters: z.object({}).strict().toJSONSchema()
},
},
];
function get_local_kst_time() {
return new Date(new Date().toLocaleString("en-US", { timeZone: "Asia/Seoul" }))
.toISOString()
.replace(".000Z", "");
}
const functions = {
get_local_kst_time
};
const messages = [];
function handleToolCalls(assistantMessage, messages) {
if (!assistantMessage.tool_calls) return false;
for (const toolCall of assistantMessage.tool_calls) {
const handler = functions[toolCall.function.name];
if (!handler) continue;
const result = handler(assistantMessage);
messages.push({
role: "tool",
tool_call_id: toolCall.id,
content: typeof result === "string" ? result : JSON.stringify(result),
});
}
return true;
}
messages.push({ role: "user", content: "현재 시간을 알려줘" })
const first = await openai.chat.completions.create({
model: "gpt-4.1-mini",
messages,
tools,
tool_choice: "auto",
});
const assistantMessage = first.choices[0].message;
messages.push(assistantMessage);
if (handleToolCalls(assistantMessage, messages)) {
const second = await openai.chat.completions.create({
model: "gpt-4.1-mini",
messages,
});
messages.push(second.choices[0].message);
console.log(second.choices[0].message.content);
}