함수 호출을 사용하면 생성 모델에서 구조화된 데이터 출력을 더 쉽게 얻을 수 있습니다. 그런 다음 이러한 출력을 사용하여 다른 API를 호출하고 관련 응답 데이터를 모델에 반환할 수 있습니다. 즉, 함수 호출은 생성된 콘텐츠에 가장 정확한 최신 정보가 포함되도록 생성 모델을 외부 시스템에 연결하는 데 도움이 됩니다.
Gemini 모델에 함수 설명을 제공할 수 있습니다. 이러한 함수는 앱의 언어로 작성하는 함수입니다 (즉, Google Cloud Functions가 아님). 모델이 쿼리를 처리할 수 있도록 함수를 호출하고 결과를 돌려보내도록 요청할 수 있습니다.
아직 확인하지 않았다면 함수 호출 소개를 확인하여 자세히 알아보세요.
프로젝트 설정
Gemini API를 호출하기 전에 API 키 설정, SDK 패키지 설치, 모델 초기화를 포함하여 프로젝트를 설정해야 합니다.
함수 호출 설정
이 튜토리얼에서는 모델이 다음 매개변수를 지원하는 가상의 통화 환율 API와 상호작용하도록 합니다.
매개변수 | 유형 | 필수 | 설명 |
---|---|---|---|
currencyFrom |
문자열 | 예 | 변환할 통화 |
currencyTo |
문자열 | 예 | 변환할 통화 |
API 요청 예
{
"currencyFrom": "USD",
"currencyTo": "SEK"
}
API 응답 예시
{
"base": "USD",
"rates": {"SEK": 0.091}
}
1단계: API 요청을 하는 함수 만들기
아직 API 요청을 하지 않았다면 먼저 API 요청을 하는 함수를 만듭니다.
이 가이드에서는 시연을 위해 실제 API 요청을 전송하는 대신 실제 API에서 반환하는 것과 동일한 형식으로 하드코딩된 값을 반환합니다.
async function makeApiRequest(currencyFrom, currencyTo) {
// This hypothetical API returns a JSON such as:
// {"base":"USD","rates":{"SEK": 0.091}}
return {
base: currencyFrom,
rates: { [currencyTo]: 0.091 },
};
}
2단계: 함수 선언 만들기
생성 모델에 전달할 함수 선언을 만듭니다(이 가이드의 다음 단계).
함수와 매개변수 설명에 최대한 많은 세부정보를 포함합니다. 생성 모델은 이 정보를 사용하여 선택할 함수와 함수 호출 시 매개변수의 값을 제공하는 방법을 결정합니다.
// Function declaration, to pass to the model.
const getExchangeRateFunctionDeclaration = {
name: "getExchangeRate",
parameters: {
type: "OBJECT",
description: "Get the exchange rate for currencies between countries",
properties: {
currencyFrom: {
type: "STRING",
description: "The currency to convert from.",
},
currencyTo: {
type: "STRING",
description: "The currency to convert to.",
},
},
required: ["currencyTo", "currencyFrom"],
},
};
// Executable function code. Put it in a map keyed by the function name
// so that you can call it once you get the name string from the model.
const functions = {
getExchangeRate: ({ currencyFrom, currencyTo }) => {
return makeApiRequest( currencyFrom, currencyTo)
}
};
3단계: 모델 초기화 중 함수 선언 지정
생성 모델을 초기화할 때 모델의 tools
매개변수를 설정하여 함수 선언을 지정합니다.
const { GoogleGenerativeAI } = require("@google/generative-ai");
// Access your API key as an environment variable (see "Set up your API key" above)
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
// ...
const generativeModel = genAI.getGenerativeModel({
// Use a model that supports function calling, like a Gemini 1.5 model
model: "gemini-1.5-flash",
// Specify the function declaration.
tools: {
functionDeclarations: [getExchangeRateFunctionDeclaration],
},
});
4단계: 함수 호출 생성
이제 정의된 함수를 사용하여 모델에 프롬프트를 표시할 수 있습니다.
함수 호출은 채팅의 멀티턴 구조에 잘 맞으므로 채팅 인터페이스를 통해 함수 호출을 사용하는 것이 좋습니다.
const chat = generativeModel.startChat();
const prompt = "How much is 50 US dollars worth in Swedish krona?";
// Send the message to the model.
const result = await chat.sendMessage(prompt);
// For simplicity, this uses the first function call found.
const call = result.response.functionCalls()[0];
if (call) {
// Call the executable function named in the function call
// with the arguments specified in the function call and
// let it call the hypothetical API.
const apiResponse = await functions[call.name](call.args);
// Send the API response back to the model so it can generate
// a text response that can be displayed to the user.
const result2 = await chat.sendMessage([{functionResponse: {
name: 'getExchangeRate',
response: apiResponse
}}]);
// Log the text response.
console.log(result2.response.text());
}