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

= = =

相关推荐
腾讯云云开发5 小时前
Gemini CLI接入CloudBase-AI-Toolkit(MCP)保姆级教程
ai编程·小程序·云开发·gemini
产业家2 天前
Sora 后思考:从 AI 工具到 AI 平台,产业 AGI 又近了一步
人工智能·chatgpt·agi
weixin_519535773 天前
从ChatGPT到新质生产力:一份数据驱动的AI研究方向指南
人工智能·深度学习·机器学习·ai·chatgpt·数据分析·aigc
我叫黑大帅3 天前
用户头像文件存储功能是如何实现的?
后端·google
尽兴-4 天前
【10 分钟!M4 Mac mini 离线部署「私有 ChatGPT」完整实录】
macos·ai·chatgpt·大模型·ollama·私有化
七牛云行业应用4 天前
100美元成本复现ChatGPT:nanochat全栈技术栈深度剖析
chatgpt·开源项目·nanochat·karpathy·lm训练
小虚竹and掘金4 天前
GPT-5-Codex 发布!claude编程王位即将不保?国内直接使用
chatgpt
007tg4 天前
OpenAI推出即时支付功能,ChatGPT将整合电商能力|技术解析与行业影响
chatgpt
马拉AI5 天前
Andrej Karpathy 发布新项目 nanochat:一个从零开始构建的极简全栈式 ChatGPT 克隆
chatgpt
神码小Z5 天前
特斯拉前AI总监开源的一款“小型本地版ChatGPT”,普通家用电脑就能运行!
人工智能·chatgpt