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

= = =

相关推荐
川川菜鸟8 小时前
用一句完整提示词,直接做出一个“球球大作战”级小游戏
gpt·gemini
nunca_te_rindas10 小时前
Gemini初体验
ai·chatgpt·gemini·deepseek
shandianchengzi11 小时前
【记录】Github|Github账号意外被封以及不需要手机号解封的全过程(被封原因:一台设备上登录过多个账号)
github·gemini
云雾J视界21 小时前
当算法试图解决一切:技术解决方案主义的诱惑与陷阱
算法·google·bert·transformer·attention·算法治理
成富1 天前
Chat Agent UI,类似 ChatGPT 的聊天界面,Spring AI 应用的测试工具
java·人工智能·spring·ui·chatgpt
魁首1 天前
Gemini CLI 深度源码:从零到一理解 AI 命令行代理的设计与实现
ai编程·gemini·mcp
Sherlock Ma1 天前
OpenAI新论文!GPT-5-Thinking新训练方法
人工智能·gpt·深度学习·语言模型·自然语言处理·chatgpt·openai
2501_940975801 天前
AIGC时代下的论文查重:从工具选择到操作指南
人工智能·chatgpt·aigc
热点速递1 天前
AI竞争升级:OpenAI在三场“战争”中拉响红色警报,全力聚焦ChatGPT!
人工智能·chatgpt