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

= = =

相关推荐
RaymondZhao3416 小时前
【全面推导】策略梯度算法:公式、偏差方差与进化
人工智能·深度学习·算法·机器学习·chatgpt
VincentHe20 小时前
Gemini CLI:自定义斜杠命令
gemini
lisuwen1161 天前
GPT-5 上线风波深度复盘:从口碑两极到策略调整,OpenAI 的变与不变
大数据·人工智能·gpt·chatgpt
kymjs张涛1 天前
零一开源|前沿技术周刊 #12
ios·google·github
量子位2 天前
4o-mini华人领队也离职了,这次不怪小扎
openai·gemini
程序员爱钓鱼2 天前
Go语言实战案例-实现分页查询接口
后端·google·go
lisuwen1163 天前
AI三国杀:马斯克炮轰苹果“偏袒”OpenAI,Grok与ChatGPT的应用商店战争揭秘
人工智能·chatgpt
暮小暮3 天前
从ChatGPT到智能助手:Agent智能体如何颠覆AI应用
人工智能·深度学习·神经网络·ai·语言模型·chatgpt
John_ToDebug3 天前
大模型提示词(Prompt)终极指南:从原理到实战,让AI输出质量提升300%
人工智能·chatgpt·prompt
CodeDevMaster3 天前
Gemini Balance:轻松实现Gemini API负载均衡与无缝切换的终极指南
负载均衡·api·gemini