【ChatGPT】【Gemini】-用Python调用google的Gemini API

用Python调用google的Gemini API

以下是Gemini自己给出的具体步骤和代码,我直接参考一次测试通过,大家可以参考。

Goodmao:Python call gemini API

Gemini:

Absolutely, calling the Gemini API with Python involves a few steps:

Prerequisites:

  1. API Key: You'll need an API key to access Gemini. You can create one easily in Google AI Studio: invalid URL removed.

  2. Python library: Install the google-generativeai library using pip:

    Bash

    复制代码
    pip install -U -q google-generativeai

    请谨慎使用代码。

Calling the API:

Here's a basic structure for calling the Gemini API for text generation:

Python

复制代码
import googleapiclient.discovery as discovery

# Replace with your API key obtained from AI Studio
API_KEY = "YOUR_API_KEY"

# Define the project ID where your Gemini model resides
PROJECT_ID = "YOUR_PROJECT_ID"

# Discovery URL for the Gemini API
service = discovery.build(
    "generativeai", "v1beta1", developerKey=API_KEY
)

# Text prompt for the model
prompt = "Write a poem about nature."

# Define the model you want to use (replace with the actual model name)
model = "your_model_name"

# Send the request with prompt and model details
body = {"prompt": prompt, "model": model}
response = service.projects().locations().models().generateText(
    parent=f"projects/{PROJECT_ID}/locations/global/models/{model}", body=body
)

# Access the generated text from the response
generated_text = response["text"]
print(generated_text)

请谨慎使用代码。

Additional functionalities:

  • List Models: Use the service.projects().locations().models().list()method to explore available models.
  • Chat Conversation: Initiate a chat session with chat = model.start_chat()and interact with the model turn-by-turn.
  • Function Calling: Enable function calling during chat by setting enable_automatic_function_calling=True in start_chat().

Resources:

= = =

相关推荐
ZhengEnCi19 小时前
韩国高考 AI 作弊:防作弊为什么总比作弊慢一步
人工智能·chatgpt
Flynt20 小时前
Google 账号被封,验证器就成了死锁?我把 Authenticator 的导出码拆到了字节层
安全·google
沉默王二21 小时前
自从吸上了Gemini,根本停不下来。
openai·agent·gemini
掘金安东尼1 天前
Google Antigravity 和 Gemini Neon:哪些行为会封号,怎么降低风险(Flavio Copes 全文转译)
人工智能·google·gemini
JasonWuuu2 天前
用惯了 Claude Code,我给 Antigravity CLI 换上了 Claude Code 的界面(开源)
ai编程·claude·gemini
枫叶丹43 天前
AI文本水印:生成机制、统计检测与误报
人工智能·机器学习·chatgpt·agent·codex
沉默王二4 天前
谷歌又搞事情,Gemini 可以在 Claude Code/Codex 中带劲蹬了。
agent·gemini·chatglm (智谱)
黄林晴4 天前
薅Google AI Ultra翻车了:本想免费用一年,结果被退订了
aigc·gemini
黄林晴4 天前
Android 开了 R8,为什么 SDK 还在阻止优化?
android·google
黄林晴4 天前
Gemini 4 Argon 来了。Android CLI 插件上线,终端 Agent 直接操控 IDE 能力
android·gemini