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

= = =

相关推荐
c++服务器开发15 小时前
一文详解Character AI:实用指南+ ChatGPT、Gemini对比分析
人工智能·chatgpt
程序员鱼皮20 小时前
用 AI 制作超长视频,保姆级教程!
google·程序员·aigc
程序员爱钓鱼1 天前
Go语言项目工程化 —— 日志、配置、错误处理规范
后端·google·go
香宝的最强后援XD1 天前
Cursor无限邮箱续费方法
语言模型·chatgpt·文心一言
程序员爱钓鱼1 天前
Go语言实战指南 —— Go中的反射机制:reflect 包使用
后端·google·go
明似水11 天前
ChatGPT:人工智能对话革命的里程碑与未来展望
人工智能·chatgpt
伊泽瑞尔11 天前
打造极致聊天体验:uz-chat——全端AI聊天组件来了!
后端·chatgpt·openai
摆烂工程师11 天前
此账号无法订阅Google One AI Pro 解决方法 (This account isn’t eligible for Google AI plan)
前端·后端·google
小虎卫远程打卡app12 天前
自动驾驶避障思考
人工智能·chatgpt·自动驾驶
白云如幻12 天前
最新免费使用GPT4.0大模型、deepseek-r1、claude-3-7,GPT-4o AI绘画,有这一个网站就够了
chatgpt·aigc·deepseek