Gemini API 빠른 시작

이 빠른 시작에서는 원하는 SDK를 사용하여 Gemini API를 시작하는 방법을 보여줍니다.

기본 요건

Python

Google AI에서 보기 Google Colab에서 실행 GitHub에서 노트북 보기

이 빠른 시작을 로컬에서 완료하려면 개발 환경이 다음 요구사항을 충족하는지 확인하세요.

  • Python 3.9 이상
  • 노트북을 실행할 jupyter 설치

Go

이 빠른 시작에서는 Go로 애플리케이션을 빌드하는 데 익숙하다고 가정합니다.

이 빠른 시작을 완료하려면 개발 환경이 다음 요구사항을 충족하는지 확인하세요.

  • Go 1.20 이상

Node.js

이 빠른 시작에서는 사용자가 Node.js로 애플리케이션을 빌드하는 데 익숙하다고 가정합니다.

이 빠른 시작을 완료하려면 개발 환경이 다음 요구사항을 충족하는지 확인하세요.

  • Node.js v18 이상
  • npm

이 빠른 시작에서는 자바스크립트를 사용하여 웹 앱을 개발하는 데 익숙하다고 가정합니다. 이 가이드는 프레임워크와 무관합니다.

이 빠른 시작을 완료하려면 개발 환경이 다음 요구사항을 충족하는지 확인하세요.

  • (선택사항) Node.js
  • 최신 웹브라우저

Dart (Flutter)

이 빠른 시작에서는 Dart로 애플리케이션을 빌드하는 데 익숙하다고 가정합니다.

이 빠른 시작을 완료하려면 개발 환경이 다음 요구사항을 충족하는지 확인하세요.

  • Dart 3.2.0 이상

Swift

이 빠른 시작에서는 Xcode를 사용하여 Swift 앱을 개발하는 데 익숙하다고 가정합니다.

이 빠른 시작을 완료하려면 개발 환경과 Swift 앱이 다음 요구사항을 충족하는지 확인하세요.

  • Xcode 15.0 이상
  • Swift 앱이 iOS 15 이상 또는 macOS 12 이상을 타겟팅해야 합니다.

Android

이 빠른 시작에서는 Android 스튜디오를 사용하여 Android 앱을 개발하는 데 익숙하다고 가정합니다.

이 빠른 시작을 완료하려면 개발 환경과 Android 앱이 다음 요구사항을 충족해야 합니다.

  • Android 스튜디오 (최신 버전)
  • Android 앱은 API 수준 21 이상을 타겟팅해야 합니다.

API 키 설정

Gemini API를 사용하려면 API 키가 필요합니다. 아직 키가 없으면 Google AI Studio에서 키를 만듭니다

API 키 가져오기

그런 다음 키를 구성합니다.

Python

버전 제어 시스템에 API 키를 체크인하지 않는 것이 좋습니다. 이 빠른 시작에서는 API 키에 환경 변수로 액세스한다고 가정합니다.

API 키를 환경 변수에 할당합니다.

export API_KEY=<YOUR_API_KEY>

Go

버전 제어 시스템에 API 키를 체크인하지 않는 것이 좋습니다. 이 빠른 시작에서는 API 키에 환경 변수로 액세스한다고 가정합니다.

API 키를 환경 변수에 할당합니다.

export API_KEY=<YOUR_API_KEY>

Node.js

버전 제어 시스템에 API 키를 체크인하지 않는 것이 좋습니다. 이 빠른 시작에서는 API 키에 환경 변수로 액세스한다고 가정합니다.

API 키를 환경 변수에 할당합니다.

export API_KEY=<YOUR_API_KEY>

버전 제어 시스템에 API 키를 체크인하지 않는 것이 좋습니다. 대신 모델을 초기화하기 직전에 API 키를 앱에 전달해야 합니다.

이 빠른 시작에서는 API 키에 전역 상수로 액세스한다고 가정합니다.

Dart (Flutter)

버전 제어 시스템에 API 키를 체크인하지 않는 것이 좋습니다. 이 빠른 시작에서는 API 키에 프로세스 환경 변수로 액세스한다고 가정합니다. Flutter 앱을 개발하는 경우 앱을 실행할 때 프로세스 환경이 달라지므로 String.fromEnvironment를 사용하고 --dart-define=API_KEY=$API_KEYflutter build 또는 flutter run에 전달하여 API 키로 컴파일할 수 있습니다.

Swift

버전 제어 시스템에 API 키를 체크인하지 않는 것이 좋습니다. 한 가지 대체 옵션은 GenerativeAI-Info.plist 파일에 저장한 후 .plist 파일에서 API 키를 읽는 것입니다. 이 .plist 파일을 앱의 루트 폴더에 저장하고 버전 제어에서 제외해야 합니다.

enum APIKey {
   // Fetch the API key from `GenerativeAI-Info.plist`
   static var `default`: String {
      guard let filePath = Bundle.main.path(forResource: "GenerativeAI-Info", ofType: "plist")
      else {
         fatalError("Couldn't find file 'GenerativeAI-Info.plist'.")
      }
      let plist = NSDictionary(contentsOfFile: filePath)
      guard let value = plist?.object(forKey: "API_KEY") as? String else {
         fatalError("Couldn't find key 'API_KEY' in 'GenerativeAI-Info.plist'.")
      }
      if value.starts(with: "_") {
         fatalError(
           "Follow the instructions at https://ai.google.dev/tutorials/setup to get an API key."
         )
      }
      return value
   }
}

Android

버전 제어 시스템에 API 키를 체크인하지 않는 것이 좋습니다. 대신 local.properties 파일 (프로젝트 루트 디렉터리에 있지만 버전 제어에서 제외됨)에 저장한 후 Android용 Secrets Gradle 플러그인을 사용하여 API 키를 빌드 구성 변수로 읽어야 합니다.

Kotlin:

// Access your API key as a Build Configuration variable
val apiKey = BuildConfig.apiKey

Java

// Access your API key as a Build Configuration variable
String apiKey = BuildConfig.apiKey;

Secrets Gradle 플러그인의 구현을 확인하려면 이 SDK의 샘플 앱을 검토하거나 Gemini API Starter 템플릿(시작하는 데 사용할 local.properties 파일이 포함되어 있음)이 포함된 Android 스튜디오 Iguana의 최신 미리보기를 사용하면 됩니다.

SDK 설치

Python

Gemini API용 Python SDK는 google-generativeai 패키지에 포함되어 있습니다. pip를 사용하여 종속 항목을 설치합니다.

pip install -q -U google-generativeai

Go

자체 애플리케이션에서 Gemini API를 사용하려면 모듈 디렉터리에서 Go SDK 패키지를 get해야 합니다.

go get github.com/google/generative-ai-go

Node.js

자체 애플리케이션에서 Gemini API를 사용하려면 Node.js용 GoogleGenerativeAI 패키지를 설치해야 합니다.

npm install @google/generative-ai

자체 웹 앱에서 Gemini API를 사용하려면 @google/generative-ai를 가져옵니다.

<script type="importmap">
   {
     "imports": {
       "@google/generative-ai": "https://esm.run/@google/generative-ai"
     }
   }
</script>

Dart (Flutter)

자체 애플리케이션에서 Gemini API를 사용하려면 google_generative_ai 패키지를 Dart 또는 Flutter 앱에 add해야 합니다.

Dart:

dart pub add google_generative_ai

Flutter:

flutter pub add google_generative_ai

Swift

자체 Swift 앱에서 Gemini API를 사용하려면 GoogleGenerativeAI 패키지를 앱에 추가합니다.

  1. Xcode의 프로젝트 탐색기에서 프로젝트를 마우스 오른쪽 버튼으로 클릭합니다.

  2. 컨텍스트 메뉴에서 Add Packages를 선택합니다.

  3. Add Packages 대화상자에서 검색창에 패키지 URL을 붙여넣습니다. none https://github.com/google/generative-ai-swift

  4. 패키지 추가를 클릭합니다. 이제 Xcode가 GoogleGenerativeAI 패키지를 프로젝트에 추가합니다.

Android

  1. 모듈 (앱 수준) Gradle 구성 파일 (예: <project>/<app-module>/build.gradle.kts)에서 Android용 Google AI SDK의 종속 항목을 추가합니다.

    Kotlin:

    dependencies {
    
       // add the dependency for the Google AI client SDK for Android
       implementation("com.google.ai.client.generativeai:generativeai:0.3.0")
    }
    

    Java

    Java의 경우 라이브러리 두 개를 추가해야 합니다.

    dependencies {
    
        // add the dependency for the Google AI client SDK for Android
        implementation("com.google.ai.client.generativeai:generativeai:0.3.0")
    
        // Required for one-shot operations (to use `ListenableFuture` from Guava Android)
        implementation("com.google.guava:guava:31.0.1-android")
    
        // Required for streaming operations (to use `Publisher` from Reactive Streams)
        implementation("org.reactivestreams:reactive-streams:1.0.4")
    }
    
  2. Android 프로젝트를 Gradle 파일과 동기화합니다.

생성 모델 초기화

Python

API를 호출하려면 먼저 생성 모델을 가져오고 초기화해야 합니다.

import google.generativeai as genai

genai.configure(api_key=os.environ["API_KEY"])
model = genai.GenerativeModel('gemini-pro')

Go

API를 호출하려면 먼저 생성 모델을 가져오고 초기화해야 합니다.

import "github.com/google/generative-ai-go/genai"
import "google.golang.org/api/option"

ctx := context.Background()
// Access your API key as an environment variable (see "Set up your API key" above)
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
    log.Fatal(err)
}
defer client.Close()

// For text-only input, use the gemini-pro model
model := client.GenerativeModel("gemini-pro")

Node.js

API를 호출하려면 먼저 생성 모델을 가져오고 초기화해야 합니다.

const { GoogleGenerativeAI } = require("@google/generative-ai");

// Access your API key as an environment variable (see "Set up your API key" above)
const genAI = new GoogleGenerativeAI(process.env.API_KEY);

// ...

// For text-only input, use the gemini-pro model
const model = genAI.getGenerativeModel({ model: "gemini-pro"});

// ...

API를 호출하려면 먼저 생성 모델을 가져오고 초기화해야 합니다.

<html>
<body>
   <!-- ... Your HTML and CSS -->
   <!-- Import @google/generative-ai, as shown above. -->
   <script type="module">
      import { GoogleGenerativeAI } from "@google/generative-ai";

      // Fetch your API_KEY
      const API_KEY = "...";

      // Access your API key (see "Set up your API key" above)
      const genAI = new GoogleGenerativeAI(API_KEY);

      // ...

      // For text-only input, use the gemini-pro model
      const model = genAI.getGenerativeModel({ model: "gemini-pro"});

      // ...
   </script>
</body>
</html>

Dart (Flutter)

API를 호출하려면 먼저 생성 모델을 가져오고 초기화해야 합니다.

import 'package:google_generative_ai/google_generative_ai.dart';

// Access your API key as an environment variable (see "Set up your API key" above)
final apiKey = Platform.environment['API_KEY'];
if (apiKey == null) {
  print('No \$API_KEY environment variable');
  exit(1);
}

// For text-only input, use the gemini-pro model
final model = GenerativeModel(model: 'gemini-pro', apiKey: apiKey);

Swift

API를 호출하려면 먼저 생성 모델을 초기화해야 합니다.

  1. GoogleAI 모듈을 가져옵니다.

    import GoogleGenerativeAI
    
  2. 생성 모델을 초기화합니다.

    // For text-only input, use the gemini-pro model
    // Access your API key from your on-demand resource .plist file (see "Set up your API key" above)
    let model = GenerativeModel(name: "gemini-pro", apiKey: APIKey.default)
    

Android

API를 호출하려면 먼저 GenerativeModel 객체를 초기화해야 합니다.

Kotlin:

val generativeModel = GenerativeModel(
      // For text-only input, use the gemini-pro model
      modelName = "gemini-pro",
      // Access your API key as a Build Configuration variable (see "Set up your API key" above)
      apiKey = BuildConfig.apiKey
)

Java

자바의 경우 GenerativeModelFutures 객체도 초기화해야 합니다.

// For text-only input, use the gemini-pro model
GenerativeModel gm = new GenerativeModel(/* modelName */ "gemini-pro",
// Access your API key as a Build Configuration variable (see "Set up your API key" above)
      /* apiKey */ BuildConfig.apiKey);

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

텍스트 생성

Python

response = model.generate_content("Write a story about a magic backpack.")
print(response.text)

Go

resp, err := model.GenerateContent(ctx, genai.Text("Write a story about a magic backpack."))
if err != nil {
  log.Fatal(err)
}

Node.js

async function run() {
  const prompt = "Write a story about a magic backpack."

  const result = await model.generateContent(prompt);
  const response = await result.response;
  const text = response.text();
  console.log(text);
}

run();

async function run() {
  const prompt = "Write a story about a magic backpack."

  const result = await model.generateContent(prompt);
  const response = await result.response;
  const text = response.text();
  console.log(text);
}

run();

Dart (Flutter)

void main() async {
   // Access your API key as an environment variable (see "Set up your API key" above)
   final apiKey = Platform.environment['API_KEY'];
   if (apiKey == null) {
      print('No \$API_KEY environment variable');
      exit(1);
   }
   // For text-only input, use the gemini-pro model
   final model = GenerativeModel(model: 'gemini-pro', apiKey: apiKey);
   final content = [Content.text('Write a story about a magic backpack.')];
   final response = await model.generateContent(content);
   print(response.text);
}

Swift

let prompt = "Write a story about a magic backpack."
let response = try await model.generateContent(prompt)
if let text = response.text {
  print(text)
}

Android

Kotlin:

generateContent()는 정지 함수이며 코루틴 범위에서 호출되어야 합니다. 코루틴에 관해 잘 모른다면 Android의 Kotlin 코루틴을 참고하세요.

val prompt = "Write a story about a magic backpack."
val response = generativeModel.generateContent(prompt)
print(response.text)

Java

generateContent()ListenableFuture를 반환합니다. 이 API에 익숙하지 않으면 ListenableFuture 사용에 관한 Android 문서를 참고하세요.

Content content = new Content.Builder()
      .addText("Write a story about a magic backpack.")
      .build();

Executor executor = // ...

ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
      @Override
      public void onSuccess(GenerateContentResponse result) {
         String resultText = result.getText();
         System.out.println(resultText);
      }

      @Override
      public void onFailure(Throwable t) {
         t.printStackTrace();
      }
}, executor);

다음 단계

Gemini API 작업에 관한 자세한 내용은 선택한 언어의 가이드를 참고하세요.

curl 명령어를 사용하여 Gemini API를 사용해 볼 수도 있습니다.

생성형 AI 모델을 처음 사용하는 경우 빠른 시작을 사용해 보기 전에 개념 가이드Gemini API 개요를 살펴보는 것이 좋습니다.