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

= = =

相关推荐
沉默王二4 小时前
谷歌真争气啊,这下可以爽用Gemini了。
openai·agent·gemini
ndz14 小时前
怎么查 ChatGPT / Perplexity 会不会推荐你的品牌
chatgpt
星恒随风1 天前
从0实现C++ AI大模型接入SDK(二):AI知识科普——从图灵测试到ChatGPT,人工智能的发展历程
linux·c++·人工智能·笔记·chatgpt
沉默王二1 天前
Gemini 4 Neon+Antigravity,干活真猛啊。
google·agent·gemini
可夫小子1 天前
Agent 接了上百个工具就变慢变贵?Gemini 把工具加载改成了按需检索
agent·ai编程·gemini
可夫小子2 天前
Inkling 2 Mini 实测解析:26.4B 模型把中间层循环跑 3 遍,20GB 内存塞进笔记本
ai编程·gemini
bryant_meng4 天前
ChatGPT Desktop Model Evolution (2025): From GPT-4.1 to GPT-5.1
gpt·chatgpt·gpt4·gpt4o·gpt5
一缕82年的清风4 天前
谷歌甩出 Gemini 4 Neon:Agent 编程榜登顶第一、缓存仅 $0.15,把刚发的 GPT-6.2 架在火上烤!
gpt·claude·gemini
stormzhangV5 天前
Google 重返第一梯队
人工智能·google·aigc
一缕82年的清风5 天前
OpenAI 突发 GPT-6.2:Sol 提速 8 倍跑分追平旗舰,但这 1 处暗改会让缓存直接失效!
gpt·chatgpt