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

= = =

相关推荐
孤狼GPT12 小时前
ChatGPT、Codex与Pro:AI开发为什么正在从“模型选择”转向“工作流设计”?
chatgpt·ai编程·codex·chatgpt pro·工作流设计
马丁路的King1 天前
Apple 设计被蒸馏成可落地 Skill
chatgpt
孤狼GPT1 天前
ChatGPT、Codex与Pro:AI开发正在从“单工具竞争”走向“系统协同”
chatgpt·ai编程·codex·chatgpt pro·系统协同
funkygroove1 天前
ChatGPT Business 包含 Pro 吗?两者区别一次说清
人工智能·chatgpt
神奇霸王龙1 天前
Gemini CLI 中转站配置使用教程
人工智能·ai·ai作画·aigc·ai编程·gemini·goolge
AI大模型-小华1 天前
Codex 长任务频繁中断怎么办?从上下文管理到 ChatGPT Pro 选择
chatgpt·ai编程·软件开发·codex·代码重构·开发效率·chatgpt pro
Summer-Bright1 天前
深度 | HBM4 标准急转弯:JEDEC 为什么在关键时刻「松绑」?
人工智能·语言模型·chatgpt·芯片·hbm
AI导出鸭1 天前
如何让deepseek生成word文档 ?「AI 导出鸭」苹果版:从API流式解析到Pages级渲染,硬核攻克公式裂变与表格回流的终极方案。
人工智能·chatgpt·word·cocoa·ai导出鸭
孤狼GPT1 天前
ChatGPT、Codex与Pro:AI写代码越快,为什么需求工程反而越重要?
chatgpt·ai编程·codex·chatgpt pro·需求工程
AI大模型-小华1 天前
Codex 为什么越用越慢?大型项目中的上下文管理与方案选择
人工智能·chatgpt·软件开发·codex·开发效率·chatgpt plus·chatgpt pro