Vertex AI의 Gemini API를 사용하여 텍스트 생성

이 문서에서는 Swift용 Google Cloud 클라이언트 라이브러리를 사용하여 Vertex AI의 Gemini API에 텍스트 및 멀티모달 요청을 전송하고 응답을 읽는 방법을 보여줍니다.

시작하기 전에

이 문서의 단계를 완료하려면 결제가 사용 설정되고 Vertex AI API가 사용 설정된 Google Cloud 프로젝트가 필요합니다. Vertex AI 모델을 사용하면 요금이 청구됩니다. 자세한 내용은 Vertex AI 가격 책정을 참조하세요.

  1. Vertex AI 설정 가이드에 따라 프로젝트를 설정하고 Vertex AI API를 사용 설정합니다.
  2. 빠른 시작: Swift 시작하기에 따라 Swift 클라이언트 라이브러리를 설정합니다.
  3. 주 구성원에게 Vertex AI 사용자 Identity and Access Management(IAM) 역할(roles/aiplatform.user) 또는 aiplatform.endpoints.predict 권한이 있는지 확인합니다.

Vertex AI 클라이언트 라이브러리 추가

swift-google-cloud-aiplatform-v1 패키지와 GoogleCloudAIPlatformV1 모듈을 프로젝트에 추가하려면 다음 단계를 따르세요.

  1. swift-google-cloud-aiplatform-v1 패키지를 Package.swift 종속 항목에 추가합니다.

    swift package add-dependency \
        https://github.com/googleapis/swift-google-cloud-aiplatform-v1.git --from 0.6.0
    
  2. GoogleCloudAIPlatformV1 모듈을 타겟의 종속 항목으로 추가합니다.

    swift package add-target-dependency \
        GoogleCloudAIPlatformV1 TARGET_NAME \
        --package swift-google-cloud-aiplatform-v1
    

    TARGET_NAME을 대상 이름으로 바꿉니다.

텍스트 프롬프트 보내기

Vertex AI의 Gemini API에 텍스트 프롬프트를 전송하고 생성된 텍스트 응답을 읽으려면 다음 단계를 따르세요.

  1. 클라이언트 라이브러리를 사용하는 데 필요한 가져오기를 추가합니다.

    import Foundation
    import GoogleCloudAIPlatformV1

  2. 프로젝트 ID를 매개변수로 허용하는 함수를 정의합니다.

    func sample(projectId: String) async throws {

  3. 기본 설정을 사용하여 PredictionServiceClient 인스턴스를 초기화합니다.

    let client = try PredictionServiceClient()

  4. 모델 리소스 이름을 구성합니다.

    let model = "projects/\(projectId)/locations/global/publishers/google/models/gemini-3.8-flash"

  5. GenerateContentRequest 객체를 빌드하고 generateContent(request:)를 호출합니다.

    let request = GenerateContentRequest().with {
      $0.model = model
      $0.contents = [
        Content().with { content in
          content.role = "user"
          content.parts = [
            Part().with { part in
              part.data = .text(
                "What's a good name for a flower shop that specializes in selling bouquets of dried flowers?"
              )
            }
          ]
        }
      ]
    }
    let response = try await client.generateContent(request: request)

  6. promptFeedback에서 안전 차단을 확인하고 첫 번째 후보 응답에서 생성된 텍스트를 추출합니다.

    if let feedback = response.promptFeedback, feedback.blockReason != .unspecified {
      print("Prompt was blocked: \(feedback.blockReason)")
      if !feedback.blockReasonMessage.isEmpty {
        print("Reason: \(feedback.blockReasonMessage)")
      }
      return
    }
    
    guard let candidate = response.candidates.first,
      let content = candidate.content
    else {
      print("No candidate content returned.")
      return
    }
    
    for part in content.parts {
      if case .text(let text)? = part.data {
        print(text)
      }
    }

프롬프트 및 이미지 전송

이전 섹션과 동일한 Foundation 및 GoogleCloudAIPlatformV1 가져오기와 sample(projectId:) 함수 서명을 사용합니다. Cloud Storage 이미지 URI 및 텍스트 프롬프트로 멀티모달 요청을 전송하려면 다음 단계를 따르세요.

  1. PredictionServiceClient 인스턴스를 초기화합니다.

    let client = try PredictionServiceClient()

  2. 모델 리소스 이름을 구성합니다.

    let model = "projects/\(projectId)/locations/global/publishers/google/models/gemini-3.8-flash"

  3. Cloud Storage URI 및 MIME 유형을 사용하여 이미지 Part 객체를 빌드합니다.

    let imagePart = Part().with {
      $0.data = .fileData(
        FileData().with { fileData in
          fileData.mimeType = "image/jpeg"
          fileData.fileUri = "gs://generativeai-downloads/images/scones.jpg"
        }
      )
    }

  4. 프롬프트 텍스트 Part 객체를 빌드합니다.

    let textPart = Part().with {
      $0.data = .text("Describe this picture.")
    }

  5. generateContent(request:)를 사용하여 멀티모달 GenerateContentRequest 객체를 전송합니다.

    let request = GenerateContentRequest().with {
      $0.model = model
      $0.contents = [
        Content().with { content in
          content.role = "user"
          content.parts = [imagePart, textPart]
        }
      ]
    }
    let response = try await client.generateContent(request: request)

  6. promptFeedback에서 안전 차단을 확인하고 첫 번째 후보 응답에서 생성된 텍스트를 추출합니다.

    if let feedback = response.promptFeedback, feedback.blockReason != .unspecified {
      print("Prompt was blocked: \(feedback.blockReason)")
      if !feedback.blockReasonMessage.isEmpty {
        print("Reason: \(feedback.blockReasonMessage)")
      }
      return
    }
    
    guard let candidate = response.candidates.first,
      let content = candidate.content
    else {
      print("No candidate content returned.")
      return
    }
    
    for part in content.parts {
      if case .text(let text)? = part.data {
        print(text)
      }
    }

코드 완성

다음 예시에서는 두 요청의 전체 코드를 보여줍니다. 앱의 @main 비동기 진입점에서 try await sample(projectId: "PROJECT_ID")를 호출하고 PROJECT_ID를 Google Cloud 프로젝트 ID로 바꿉니다. 그런 다음 swift run을 실행하여 다음과 비슷한 출력을 인쇄합니다.

The image shows scones with blueberries and flowers next to cups of coffee.

텍스트 프롬프트

import Foundation
import GoogleCloudAIPlatformV1

func sample(projectId: String) async throws {
  let client = try PredictionServiceClient()

  let model = "projects/\(projectId)/locations/global/publishers/google/models/gemini-3.8-flash"

  let request = GenerateContentRequest().with {
    $0.model = model
    $0.contents = [
      Content().with { content in
        content.role = "user"
        content.parts = [
          Part().with { part in
            part.data = .text(
              "What's a good name for a flower shop that specializes in selling bouquets of dried flowers?"
            )
          }
        ]
      }
    ]
  }
  let response = try await client.generateContent(request: request)
  if let feedback = response.promptFeedback, feedback.blockReason != .unspecified {
    print("Prompt was blocked: \(feedback.blockReason)")
    if !feedback.blockReasonMessage.isEmpty {
      print("Reason: \(feedback.blockReasonMessage)")
    }
    return
  }

  guard let candidate = response.candidates.first,
    let content = candidate.content
  else {
    print("No candidate content returned.")
    return
  }

  for part in content.parts {
    if case .text(let text)? = part.data {
      print(text)
    }
  }
}

프롬프트 및 이미지

import Foundation
import GoogleCloudAIPlatformV1

func sample(projectId: String) async throws {
  let client = try PredictionServiceClient()

  let model = "projects/\(projectId)/locations/global/publishers/google/models/gemini-3.8-flash"

  let imagePart = Part().with {
    $0.data = .fileData(
      FileData().with { fileData in
        fileData.mimeType = "image/jpeg"
        fileData.fileUri = "gs://generativeai-downloads/images/scones.jpg"
      }
    )
  }

  let textPart = Part().with {
    $0.data = .text("Describe this picture.")
  }

  let request = GenerateContentRequest().with {
    $0.model = model
    $0.contents = [
      Content().with { content in
        content.role = "user"
        content.parts = [imagePart, textPart]
      }
    ]
  }
  let response = try await client.generateContent(request: request)
  if let feedback = response.promptFeedback, feedback.blockReason != .unspecified {
    print("Prompt was blocked: \(feedback.blockReason)")
    if !feedback.blockReasonMessage.isEmpty {
      print("Reason: \(feedback.blockReasonMessage)")
    }
    return
  }

  guard let candidate = response.candidates.first,
    let content = candidate.content
  else {
    print("No candidate content returned.")
    return
  }

  for part in content.parts {
    if case .text(let text)? = part.data {
      print(text)
    }
  }
}

다음 단계