함수 호출 튜토리얼

<ph type="x-smartling-placeholder"></ph> 를 참조하세요.

함수 호출을 통해 구조화된 데이터 출력을 더 쉽게 가져올 수 있음 살펴보겠습니다 그런 다음 이러한 출력을 사용하여 다른 API를 호출하고 모델에 전달합니다. 즉, 함수 호출은 생성 모델을 외부 시스템에 연결하여 생성된 콘텐츠가 가장 정확한 최신 정보가 포함됩니다.

Gemini 모델에 함수에 대한 설명을 제공할 수 있습니다. 이는 함수 (즉, API를 사용하지 않는 Google Cloud Functions). 모델이 함수를 호출하고 결과를 반환하도록 요청할 수 있습니다. 모델이 쿼리를 처리하는 데 도움이 됩니다.

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

조명 제어를 위한 API의 예

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

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

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

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

이 튜토리얼에서는 Gemini API에 대한 함수 호출을 설정하여 사용자의 조명 요청을 해석하고 API 설정에 매핑하여 빛의 밝기와 색상 온도 값을 변경할 수 있습니다.

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

Gemini API를 호출하기 전에 프로젝트를 설정하고 확인할 수 있습니다

API 함수 정의

API 요청을 하는 함수를 만듭니다. 이 함수는 API를 호출하지만 외부에서 서비스 또는 API를 호출할 수 있습니다. 실행할 수 있습니다 Gemini 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)