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

= = =

相关推荐
hsjcjh35 分钟前
多步推理引擎落地办公:用ChatGPT 5.4镜像站构建复杂文档的自动编织流水线(国内实测教程)
chatgpt
小超同学你好9 小时前
OpenClaw 深度解析系列 · 第8篇:Learning & Adaptation(学习与自适应)
人工智能·语言模型·chatgpt
Resistance丶未来14 小时前
GPT-5.5 深度评测:性能边界与实战价值全解析
gpt·大模型·api·claude·gemini·api key·gpt5.5
马丁路的King15 小时前
ChatGPT 不同档位的性价比
chatgpt
Jet450515 小时前
玩转ChatGPT:Seedance 2.0制作宣传片(Clip 04-07)
chatgpt·seedance 2.0
YJlio21 小时前
Windows Internals 读书笔记 10.3.3:Task Scheduler 架构详解
人工智能·windows·笔记·python·学习·chatgpt·架构
GEO索引未来1 天前
国内首部GEO可信传播标准立项通过/DeepSeek-V4 正式上线并开源/Open AI、Google继续推进AI广告标准化
大数据·人工智能·gpt·ai·chatgpt·开源
华科大胡子1 天前
Gemini实战:用AI写CI/CD脚本
gemini
nbwenren1 天前
2026技术实战:用ChatGPT搭建个人办公自动化流水线(国内直访方案全解析)
chatgpt
Agent产品评测局2 天前
生产排期与MES/ERP系统打通,实操方法详解:2026企业级智能体与超自动化集成实战指南
运维·人工智能·ai·chatgpt·自动化