함수 호출 튜토리얼

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

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

자세한 내용은 함수 호출 소개를 참고하세요.

조명 제어를 위한 API의 예

애플리케이션 프로그래밍 인터페이스 (API)가 있는 기본 조명 제어 시스템이 있으며 사용자가 간단한 텍스트 요청을 통해 조명을 제어할 수 있도록 한다고 가정해 보겠습니다. 함수 호출 기능을 사용하여 사용자의 광원 변경 요청을 해석하고 API 호출로 변환하여 광원 값을 설정할 수 있습니다. 이 가상의 조명 제어 시스템을 사용하면 두 개의 개별 매개변수로 정의된 빛의 밝기와 색상 온도를 제어할 수 있습니다.

파라미터 유형 필수 설명
brightness 숫자 0~100 사이의 빛 밝기입니다. 0은 꺼져 있고 100은 최대 밝기입니다.
colorTemperature 문자열 조명 기구의 색상 온도입니다(daylight, cool, warm일 수 있음).

편의상 이 가상의 조명 시스템에는 하나의 광원만 있으므로 사용자는 방이나 위치를 지정할 필요가 없습니다. 다음은 조명 제어 API에 전송하여 일광 색상 온도를 사용하여 조도를 50%로 변경하도록 할 수 있는 JSON 요청의 예입니다.

{
  "brightness": "50",
  "colorTemperature": "daylight"
}

이 튜토리얼에서는 Gemini API에 대한 함수 호출을 설정하여 사용자의 조명 요청을 해석하고 이를 API 설정에 매핑하여 조명의 밝기 및 색상 온도 값을 제어하는 방법을 보여줍니다.

시작하기 전에: 프로젝트 및 API 키 설정

Gemini API를 호출하기 전에 프로젝트를 설정하고 API 키를 구성해야 합니다.

API 함수 정의

API 요청을 하는 함수를 만듭니다. 이 함수는 애플리케이션의 코드 내에서 정의해야 하지만 애플리케이션 외부의 서비스나 API를 호출할 수 있습니다. Gemini API는 이 함수를 직접 호출하지 않으므로 애플리케이션 코드를 통해 이 함수가 실행되는 방법과 시기를 제어할 수 있습니다. 시연을 위해 이 튜토리얼에서는 요청된 조명 값만 반환하는 모의 API 함수를 정의합니다.

func setLightValues(brightness: String,
                    colorTemp: String) -> JSONObject {
  // This mock API returns the requested lighting values
  return [
    "brightness": .string(brightness),
    "colorTemperature": .string(colorTemp)
  ]
}

함수 선언 만들기

생성 모델에 전달할 함수 선언을 만듭니다. 모델에서 사용할 함수를 선언할 때는 함수 및 매개변수 설명에 최대한 많은 세부정보를 포함해야 합니다. 생성 모델은 이 정보를 사용하여 선택할 함수를 결정하고 함수 호출의 매개변수 값을 제공하는 방법을 결정합니다. 다음 코드는 조명 제어 함수를 선언하는 방법을 보여줍니다.

let controlLightFunctionDeclaration = FunctionDeclaration(
  name: "controlLight",
  description: "Set the brightness and color temperature of a room light.",
  parameters: [
    "brightness": Schema(
      type: .string,
      description: "Light level from 0 to 100. Zero is off and 100 is full brightness."
    ),
    "colorTemperature": Schema(
      type: .string,
      description: "Color temperature of the light fixture which can be `daylight`, `cool` or `warm`."
    ),
  ],
  requiredParameters: ["brightness", "colorTemperature"]
)

모델 초기화 중 함수 선언

모델에서 함수 호출을 사용하려면 모델 객체를 초기화할 때 함수 선언을 제공해야 합니다. 모델의 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: [controlLightFunctionDeclaration])]
)

함수 호출 생성

함수 선언으로 모델을 초기화한 후에는 정의된 함수를 사용하여 모델에 프롬프트를 표시할 수 있습니다. 채팅 프롬프팅 (sendMessage())을 사용하는 함수 호출을 사용해야 합니다. 일반적으로 함수 호출에는 이전 프롬프트와 응답의 컨텍스트가 있으면 이점이 있기 때문입니다.

let chat = generativeModel.startChat()

let prompt = "Dim the lights so the room feels cozy and warm."

// 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 == "controlLight" else {
  fatalError("Unexpected function called: \(functionCall.name)")
}
// Verify that the names and types of the parameters match the declaration
guard case let .string(brightness) = functionCall.args["brightness"] else {
  fatalError("Missing argument: brightness")
}
guard case let .string(colorTemp) = functionCall.args["colorTemperature"] else {
  fatalError("Missing argument: colorTemperature")
}

// Call the hypothetical API
let apiResponse = setLightValues(brightness: brightness, colorTemperature: colorTemp)

// 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)