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

= = =

相关推荐
二妹的三爷17 小时前
2026实测:Gemini 3镜像官网 上下文记忆在持续迭代式产品需求文档维护中的深度应用
gemini
绘梨衣5471 天前
Agentic RAG、传统RAG、ReAct、Function Calling 核心关系
人工智能·chatgpt·tensorflow
qq5680180761 天前
国内如何使用Gemini 3.1 Pro?
chatgpt·ai作画·ai编程·ai写作·agi
whyfail1 天前
AI 平台订阅套餐 Coding Plan 、Token Plan对比指南(2026年4月)
人工智能·ai·chatgpt·订阅套餐·平台对比
小龙报1 天前
【Coze-AI智能体平台】低代码省时高效:Coze 应用开发全流程指南
java·人工智能·python·深度学习·低代码·chatgpt·交互
大写的老王1 天前
2026年AI工具终极对比:豆包、DeepSeek、元宝、ChatGPT、Cursor,谁才是你的最佳搭档?
人工智能·chatgpt
Agent产品评测局1 天前
流程型制造业生产节拍智能调整,落地方法与案例 | 2026工业AI Agent架构全景解析
人工智能·ai·chatgpt·架构
蔡俊锋1 天前
AI进阶运营:从信息爆炸到智能掌控
人工智能·chatgpt·ai进阶运营
yaodong5181 天前
ChatGPT-Image-2 绘图实战:国内镜像站 Prompt 工程指南及多模型对比
gpt·chatgpt·prompt