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

= = =

相关推荐
乾元1 小时前
安全官(CISO)的困惑:AI 投入产出比(ROI)的衡量
网络·人工智能·安全·网络安全·chatgpt·架构·安全架构
智算菩萨5 小时前
通用人工智能(AGI)的定义与ChatGPT 5.4的AGI资格评估
人工智能·ai·语言模型·chatgpt·agi
智算菩萨6 小时前
基于ChatGPT 5.4的Windows 11智能命令行维护系统:理论架构与实践应用
人工智能·python·ai·chatgpt·ai编程
视频砖家6 小时前
AI Sider: ChatGPT + DeepSeek + Gemini
人工智能·chatgpt
RskAi6 小时前
2026年GPT-5.4与Gemini3 Pro技术深度拆解:架构、性能与国内镜像站
人工智能·gpt·chatgpt
workflower7 小时前
大型语言模型简史
人工智能·语言模型·自然语言处理·chatgpt·机器人·集成测试·ai编程
智算菩萨7 小时前
ChatGPT 5.4文献检索实战指南:从入门到精通的学术搜索方法论
论文阅读·人工智能·ai·chatgpt·全文检索
桃花猿9 小时前
大模型Token入门详解:概念、原理、换算与核心作用【AI基础】
人工智能·chatgpt
雨夜之寂19 小时前
能动手才推 · AI · 03/18
chatgpt