【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:

= = =

相关推荐
Liekkas Kono5 小时前
Codex(ChatGPT 桌面版)支持SSH连接远程服务器
chatgpt·ssh·swhl
xiakq11 小时前
5 分钟接入 GPT-5.6 完整指南
gpt·openai·claude·gemini·anthropic
AI大模型-小华12 小时前
ChatGPT充值后Codex误改数据库怎么办?用迁移审查避免数据丢失
数据库·chatgpt·codex·chatgpt plus·chatgpt pro·chatgpt充值
AI大模型-小雄12 小时前
ChatGPT充值后Codex接口频繁出现429?用限流与退避机制稳定任务执行
chatgpt·codex·chatgpt plus·chatgpt pro·接口限流·chatgpt充值
HAHAXX812 小时前
ChatGPT 4o + RPA 自动化工具:一站式业务流程开发实战指南
chatgpt·自动化·rpa
gptAI_plus13 小时前
别把整个仓库塞给 AI:用 Python 生成安全的代码上下文清单
python·chatgpt
AI大模型-小华13 小时前
ChatGPT充值后Codex越优化接口越慢?用性能基线避免无效重构
chatgpt·重构·codex·chatgpt plus·chatgpt pro·chatgpt充值
薛瑄1 天前
国内一键下载配置 Claude Code、ChatGPT、Codex 使用第三方API,详细图文教程
chatgpt
AI大模型-小华1 天前
ChatGPT充值后Codex还是反复读取项目?用上下文复用率判断Plus还是Pro
chatgpt·ai编程·codex·chatgpt plus·chatgpt pro·chatgpt充值
仙逆GPT1 天前
ChatGPT、Codex实战:离开电脑后,怎么用手机继续控制任务?
chatgpt·ai编程·codex·手机控制·remote