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


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

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

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

프로젝트 설정

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

함수 호출 설정

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

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

API 요청 예

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

API 응답 예시

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

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

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

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

func makeAPIRequest(currencyFrom: String,
                    currencyTo: String) -> JSONObject {
  // This hypothetical API returns a JSON such as:
  // {"base":"USD","rates":{"SEK": 0.091}}
  return [
    "base": .string(currencyFrom),
    "rates": .object([currencyTo: .number(0.091)]),
  ]
}

2단계: 함수 선언 만들기

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

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

let getExchangeRate = FunctionDeclaration(
  name: "getExchangeRate",
  description: "Get the exchange rate for currencies between countries",
  parameters: [
    "currencyFrom": Schema(
      type: .string,
      description: "The currency to convert from."
    ),
    "currencyTo": Schema(
      type: .string,
      description: "The currency to convert to."
    ),
  ],
  requiredParameters: ["currencyFrom", "currencyTo"]
)

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

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

// Use a model that supports function calling, like a Gemini 1.5 model
let generativeModel = GenerativeModel(
  name: "gemini-1.5-flash",
  apiKey: apiKey,
  // Specify the function declaration.
  tools: [Tool(functionDeclarations: [getExchangeRate])]
)

4단계: 함수 호출 생성

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

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

let chat = generativeModel.startChat()

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

// Send the message to the generative model
let response1 = try await chat.sendMessage(prompt)

// Check if the model responded with a function call
guard let functionCall = response1.functionCalls.first else {
  fatalError("Model did not respond with a function call.")
}
// Print an error if the returned function was not declared
guard functionCall.name == "getExchangeRate" else {
  fatalError("Unexpected function called: \(functionCall.name)")
}
// Verify that the names and types of the parameters match the declaration
guard case let .string(currencyFrom) = functionCall.args["currencyFrom"] else {
  fatalError("Missing argument: currencyFrom")
}
guard case let .string(currencyTo) = functionCall.args["currencyTo"] else {
  fatalError("Missing argument: currencyTo")
}

// Call the hypothetical API
let apiResponse = makeAPIRequest(currencyFrom: currencyFrom, currencyTo: currencyTo)

// Send the API response back to the model so it can generate a text response that can be
// displayed to the user.
let response = try await chat.sendMessage([ModelContent(
  role: "function",
  parts: [.functionResponse(FunctionResponse(
    name: functionCall.name,
    response: apiResponse
  ))]
)])

// Log the text response.
guard let modelResponse = response.text else {
  fatalError("Model did not respond with text.")
}
print(modelResponse)