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

= = =

相关推荐
nvvas18 分钟前
AI互联网辅助工具
人工智能·chatgpt
小虚竹4 小时前
1.6万字测评:deepseek-r1-0528横向对比 gemini-2.5-pro-0506和claude4
claude·gemini·deepseek
量子位5 小时前
ChatGPT 普通会员能用编程神器 Codex 了!支持联网,奥特曼:更多更新在路上
chatgpt·ai编程
AmazingKO5 小时前
5分钟申请edu邮箱【方案本周有效】
python·chatgpt·ai编程·竹相左边·edu教育邮箱
哪吒编程6 小时前
基于Gemini 2.5 Pro打造的AI智能体CanvasX上线,绘制常见图表(折线图、柱状图等),国内直接使用
aigc·gemini
laughing9988 小时前
独立域名,免费服务器,无限活跃工作流--n8n免费部署
google·产品·工作流引擎
爱吃的小肥羊1 天前
GPT-5 确定 7月发布?似乎不是谣言!
chatgpt·openai
zhaoolee1 天前
一次借助ChatGPT抵御恶意攻击的经历,为个人服务器添加自动防御系统Fail2ban
运维·服务器·chatgpt
AIWritePaper智能写作探索1 天前
manus对比ChatGPT-Deep reaserch进行研究类论文数据分析!谁更胜一筹?
人工智能·chatgpt·aigc·智能写作·manus·claude4
程序员爱钓鱼1 天前
Go Modules 详解 -《Go语言实战指南》
后端·google·go