Gemini API를 사용한 함수 호출 | Google AI for Developers
함수 호출을 사용하면 모델을 외부 도구 및 API에 연결할 수 있습니다. 모델은 텍스트 응답을 생성하는 대신 특정 함수를 호출해야 하는 시점을 파악하고 실제 작업을 실행하는 데 필요한 매개변수를 제공합니다. 이를 통해 모델은 자연어와 실제 작업 및 데이터 간의 연결고리 역할을 할 수 있습니다. 함수 호출에는 3가지 주요 사용 사례가 있습니다.
- 지식 보강: 데이터베이스, API, 기술 자료와 같은 외부 소스의 정보에 액세스합니다.
- 기능 확장: 외부 도구를 사용하여 계산을 수행하고 계산기 사용 또는 차트 생성과 같은 모델의 제한사항을 확장합니다.
- 작업 실행: API를 사용하여 외부 시스템과 상호작용합니다(예: 일정 예약, 인보이스 생성, 이메일 전송, 스마트 홈 기기 제어).
구조화된 출력 | Gemini API | Google AI for Developers
제공된 JSON 스키마를 준수하는 대답을 생성하도록 Gemini 모델을 구성할 수 있습니다. 이 기능을 사용하면 예측 가능하고 파싱 가능한 결과를 보장하고, 형식 및 유형 안전성을 보장하며, 거부를 프로그래매틱 방식으로 감지하고, 프롬프트를 간소화할 수 있습니다.

구조화된 출력과 함수 호출은 모두 JSON 스키마를 사용하지만 용도가 다릅니다.
기능 기본 사용 사례 구조화된 출력 사용자에게 전송할 최종 응답의 서식을 지정합니다. 모델의 답변이 특정 형식이어야 하는 경우 (예: 문서에서 데이터를 추출하여 데이터베이스에 저장) 사용합니다. 함수 호출 대화 중에 조치를 취합니다. 모델이 작업을 수행하도록 요청해야 하는 경우 (예: '현재 날씨 가져와')를 요청해야 최종 답변을 제공할 수 있습니다.
AI가 중간에 실제로 무언가를 실행하고 그 결과를 다시 AI가 받아서 처리하기보다는 더 단순하게 비속어 리스트들을 JSON 포맷으로 바꾸는 변환 처리
굳이 함수 호출이라는 개념을 빌려오지 않고, 구조화된 출력으로 응답을 JSON 스키마로 달라고 해도 될 것 같음
Gemini API 문서 예시 코드
import { GoogleGenAI } from "@google/genai";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
const ingredientSchema = z.object({
name: z.string().describe("Name of the ingredient."),
quantity: z.string().describe("Quantity of the ingredient, including units."),
});
const recipeSchema = z.object({
recipe_name: z.string().describe("The name of the recipe."),
prep_time_minutes: z.number().optional().describe("Optional time in minutes to prepare the recipe."),
ingredients: z.array(ingredientSchema),
instructions: z.array(z.string()),
});
const ai = new GoogleGenAI({});
const prompt = `
Please extract the recipe from the following text.
The user wants to make delicious chocolate chip cookies.
They need 2 and 1/4 cups of all-purpose flour, 1 teaspoon of baking soda,
1 teaspoon of salt, 1 cup of unsalted butter (softened), 3/4 cup of granulated sugar,
3/4 cup of packed brown sugar, 1 teaspoon of vanilla extract, and 2 large eggs.
For the best part, they'll need 2 cups of semisweet chocolate chips.
First, preheat the oven to 375°F (190°C). Then, in a small bowl, whisk together the flour,
baking soda, and salt. In a large bowl, cream together the butter, granulated sugar, and brown sugar
until light and fluffy. Beat in the vanilla and eggs, one at a time. Gradually beat in the dry
ingredients until just combined. Finally, stir in the chocolate chips. Drop by rounded tablespoons
onto ungreased baking sheets and bake for 9 to 11 minutes.
`;
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: prompt,
config: {
responseMimeType: "application/json",
responseJsonSchema: zodToJsonSchema(recipeSchema),
},
});
const recipe = recipeSchema.parse(JSON.parse(response.text));
console.log(recipe);
응답 예시
{
"recipe_name": "Delicious Chocolate Chip Cookies",
"ingredients": [
{
"name": "all-purpose flour",
"quantity": "2 and 1/4 cups"
},
{
"name": "baking soda",
"quantity": "1 teaspoon"
},
{
"name": "salt",
"quantity": "1 teaspoon"
},
{
"name": "unsalted butter (softened)",
"quantity": "1 cup"
},
{
"name": "granulated sugar",
"quantity": "3/4 cup"
},
{
"name": "packed brown sugar",
"quantity": "3/4 cup"
},
{
"name": "vanilla extract",
"quantity": "1 teaspoon"
},
{
"name": "large eggs",
"quantity": "2"
},
{
"name": "semisweet chocolate chips",
"quantity": "2 cups"
}
],
"instructions": [
"Preheat the oven to 375°F (190°C).",
"In a small bowl, whisk together the flour, baking soda, and salt.",
"In a large bowl, cream together the butter, granulated sugar, and brown sugar until light and fluffy.",
"Beat in the vanilla and eggs, one at a time.",
"Gradually beat in the dry ingredients until just combined.",
"Stir in the chocolate chips.",
"Drop by rounded tablespoons onto ungreased baking sheets and bake for 9 to 11 minutes."
]
}