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

= = =

相关推荐
2601_962885721 小时前
把行情 DataFrame 喂给 ChatGPT/Claude 分析:prompt 工作流
chatgpt·prompt
一缕82年的清风1 小时前
当团队全员都在用 Coding Agent:为什么生产环境代码通胀与架构债务反而激增了?
chatgpt·claude
sbjdhjd17 小时前
AI产业周度动态:从“更强模型”走向“可执行、可治理、可计价”的系统竞争 (2026年10月19日—10月25日)
人工智能·笔记·ai·开源·gemini·信息差·claude code
小年糕是糕手1 天前
【AI】用 Python 做一个 AI 截图检索助手:把收藏夹里的截图找回来
linux·人工智能·python·chatgpt·agent·codex·deepseek
shennv8881 天前
Codex 5小时限额和周限额是什么意思?2026年 ChatGPT Plus、Pro 用量机制详解
chatgpt
shennv8881 天前
2026年国内如何开通ChatGPT Plus和Pro?订阅方式、Codex额度及常见问题整理
人工智能·chatgpt
Ai-_Man1 天前
Microsoft Copilot对话数据怎么导入到另外一个Microsoft Copilot账号里去?AI导出鸭
开发语言·javascript·人工智能·microsoft·chatgpt·ecmascript·copilot
死磕音视频2 天前
ChatGPT 语音入门:用 Live 模式做英语口语陪练
chatgpt·口语练习·ai学习·语音对话
远航计算机2 天前
收录从分钟级变 3 到 7 天,抢首发为什么失效了
大数据·人工智能·爬虫·chatgpt·aigc·1024程序员节
奈落242 天前
从“你问它答”到“它主动推”:ChatGPT Pulse 把记忆、反馈和日历变成一条信息策划流水线
人工智能·chatgpt·ai 编程