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

= = =

相关推荐
全栈弄潮儿7 小时前
开始 AI 编程前,到底需要准备什么?
chatgpt·openai·ai编程
全栈弄潮儿9 小时前
AI 编程是什么?5 个真实开发场景带你快速入门
chatgpt·openai·ai编程
yuluo_YX9 小时前
什么是 OpenAI Responses API?
人工智能·chatgpt
吨吨ai12 小时前
ChatGPT Plus / Pro 如何用好 Codex?AGENTS.md、测试闭环与 AI Code Review 实战
人工智能·chatgpt·代码复审
AI导出鸭1 天前
怎么让千问做表格?AI导出鸭苹果版将千问输出的管道表格智能解析为二维结构,一键导出为Excel或Word标准表格。
人工智能·chatgpt·word·excel·ai导出鸭
南方程序猴1 天前
Windows一键安装Codex所有环境
人工智能·gpt·ai·chatgpt·ai编程
Summer-Bright1 天前
深度 | 当 AI 替你上网:浏览器智能体 2026 的入口之争、成本坍塌与可靠性上限
人工智能·ai·chatgpt·agi·ai应用
%d%d21 天前
Windows 本地部署小红书 MCP + OpenAI Tunnel + ChatGPT 接入全流程
windows·chatgpt
王莹月1 天前
nano banana pro 怎么用?生图接口返回的图别直接存链接:nano banana pro / gpt-image-2 出图结果的落库与转存
gpt·ai·chatgpt·ai作画·aigc·agi
天天有money2 天前
Claude 中转站用于报告生成:会议纪要、周报和项目复盘怎么提效
gpt·ai·chatgpt