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

= = =

相关推荐
云天AI实战派15 分钟前
ChatGPT / Realtime API / 智能体故障排查指南:语音模型、浏览器会话与权限问题全流程解决方案
人工智能·chatgpt
YJlio1 小时前
2023-09-25:ChatGPT 开始支持“看、听、说”,从纯文本正式迈向多模态交互
人工智能·python·科技·chatgpt·django·交互·pygame
YJlio1 小时前
ChatGPT 2023年8月28日更新解读:ChatGPT Enterprise发布,AI正式进入企业级办公场景
chatgpt·openai·数据安全·gpt-4·enterprise·企业级ai·高级数据分析
星辰徐哥13 小时前
AI时代最容易上手的5个副业,月入5000+
人工智能·ai·chatgpt·工具·副业·ai副业
●VON13 小时前
四大AI生图工具横评:GPT Image 2 一骑绝尘!但Gemini的免费策略才是真正的王炸
人工智能·gpt·chatgpt·大模型·image
云天AI实战派16 小时前
AI 智能体/API 调用故障排查指南:实时语音、Codex 权限与 Spec 驱动开发全流程修复手册
人工智能·驱动开发·chatgpt·api·codex
Agent产品评测局21 小时前
制造业考勤智能管理系统,主流AI Agent方案横评:2026年企业级自动化选型深度指南
运维·人工智能·ai·chatgpt·自动化
Android出海1 天前
ChatGPT降智怎么恢复?GPT-5.4降智原因与恢复方法
人工智能·gpt·ai·chatgpt·openai
人道领域1 天前
2026 AI编程助手终极选型指南(Claude Code vs Codex vs Gemini):国内外智能体与大模型全景对比,性价比最高的选择
人工智能·ai编程·claude·gemini