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

= = =

相关推荐
jerrywus16 小时前
你给 AI 装的那些 skill,可能有一半根本没生效,1个技巧专治「AI 技能包装着装着就成了一团麻」
chatgpt·agent·claude
m0_7345717617 小时前
深入理解人工智能 chatGPT 核心协调与调度层 (Core Orchestration Layer)
人工智能·chatgpt
架构指南17 小时前
macOS 实测:Codex 桌面版双开,官方账号与第三方 API 独立使用
chatgpt·ai编程
跨境生态圈1 天前
2026谷歌SEO快速排名深度解析:合规起量、避坑指南与实战落地策略
数据库·人工智能·爬虫·搜索引擎·chatgpt
诺伦1 天前
RiseClaw玄策:GEO优化工程实战,从零搭建生成式引擎优化体系
人工智能·chatgpt
Xu_youyaxianshen2 天前
【OpenAI 昨天正式更新了 ChatGPT Images 2.5。】
chatgpt·aigc
码农学院2 天前
外贸独立站GEO实战:用 Python 自动生成多语言 llms.txt 和 Schema 站点地图
人工智能·python·chatgpt·geo·geo优化·ai优化aio
空堂与归2 天前
ChatGPT的视觉模型:ChatGPT Images 2.5:快与准拆成两个模型
人工智能·gpt·ai·chatgpt
XLYcmy2 天前
ReasoningBank: Scaling Agent Self-Evolving with Reasoning Memory论文阅读
论文阅读·google·llm·agent·记忆·harness·自进化