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

= = =

相关推荐
Code_Artist17 小时前
AI 终于学会写正确的汉字了?GPT Image 2.0 到底做对了什么?
人工智能·chatgpt·openai
小郭哥x1 天前
Codex 桌面版(Windows)启动后无 UI 窗口问题
chatgpt·openai·codex
承渊政道1 天前
【大模型应用开发:基于GPT-4和ChatGPT】(深入了解GPT-4和ChatGPT的API)
chatgpt·api·gpt-4·大模型应用开发
dozenyaoyida1 天前
AI与大模型新闻日报 | 2026-10-17
人工智能·ai·chatgpt·新闻
XLYcmy2 天前
《数字经济赋能城市低碳治理的路径研究检索报告》审阅与修改指导意见——基于完整检索报告体例的完整性诊断、学术规范核查与方法论纠偏 上
数据库·ai·chatgpt·文心一言·检索·知网·豆包
Summer-Bright2 天前
浏览器成了AI应用的新入口:智能体接管标签页之后,三本账谁买单
人工智能·chatgpt·agent·浏览器·智能体
承渊政道2 天前
【大模型应用开发:基于GPT-4和ChatGPT】(初识GPT-4和ChatGPT)
chatgpt·nlp·gpt-4·大模型应用开发
小虎AI生活2 天前
ChatGPT 浏览器扩展升级详解:装扩展、给权限、派第一个活(附可抄话术)
人工智能·chatgpt·超级个体·一人公司·青玥ai
Frag0ut2 天前
Chrome 2026 AI 能力全解析:从 Auto Browse 到 Skills,浏览器正在变成智能代理
chrome·ai·谷歌浏览器·gemini·智能代理·skills·auto browse
死磕音视频3 天前
Gemini 学习功能入门:用引导学习与音频概览把资料听懂看懂
gemini·ai学习·guided learning·audio overview