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

= = =

相关推荐
OpenBayes贝式计算15 小时前
教程上新丨一键部署Gemma 4 31B,最高256K上下文,能力媲美Qwen3.5 397B
google·开源·llm
ChoSeitaku16 小时前
NO.3|接入ChatGPT|Gemini|Ollama本地接入DeepSeek
人工智能·chatgpt
时光之源18 小时前
一场关于红绿灯检测项目的辩论赛——YOLOv26
深度学习·yolo·grok·gemini·deepseek
GEO索引未来20 小时前
为什么做GEO需要一套好的数据系统?
大数据·人工智能·ai·chatgpt·googlecloud
恁这是弄啥咧1 天前
美国地址生成器网站 做SEO再也不愁了,谷歌浏览器Chrome重要升级,结合了Gemini!
chrome·gemini
华科大胡子1 天前
Gemini实战——用AI写CI/CD脚本
gemini
yuntier2 天前
Antigravity 登录失败怎么排?从 Account not eligible 到 oauth-success`的实操修复
google
jimmyleeee2 天前
人工智能基础知识笔记三十九:几个Skills的网站
人工智能·笔记·chatgpt
人道领域2 天前
2026年3月大模型全景深度解析:国产登顶、百万上下文落地、Agent工业化,AI实用时代全面来临[特殊字符]
大数据·人工智能·chatgpt·大模型
学习前端的小z2 天前
【AIGC】ChatGPT 的 Prompt Hacker 技巧:让简历轻松通过 AI 筛选
chatgpt·prompt·aigc