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

= = =

相关推荐
Ztiddler12 小时前
Codex重新连接解决方法
chatgpt·openai·codex
I Am a robert girl13 小时前
谷歌迈出RSI一大步:从Gemini模型迭代看AI工程化的新风向
人工智能·大模型·gemini·ai工程化·上下文工程·rsi·工具链集成
吨吨ai1 天前
Codex 长会话上下文管理:会话拆分与状态交接的工程化实践
chatgpt
守城小轩1 天前
AcBoter 多账号管理指南:隐私与设置选项(五)
chatgpt·codex·acboter
ServBay1 天前
ChatGPT Pro 20X 限时回归
gpt·chatgpt·openai
枫叶丹42 天前
开源还是开权重:2026 年 AI 模型战争的控制权之争
人工智能·chatgpt·开源·agent·codex
小猿君2 天前
Claude 入口砍到只剩一个,GPT-6 已经能自己连干 24 小时
人工智能·chatgpt·agi
4SAPI3 天前
Gemini 4 Pro 泄露参数解析:2M 上下文时代,企业如何规划 Gemini API 中转与多模型架构?
人工智能·gemini
GEO实战经验分享4 天前
王涛:GEO 服务商能力评估清单——基础、结构、战略、风控四层怎么核验
大数据·人工智能·chatgpt
FEF前端团队4 天前
04# Codex CLI实战:OpenAI的编程代理
前端·chatgpt·ai编程