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

= = =

相关推荐
一缕82年的清风1 天前
告别手动搬砖!我是如何搭出一套“AI 全自动自媒体运营系统”,每天 10 分钟铺满 7 大平台的?
chatgpt·claude·gemini
可乐ea3 天前
智能体的模型列表为什么要从三处来源合成:一次让 GPT-6.1 Sol 选不上的发布延迟
人工智能·gpt·chatgpt·智能体框架·模型列表·多源数据合成·客户端工程
一缕82年的清风4 天前
再见 Flash!Google 突发 Gemini 4 Hydrogen(氢):和“碳基大脑”打配合的极速工兵有多猛?
gemini
云卷云舒___________4 天前
突发:Gemini 4 Hydrogen内测,Grok 4.8推送,Qwen Code 1.0开源,格局一夜生变 | AI日报11.12
google·qwen·grok·gemini·xai·ai日报·qwencode
沉默王二5 天前
Gemini 4 Carbon 正式开放,正面硬刚 Fable 5.2。
ai编程·gemini·vibecoding
dozenyaoyida5 天前
AI与大模型新闻日报 | 2026-11-11
人工智能·chatgpt·大模型·新闻
一缕82年的清风5 天前
Claude Code 跑 DeepSeek 还带自动切号?开源 Magpie 彻底把大厂的协议护城河给拆了!
chatgpt·claude·gemini
云卷云舒___________6 天前
突发:Gemini 4 Hydrogen现身,美团开源LongCat-2.5,Meta Muse Ember追平Haiku 5.5 | 11月10日 AI日报
meta·美团·gemini·开源模型·ai日报·longcat·haiku
一缕82年的清风7 天前
没买显卡,我用 Google Colab 免费跑通了 AI 生图:从零部署 Z-Image Turbo
gpt·claude·gemini
Spidermanbaout8 天前
Prompt-Engineering实战-2026年11月2日
人工智能·机器学习·ai·chatgpt·ai编程