튜토리얼: Gemini API로 함수 호출


함수 호출을 사용하면 생성 모델에서 구조화된 데이터 출력을 더 쉽게 얻을 수 있습니다. 그런 다음 이러한 출력을 사용하여 다른 API를 호출하고 관련 응답 데이터를 모델에 반환할 수 있습니다. 즉, 함수 호출은 생성된 콘텐츠에 가장 정확한 최신 정보가 포함되도록 생성 모델을 외부 시스템에 연결하는 데 도움이 됩니다.

Gemini 모델에 함수 설명을 제공할 수 있습니다. 이러한 함수는 앱의 언어로 작성하는 함수입니다 (즉, Google Cloud Functions가 아님). 모델이 쿼리를 처리할 수 있도록 함수를 호출하고 결과를 돌려보내도록 요청할 수 있습니다.

아직 확인하지 않았다면 함수 호출 소개를 확인하여 자세히 알아보세요.

프로젝트 설정

Gemini API를 호출하기 전에 프로젝트를 설정해야 합니다. 여기에는 API 키 설정, Pub 종속 항목에 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에서 반환하는 것과 동일한 형식으로 하드코딩된 값을 반환합니다.

Future<Map<String, Object?>> findExchangeRate(
  Map<String, Object?> arguments,
) async =>
    // This hypothetical API returns a JSON such as:
    // {"base":"USD","date":"2024-04-17","rates":{"SEK": 0.091}}
    {
      'date': arguments['currencyDate'],
      'base': arguments['currencyFrom'],
      'rates': <String, Object?>{arguments['currencyTo'] as String: 0.091}
    };

2단계: 함수 선언 만들기

생성 모델에 전달할 함수 선언을 만듭니다(이 가이드의 다음 단계).

함수와 매개변수 설명에 최대한 많은 세부정보를 포함합니다. 생성 모델은 이 정보를 사용하여 선택할 함수와 함수 호출 시 매개변수의 값을 제공하는 방법을 결정합니다.

final exchangeRateTool = FunctionDeclaration(
    'findExchangeRate',
    'Returns the exchange rate between currencies on given date.',
    Schema(SchemaType.object, properties: {
      'currencyDate': Schema(SchemaType.string,
          description: 'A date in YYYY-MM-DD format or '
              'the exact value "latest" if a time period is not specified.'),
      'currencyFrom': Schema(SchemaType.string,
          description: 'The currency code of the currency to convert from, '
              'such as "USD".'),
      'currencyTo': Schema(SchemaType.string,
          description: 'The currency code of the currency to convert to, '
              'such as "USD".')
    }, requiredProperties: [
      'currencyDate',
      'currencyFrom'
    ]));

3단계: 모델 초기화 중 함수 선언 지정

생성 모델을 초기화할 때 모델의 tools 매개변수에 함수 선언을 전달하여 지정합니다.

final model = GenerativeModel(
  // Use a model that supports function calling, like a Gemini 1.5 model
  model: 'gemini-1.5-flash',
  apiKey: apiKey,

  // Specify the function declaration.
  tools: [
    Tool(functionDeclarations: [exchangeRateTool])
  ],
);

4단계: 함수 호출 생성

이제 정의된 함수를 사용하여 모델에 프롬프트를 표시할 수 있습니다.

함수 호출은 채팅의 멀티턴 구조에 잘 맞으므로 채팅 인터페이스를 통해 함수 호출을 사용하는 것이 좋습니다.

final chat = model.startChat();
final prompt = 'How much is 50 US dollars worth in Swedish krona?';

// Send the message to the generative model.
var response = await chat.sendMessage(Content.text(prompt));

final functionCalls = response.functionCalls.toList();
// When the model response with a function call, invoke the function.
if (functionCalls.isNotEmpty) {
  final functionCall = functionCalls.first;
  final result = switch (functionCall.name) {
    // Forward arguments to the hypothetical API.
    'findExchangeRate' => await findExchangeRate(functionCall.args),
    // Throw an exception if the model attempted to call a function that was
    // not declared.
    _ => throw UnimplementedError(
        'Function not implemented: ${functionCall.name}')
  };
  // Send the response to the model so that it can use the result to generate
  // text for the user.
  response = await chat
      .sendMessage(Content.functionResponse(functionCall.name, result));
}
// When the model responds with non-null text content, print it.
if (response.text case final text?) {
  print(text);
}