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

= = =

相关推荐
fanstuck14 小时前
从0到提交,如何用 ChatGPT 全流程参与建模比赛的
大数据·数学建模·语言模型·chatgpt·数据挖掘
Minilinux20181 天前
Google ProtoBuf 简介
开发语言·google·protobuf·protobuf介绍
有颜有货1 天前
GEO(生成引擎优化)是什么?GEO的工作流程详解
人工智能·chatgpt·geo
数研小生1 天前
用爬虫数据训练 ChatGPT 行业知识库:从数据采集到模型微调的实战指南
人工智能·爬虫·chatgpt
感谢地心引力1 天前
在Chrome浏览器中使用Gemini,附一键开启方法
前端·chrome·ai·gemini
星辰引路-Lefan3 天前
Antigravity 登录问题及解决方案:Antigravity Tools 账号管理工具详解
ide·ai编程·gemini·antigravity
熙客3 天前
Claude 与 Claude Code 介绍、安装与使用
chatgpt
石去皿3 天前
Depth Viewer: 16-bit 深度图可视化工具
人工智能·chatgpt·prompt
FreeBuf_4 天前
AI扩大攻击面,大国博弈引发安全新挑战
人工智能·安全·chatgpt
B2_Proxy4 天前
亚马逊采集的正确打开方式:从合规边界到反爬博弈,再到数据价值落地
服务器·网络·网络协议·tcp/ip·chatgpt