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

= = =

相关推荐
bu_shuo2 小时前
AI生成的数学公式复制为LaTeX插件
ai·chatgpt·latex·gemini·千问·豆包·数学公式复制
智算菩萨3 小时前
GPT-5.4的“慢思考“艺术:详解推理时计算(Inference-Time Compute)如何重塑复杂任务解决能力
人工智能·gpt·ai·chatgpt
SEO_juper4 小时前
AI时代的SEO重构:从搜索排名到AI可见度的底层逻辑变革
人工智能·ai·chatgpt·重构·seo·数字营销·2026
放下华子我只抽RuiKe513 小时前
机器学习全景指南-直觉篇——基于距离的 K-近邻 (KNN) 算法
人工智能·gpt·算法·机器学习·语言模型·chatgpt·ai编程
python零基础入门小白19 小时前
多智能体强化学习:从基础到实战,掌握协作与竞争的艺术!
人工智能·学习·chatgpt·大模型·产品经理·ai大模型·大模型学习
wing9821 小时前
Vue3 接入 Google 登录:极简教程
前端·vue.js·google
袁袁袁袁满1 天前
我同时用了三个月ChatGPT/Claude/Gemini/Grok最真实的感受
chatgpt·claude·grok·gemini·gemini 3.1pro·gork4.2·claude4.6
LaughingZhu1 天前
Product Hunt 每日热榜 | 2026-03-13
数据库·人工智能·经验分享·神经网络·chatgpt
智算菩萨2 天前
GPT-5.4原生操控电脑揭秘:从Playwright脚本到屏幕截图识别,手把手搭建你的第一个自动化智能体
人工智能·gpt·ai·chatgpt·自动化
CocoaKier2 天前
苹果谷歌纷纷调低官方抽成,苹果谷歌全球抽成比例汇总
ios·google·apple