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

= = =

相关推荐
嘿嘿-663 小时前
Windows 一键使用 GPT-6 Astra:Codex CLI 配置教程
java·人工智能·windows·gpt·chatgpt·web
ServBay7 小时前
谷歌发布 Gemini 3.8 Flash,官方跑分很厉害,但又被嘲了?
aigc·ai编程·gemini
全栈弄潮儿9 小时前
AI 编程进阶实战:我为什么要做这个专栏
chatgpt·openai·ai编程
嘿嘿-6611 小时前
gpt-6-astra测试,测试你的模型有没有降智
人工智能·gpt·chatgpt·web
大模型码小白12 小时前
ChatGPT 的回答也能被结构化抓取?AI Bot Scraper 对比测评
服务器·开发语言·数据库·人工智能·spring·chatgpt
deepseek2313 小时前
Google Gemini Agentic Video 上线:88% 少 token 的主动取样如何改写长视频理解
python·多模态·ai agent·gemini·视频理解
顿哥GPT14 小时前
ChatGPT Plus / Pro + Codex 深度实战指南(2026年9月5日):从模型能力对比到 Codex 自动化编程工作流全解析
人工智能·chatgpt·自动化
天衍四九-14 小时前
Agent Skills从入门到工程化(十六):面试中如何讲清楚 Agent Skills?
大数据·数据库·人工智能·python·chatgpt·面试
野区小女王1 天前
Codex 接入 DeepSeek-V4-Flash保姆级教程
gpt·chatgpt
嘿嘿-661 天前
GPT-6 Astra 新手快速上手指南
人工智能·gpt·ai·chatgpt·ai编程