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

= = =

相关推荐
程序员佳佳5 小时前
【万字硬核】从零构建企业级AI中台:基于Vector Engine整合GPT-5.2、Sora2与Veo3的落地实践指南
人工智能·gpt·chatgpt·ai作画·aigc·api·ai编程
sinat_2869451910 小时前
opencode
人工智能·算法·chatgpt
小溪彼岸13 小时前
Gemini CLI V0.22发布了Conductor和Endor Labs并向Free Tier用户开放了Gemini 3
google·gemini
Blossom.11817 小时前
大模型自动化压缩:基于权重共享的超网神经架构搜索实战
运维·人工智能·python·算法·chatgpt·架构·自动化
开发者导航17 小时前
【开发者导航】ChatGPT Atlas 开源平替,一款免费的AI浏览器,让网页自动驾驶!
人工智能·chatgpt
赫尔·普莱蒂科萨·帕塔2 天前
医疗新纪元的开启
人工智能·chatgpt
TOPGUS2 天前
黑帽GEO手法揭秘:AI搜索阴影下的新型搜索劫持与风险
人工智能·搜索引擎·chatgpt·aigc·谷歌·数字营销
光锥智能3 天前
蚂蚁阿福月活用户已达3000万,OpenAI跟进发布ChatGPT Health
人工智能·chatgpt
空山新雨后、3 天前
Masked AutoEncoder(MAE)详解:高 Mask 率如何造就强视觉表征
人工智能·深度学习·chatgpt·多模态
数据猿3 天前
产业共振:数据猿与永洪科技共塑数智未来
人工智能·科技·chatgpt