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

= = =

相关推荐
仙逆GPT1 天前
ChatGPT、Codex工程实战:Agent接入企业知识库,文档明明更新了,为什么回答还是旧版本?
chatgpt·codex·rag·企业知识库·ai agent
lucas_AI1 天前
「无限 Codex」白嫖项目终结?OpenAI 12 月起把 ChatGPT 与 Codex 额度合成一个池子
chatgpt·openai
孤狼GPT1 天前
ChatGPT、Codex工程实战:Spring Boot的SSE一直在推送,为什么经过Nginx后前端才一次性显示?
spring boot·chatgpt·sse·codex·chatgptplus
孤狼GPT1 天前
ChatGPT、Codex性能实战:MySQL升级到8.0后,SQL没改,为什么接口P99反而翻倍?
spring boot·chatgpt·sql优化·codex·mysql8.0
星核0penstarry1 天前
视频理解模型选型指南:Gemini、Qwen、SeedRealtime 怎么选(附 API 示例)
人工智能·音视频·实时音视频·视频·gemini·vs qwen
lucas_AI2 天前
点开一条 ChatGPT 分享链接,私聊就被端了:数学键盘 + YouTube JSONP 组成的 P1 漏洞链
chatgpt
奈落242 天前
全局切换器之后:从 ChatGPT 桌面端把聊天、工作、编程并进一个窗口,看“三合一”改了什么、没改什么
chatgpt·工作流·ai 编程
dozenyaoyida3 天前
AI与大模型新闻日报 | 2026-10-30
人工智能·ai·chatgpt·大模型·新闻
LaughingZhu3 天前
Product Hunt 热榜 2026-10-30:Empacer、Scape、Floot in ChatGPT
java·前端·数据库·人工智能·chatgpt·notion
卢卡上学3 天前
WorkBuddy内配置使用Claude、ChatGPT、Gemini、Grop模型
chatgpt·中转站·腾讯workbuddy