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

= = =

相关推荐
阿拉斯攀登3 小时前
Embedding 模型选择与领域适配
人工智能·chatgpt·embedding·agent·ai编程·loop·rag
VIP_CQCRE5 小时前
OpenAI Chat Completion API 接入指南:用 Ace Data Cloud 快速把 ChatGPT 能力接进业务系统
人工智能·chatgpt·openai·api·acedatacloud
Coffeeee7 小时前
从 Android 15 到 Android 17,谷歌猝不及防的音频改动
android·前端·google
孤狼GPT8 小时前
2026年7月怎么充GPT会员?先分清Plus、Pro、Codex和API
人工智能·gpt·chatgpt·codex
Mr.Daozhi8 小时前
从零构建 AI 学术论文助手(四):PDF.js 实时截图 + Gemini 视觉分析
javascript·人工智能·pdf·canvas·pdf.js·gemini
云卷云舒___________9 小时前
Gemini 3.5 Pro或17日发布、Grok Imagine新增15秒视频生成、GPT-5.6 Sol 跑30小时超Opus | 7月5日 AI日报
华为·ai·grok·视频生成·gemini·ai日报·gpt56
oscar9991 天前
Codex 编程智能体入门指南
ai·chatgpt·codex
云卷云舒___________1 天前
Google Gemini 3.5 Pro泄露、GPT-5.6套餐限额放宽、Meta Watermelon追平GPT-5.5 | 7月4日 AI日报
google·meta·openai·gemini·ai日报·gpt56·watermelon
云栖梦泽在1 天前
Claude Code / Codex 使用卡顿怎么办?AI 编程 Agent 连接失败与网络排查思路
网络·人工智能·网络协议·chatgpt·性能优化
阿拉斯攀登1 天前
AI Agent 入门:从 ChatGPT 到自主智能体
人工智能·chatgpt·agent·ai编程·loop