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

= = =

相关推荐
Maynor9962 小时前
Claude vs ChatGPT vs Gemini: 기능 비교, 사용 경험, 적합 인군
人工智能·chatgpt
win4r12 小时前
🚀Claude Code被封号?用谷歌Antigravity+Claude Opus 4.5轻松替代!实测项目重构+全栈开发效果惊艳!Opus 4.5 才王道
claude·gemini·vibecoding
AI大模型学徒13 小时前
大模型应用开发(十六)_知识库2
chatgpt·大模型·知识库·deepseek
kkk_皮蛋19 小时前
“红色警报“后的反击:OpenAI 发布 GPT-5.2,AI 霸主之争白热化
人工智能·gpt·chatgpt
视觉&物联智能1 天前
【杂谈】-RL即服务:解锁新一轮自主浪潮
人工智能·ai·chatgpt·aigc·强化学习·agi·deepseek
智算菩萨1 天前
从对话演示到智能工作平台:ChatGPT的三年演进史(2022-2025)
人工智能·chatgpt
致Great1 天前
Ollama 进阶指南
人工智能·gpt·chatgpt·agent·智能体
致Great2 天前
Nano Banana提示语精选
人工智能·gpt·chatgpt·开源·agent
AI大模型学徒2 天前
大模型应用开发(十五)_知识库1
人工智能·chatgpt·大模型·llm·知识库·deepseek
你那是什么调调2 天前
大语言模型如何“思考”与“创作”:以生成一篇杭州游记为例
人工智能·语言模型·chatgpt