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

= = =

相关推荐
Hello_wshuo14 小时前
FreeCAD配置MCP使用chatgpt
chatgpt
盘古开天166616 小时前
windows鱼塘可交互鱼群动态桌面资源
人工智能·chatgpt·开源
枫叶丹417 小时前
从一次推理请求出发:模型、显存、网络与服务系统如何共同决定性能
网络·人工智能·chatgpt·开源·agent·codex
YH552698419 小时前
怎么看 OpenAI 的 Pro 订阅取消 5x 和 20x 的描述?
人工智能·chatgpt
Frag0ut21 小时前
Chrome Dev 最新功能更新:AI 智能体开发工具、HTML-in-Canvas 与双周更新节奏
chrome·google·dev·webmcp·最新功能·双周更新
Helix2502 天前
Chrome 性能优化实战:内存节省、硬件加速与 Flags 设置,让浏览器更流畅
chrome·google·性能优化·内存占用·硬件加速·设置技巧·浏览器优化
Helix2502 天前
Chrome 标签页管理术:分组、固定、搜索与恢复,告别标签页混乱
chrome·google·分组·标签页管理·固定标签·标签页恢复
Helix2503 天前
Chrome 快捷键效率提升:10 个常用快捷键,把浏览速度提升一个量级
chrome·google·浏览器·使用技巧·效率工具·快捷键·爆红教程
海盗12344 天前
AI 新闻日报 2026-10-01:OpenAI 把 ChatGPT 变成智能体平台,VS Code 上线多模型编排,国产算力补到内核层
人工智能·chatgpt·机器人·人工智能aigc
枫叶丹44 天前
AI 进入日常工作后,任务应该怎样重新拆分
人工智能·chatgpt·开源·agent·codex