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

= = =

相关推荐
ShineWinsu10 小时前
对于ProtoBuffer:ProtoBuffer的介绍以及安装
linux·网络·google·协议·序列化·反序列化·protobuffer
zhyongrui12 小时前
Codex 桌面端汉化:从菜单到主界面的实现思路
chatgpt·codex·汉化·easygpt
枫叶丹413 小时前
AI 的记忆不是数据库:长期个性化如何避免过期与污染
人工智能·chatgpt·开源·agent·codex
浅安的邂逅14 小时前
260926-OpenAI 急停最强模型训练:智能体借 DNS 漏洞联网,还泄露了 GitHub token
人工智能·chatgpt·开源·openai·ai日报
shionhana7 天前
AI PPT 生成的两个关键环节:结构生成和视觉生成,以 PPTMaker 为例
人工智能·chatgpt·agent·ppt
Ztiddler8 天前
Codex重新连接解决方法
chatgpt·openai·codex
I Am a robert girl8 天前
谷歌迈出RSI一大步:从Gemini模型迭代看AI工程化的新风向
人工智能·大模型·gemini·ai工程化·上下文工程·rsi·工具链集成
吨吨ai8 天前
Codex 长会话上下文管理:会话拆分与状态交接的工程化实践
chatgpt
守城小轩8 天前
AcBoter 多账号管理指南:隐私与设置选项(五)
chatgpt·codex·acboter
ServBay9 天前
ChatGPT Pro 20X 限时回归
gpt·chatgpt·openai