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


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

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

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

프로젝트 설정

Gemini API를 호출하기 전에 Android 프로젝트를 설정해야 합니다. 여기에는 API 키 설정, Android 프로젝트에 SDK 종속 항목 추가, 모델 초기화가 포함됩니다.

함수 호출 설정

이 튜토리얼에서는 모델이 다음 매개변수를 지원하는 가상의 통화 환율 API와 상호작용하도록 합니다.

매개변수 유형 필수 설명
currencyFrom 문자열 변환할 통화
currencyTo 문자열 변환할 통화

API 요청 예

{
  "currencyFrom": "USD",
  "currencyTo": "SEK"
}

API 응답 예시

{
  "base": "USD",
  "rates": {"SEK": 0.091}
}

1단계: API 요청을 하는 함수 만들기

아직 API 요청을 하지 않았다면 먼저 API 요청을 하는 함수를 만듭니다.

이 가이드에서는 시연을 위해 실제 API 요청을 전송하는 대신 실제 API에서 반환하는 것과 동일한 형식으로 하드코딩된 값을 반환합니다.

suspend fun makeApiRequest(
    currencyFrom: String,
    currencyTo: String
): JSONObject {
    // This hypothetical API returns a JSON such as:
    // {"base":"USD","rates":{"SEK": 0.091}}
    return JSONObject().apply {
        put("base", currencyFrom)
        put("rates", hashMapOf(currencyTo to 0.091))
    }
}

2단계: 함수 선언 만들기

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

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

val getExchangeRate = defineFunction(
  name = "getExchangeRate",
  description = "Get the exchange rate for currencies between countries",
  Schema.str("currencyFrom", "The currency to convert from."),
  Schema.str("currencyTo", "The currency to convert to.")
) { from, to ->
    // Call the function that you declared above
    makeApiRequest(from, to)
}

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

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

val generativeModel = GenerativeModel(
  // Use a model that supports function calling, like a Gemini 1.5 model
  modelName = "gemini-1.5-flash",
  // Access your API key as a Build Configuration variable (see "Set up your API key" above)
  apiKey = BuildConfig.apiKey,
  // Specify the function declaration.
  tools = listOf(Tool(listOf(getExchangeRate)))
)

4단계: 함수 호출 생성

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

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

val chat = generativeModel.startChat()

val prompt = "How much is 50 US dollars worth in Swedish krona?"

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

// Check if the model responded with a function call
response.functionCall?.let { functionCall ->
  // Try to retrieve the stored lambda from the model's tools and
  // throw an exception if the returned function was not declared
  val matchedFunction = generativeModel.tools?.flatMap { it.functionDeclarations }
      ?.first { it.name == functionCall.name }
      ?: throw InvalidStateException("Function not found: ${functionCall.name}")

  // Call the lambda retrieved above
  val apiResponse: JSONObject = matchedFunction.execute(functionCall)

  // Send the API response back to the generative model
  // so that it generates a text response that can be displayed to the user
  response = chat.sendMessage(
    content(role = "function") {
        part(FunctionResponsePart(functionCall.name, apiResponse))
    }
  )
}

// Whenever the model responds with text, show it in the UI
response.text?.let { modelResponse ->
    println(modelResponse)
}