함수 호출을 사용하면 생성 모델에서 구조화된 데이터 출력을 더 쉽게 얻을 수 있습니다. 그런 다음 이러한 출력을 사용하여 다른 API를 호출하고 관련 응답 데이터를 모델에 반환할 수 있습니다. 즉, 함수 호출은 생성된 콘텐츠에 가장 정확한 최신 정보가 포함되도록 생성 모델을 외부 시스템에 연결하는 데 도움이 됩니다.
Gemini 모델에 함수 설명을 제공할 수 있습니다. 이러한 함수는 앱의 언어로 작성하는 함수입니다 (즉, Google Cloud Functions가 아님). 모델이 쿼리를 처리할 수 있도록 함수를 호출하고 결과를 돌려보내도록 요청할 수 있습니다.
아직 확인하지 않았다면 함수 호출 소개를 확인하여 자세히 알아보세요.
프로젝트 설정
Gemini API를 호출하기 전에 API 키 설정, SDK 패키지 설치, 모델 초기화를 포함하여 프로젝트를 설정해야 합니다.
함수 호출 설정
이 튜토리얼에서는 모델이 다음 매개변수를 지원하는 가상의 통화 환율 API와 상호작용하도록 합니다.
매개변수 | 유형 | 필수 | 설명 |
---|---|---|---|
currencyDate
|
문자열 | 예 | 의 환율을 가져올 날짜(항상 YYYY-MM-DD 형식이어야 하며 기간이 지정되지 않은 경우 latest 값이어야 함) |
currencyFrom |
문자열 | 예 | 변환할 통화 |
currencyTo |
문자열 | 아니요 | 변환할 통화 |
API 요청 예
{
"currencyDate": "2024-04-17",
"currencyFrom": "USD",
"currencyTo": "SEK"
}
API 응답 예시
{
"base": "USD",
"date": "2024-04-17",
"rates": {"SEK": 0.091}
}
1단계: API 요청을 하는 함수 만들기
아직 API 요청을 하지 않았다면 먼저 API 요청을 하는 함수를 만듭니다.
이 가이드에서는 시연을 위해 실제 API 요청을 전송하는 대신 실제 API에서 반환하는 것과 동일한 형식으로 하드코딩된 값을 반환합니다.
func exchangeRate(currencyDate string,
currencyFrom string, currencyTo string) map[string]any {
// This hypothetical API returns a JSON such as:
// {"base":"USD","date":"2024-04-17","rates":{"SEK": 0.091}}
return map[string]any{
"base": currencyFrom,
"date": currencyDate,
"rates": map[string]any{currencyTo: 0.091}}
}
2단계: 함수 선언 만들기
생성 모델에 전달할 함수 선언을 만듭니다(이 가이드의 다음 단계).
함수와 매개변수 설명에 최대한 많은 세부정보를 포함합니다. 생성 모델은 이 정보를 사용하여 선택할 함수와 함수 호출 시 매개변수의 값을 제공하는 방법을 결정합니다.
currencyExchangeTool := &genai.Tool{
FunctionDeclarations: []*genai.FunctionDeclaration{{
Name: "exchangeRate",
Description: "Lookup currency exchange rates by date",
Parameters: &genai.Schema{
Type: genai.TypeObject,
Properties: map[string]*genai.Schema{
"currencyDate": {
Type: genai.TypeString,
Description: "A date that must always be in YYYY-MM-DD format" +
" or the value 'latest' if a time period is not specified",
},
"currencyFrom": {
Type: genai.TypeString,
Description: "Currency to convert from",
},
"currencyTo": {
Type: genai.TypeString,
Description: "Currency to convert to",
},
},
Required: []string{"currencyDate", "currencyFrom"},
},
}},
}
3단계: 모델 초기화 중 함수 선언 지정
생성 모델을 초기화할 때 모델의 Tools
매개변수에 함수 선언을 전달하여 지정합니다.
// ...
currencyExchangeTool := &genai.Tool{
// ...
}
// Use a model that supports function calling, like a Gemini 1.5 model
model := client.GenerativeModel("gemini-1.5-flash")
// Specify the function declaration.
model.Tools = []*genai.Tool{currencyExchangeTool}
4단계: 함수 호출 생성
이제 정의된 함수를 사용하여 모델에 프롬프트를 표시할 수 있습니다.
함수 호출은 채팅의 멀티턴 구조에 잘 맞으므로 채팅 인터페이스를 통해 함수 호출을 사용하는 것이 좋습니다.
// Start new chat session.
session := model.StartChat()
prompt := "How much is 50 US dollars worth in Swedish krona?"
// Send the message to the generative model.
resp, err := session.SendMessage(ctx, genai.Text(prompt))
if err != nil {
log.Fatalf("Error sending message: %v\n", err)
}
// Check that you got the expected function call back.
part := resp.Candidates[0].Content.Parts[0]
funcall, ok := part.(genai.FunctionCall)
if !ok {
log.Fatalf("Expected type FunctionCall, got %T", part)
}
if g, e := funcall.Name, currencyExchangeTool.FunctionDeclarations[0].Name; g != e {
log.Fatalf("Expected FunctionCall.Name %q, got %q", e, g)
}
fmt.Printf("Received function call response:\n%q\n\n", part)
apiResult := map[string]any{
"base": "USD",
"date": "2024-04-17",
"rates": map[string]any{"SEK": 0.091}}
// Send the hypothetical API result back to the generative model.
fmt.Printf("Sending API result:\n%q\n\n", apiResult)
resp, err = session.SendMessage(ctx, genai.FunctionResponse{
Name: currencyExchangeTool.FunctionDeclarations[0].Name,
Response: apiResult,
})
if err != nil {
log.Fatalf("Error sending message: %v\n", err)
}
// Show the model's response, which is expected to be text.
for _, part := range resp.Candidates[0].Content.Parts {
fmt.Printf("%v\n", part)
}