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

= = =

相关推荐
win4r7 小时前
🚀开发者必看!深度测评谷歌Gemini 3 Pro + Antigravity IDE!对比Claude Sonnet 4.5前端编程巅峰对决!模型能力是否被
google·aigc·gemini
coder_pig10 小时前
【AI省流快讯】Cloudflare 炸了 / Gemini 3 来了 / Antigravity 独家实测 (附:无法登录解法)
google·ai编程·gemini
该用户已不存在12 小时前
Gemini 3.0 发布,Antigravity 掀桌,程序员何去何从?
后端·ai编程·gemini
算家计算14 小时前
Gemini 3.0重磅发布!技术全面突破:百万上下文、全模态推理与开发者生态重构
人工智能·资讯·gemini
无法飞15 小时前
从 GPT-4 到 Gemini 3 Pro:一个五子棋游戏见证的 AI 两年进化史
gemini
std78791 天前
谷歌推“Cameyo”方案,助力企业从Win系统转型ChromeOS
google
权泽谦1 天前
新世代的 C++:当 ChatGPT 遇上模板元编程
开发语言·c++·chatgpt
陈天伟教授1 天前
人工智能技术- 语音语言- 03 ChatGPT 对话、写诗、写小说
人工智能·chatgpt
智算菩萨2 天前
GPT-5.1:在 GPT-5 能力基线之上的体验升级、自适应推理与安全新范式
人工智能·机器学习·chatgpt
量子位2 天前
Gemini 3“超前点映”效果炸场,巴菲特305亿重仓谷歌
ai编程·gemini·trae