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

= = =

相关推荐
Carson带你学Android2 小时前
Google I/O 2026:Android 开发,Agent 时代来了
google·ai编程·google io
searchforAI3 小时前
5款AI笔记工具实测:导入体验、结构化输出、后续能力逐项对比
人工智能·笔记·学习·ai·chatgpt·aigc·音视频
视觉&物联智能13 小时前
【杂谈】-游戏生成数据:人工智能训练中极易被低估的核心资源
人工智能·游戏·ai·chatgpt·openai·agi·deepseek
沅柠-AI营销19 小时前
ChatGPT GEO深度拆解:从专业底层逻辑到高阶流量壁垒的完整打法
人工智能·chatgpt·数据分析·品牌营销·ai搜索优化·geo优化
嗝o゚1 天前
昇腾CANN cann-recipes-train 仓:在大模型上做微调是什么体验
人工智能·chatgpt·cann
Rocky Ding*1 天前
昔日AI绘画框架王者Stable Diffusion WebUI,已死
人工智能·深度学习·机器学习·chatgpt·ai作画·stable diffusion·aigc
环信即时通讯云1 天前
AI圈今日大事(2026-05-21)
人工智能·阿里云·ai·google·芯片·qwen·gemini
dayuOK63072 天前
AI内容创作工具的下一个战场:从“生成”到“全流程自动化”
运维·人工智能·chatgpt·职场和发展·自动化·新媒体运营·媒体
jovi_AI电报2 天前
ChatGPT 对话太多,之前聊的好东西找不到了
人工智能·chatgpt
像一阵风。2 天前
【技术复盘】基于 Web 接口的 ChatGPT Plus 订阅风控破局与免密全自动续费实践
人工智能·chatgpt