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

= = =

相关推荐
湫夨兮1 小时前
如何配置codex cli和codex app(官方已经合并,现在名字为chatgpt)
chatgpt·codex
协享科技3 小时前
2026 年 AI 表格工具怎么选:ChatGPT、原生 Copilot/Gemini 与公式助手
人工智能·chatgpt·excel·copilot
武子康1 天前
2026 开源视频生成模型全景图:按 9 类任务路由比按参数量选模型更可靠
人工智能·ai·chatgpt·openai·claude·世界模型·视频模型
dunge20261 天前
2026年7月更新:ChatGPT Pro、Plus 与 Codex 如何进入事件驱动软件架构(GPT-5.6与AI Agent技术分享)
人工智能·gpt·chatgpt
春波petal1 天前
大模型底层逻辑:优势局限与天生短板
人工智能·自然语言处理·chatgpt·大模型·多模态·语音大模型
无处安放_a1 天前
ChatGPT Agent 发布:OpenAI 把整个电脑装进了对话框
chatgpt
顿哥GPT1 天前
7月更新 ChatGPT、Codex、Pro、Plus 背后的工程难题:AI Consistency 将成为 LLM-Native 系统的下一道门槛(5.6)
人工智能·chatgpt
顿哥GPT1 天前
7月18日更新,ChatGPT Plus、ChatGPT Pro 与 Codex:未来的软件开发(GPT5.6)
chatgpt
Mac的实验室2 天前
最新注册谷歌邮箱遇到此号码验证次数过多提示 | 谷歌账号电话号码用太多次的解决办法
google