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

= = =

相关推荐
云卷云舒___________11 小时前
突发 | OpenAI 惊现 memory4-dream 与 gpt-rosalind!Gemini 3.8 路由至4? | 10月11日 AI日报
openai·codex·gemini·ai日报·antigravity·memory4dream·gptrosalind
OliverQiu15 小时前
开源一个 macOS 小工具:集中管理 ChatGPT 的网络启动配置
macos·chatgpt·swiftui·mac·proxy·codex·dmg
寒狼GPT16 小时前
Codex 5小时额度是固定重置还是滚动恢复?为什么每个人Reset时间不一样
chatgpt·程序员·ai编程
AI大模型-小华17 小时前
AI 编程进入深度开发阶段:什么时候普通方案不够,需要更高算力支持?
人工智能·chatgpt·ai编程·vs code·codex·codex cli
一缕82年的清风1 天前
单次输出100万Token!谷歌秘密王牌Gemini 4 Argon曝光:大模型终于能通宵写代码了?
gemini
Mr.朱鹏1 天前
科技周报(第2026-10-10期):GPT6与安全
科技·安全·chatgpt
云卷云舒___________1 天前
Gemini 4-Flash曝光?Argon现身Antigravity?Carbon新检查点?Ultra模式齐亮相? 谷歌憋大招!| 10月10日 AI日报
ai·谷歌·gemini·ai日报·aistudio·antigravity·gemini4
Frag0ut2 天前
Chrome数据备份指南:本地备份还原书签密码与扩展配置工具
chrome·google·谷歌浏览器·数据同步·备份工具·配置迁移·书签密码备份
GlobalAIagent2 天前
外贸站上线前的技术自查清单:漏一项询盘可能消失
google·typescript·ar·go语言·seo
知昂七昂2 天前
00-01:AOSP 源码仓库结构与 repo 工作流源码剖析(Android 16 / aosp-main)
android·google