【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 小时前
各个模型rate limit汇总
chatgpt
酷尔。3 小时前
Gemini学生认证、订阅方法和常见问题的解决方法
ai·googlecloud·使用教程·gemini
景联文科技3 小时前
景联文AI观察动态速递 第3期
人工智能·chatgpt
蜡笔小嘟7 小时前
使用gemini 3 pro实现可视化大屏
前端·ai·gemini·gemini3peo
L_cl8 小时前
【NLP 79、强化学习串讲】
人工智能·chatgpt
500佰8 小时前
解读NotebookLM基于AI的PTT生成 程序化处理方法
前端·google·程序员
LinkTime_Cloud8 小时前
OpenAI 拉响红色警报,以突击式提升 ChatGPT
人工智能·chatgpt
中國龍在廣州10 小时前
李飞飞最新思考:语言模型救不了机器人
人工智能·深度学习·算法·语言模型·自然语言处理·chatgpt·机器人
Nerve1 天前
GooglePay: API 文档
android·google
Nerve1 天前
GooglePay: 订阅商品购买流程
android·google