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

= = =

相关推荐
若苗瞬3 小时前
继续提速:Llama.cpp 已经正式支持 Gemma4 MTP
google·llama·gemma·qat·mtp
DS随心转插件4 小时前
DeepSeek 代码手机端导出与 AI 辅助方案实测
android·人工智能·chatgpt·智能手机·deepseek·ai导出鸭
码农小旋风4 小时前
智能体经典范式构建
chatgpt·claude
Coffeeee4 小时前
Android17应用内存限制--App:我人不舒服,系统:那你走吧
android·google·kotlin
码农小旋风5 小时前
Agent框架开发实践
人工智能·chatgpt·claude
AI周红伟5 小时前
事件分析:FDE标准,“OpenClaw+RAG+Agent” 应用实战的标准
前端·人工智能·chrome·chatgpt·aigc
资源分享助手6 小时前
ChatGPT App接入Codex教程:手机远程管理AI编程助手
chatgpt·智能手机·ai编程
暮雪倾风6 小时前
【AI】CC switch安装与使用教程:告别繁琐配置,解锁 AI 编程 CLI 一键管理
人工智能·chatgpt·claudecode·ccswitch
若苗瞬1 天前
谷歌发布了 Gemma 4 QAT (Quantization-Aware Training) 模型
google·gemma·qat·gguf·unsloth
DS随心转APP1 天前
AI导出鸭:AI 文档排版与一键导出实战指南
人工智能·ai·chatgpt·deepseek·ai导出鸭