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

= = =

相关推荐
烁烁闪闪烁烁1 天前
【weelinking系列Claude教程】 04 - Claude Code 安装与配置
人工智能·chatgpt·ai编程·claude·cursor·claude code·opencode
冬奇Lab2 天前
一天一个开源项目(第22篇):nanochat - 百元级「最好的 ChatGPT」,Karpathy 的极简 LLM 训练套件
人工智能·gpt·chatgpt
namelessmyth2 天前
聚合AI大模型API平台-横向评测对比
人工智能·语言模型·chatgpt·ai编程
三寸3372 天前
ChatGPT Plus国内订阅三种方案深度对比:风险、成本分析
人工智能·ai·chatgpt
西凉的悲伤3 天前
Chrome浏览器原生Gemini AI 按钮功能开启指南
chrome·谷歌浏览器·gemini
赛博鲁迅3 天前
coze 工作流使用中转API 教程
gpt·大模型·ai编程·agi·gemini·coze
A洛3 天前
OpenAI Codex CLI 完整速查表:命令、配置、MCP 一网打尽
人工智能·chatgpt·codex·claude code
摘星编程4 天前
超越ChatGPT!一文读懂如何用LoRA高效微调打造专属行业大模型
chatgpt
电话交换机IPPBX-3CX4 天前
3CX 让 Gemini 读懂企业通话数据
数据库·gemini·ip pbx·电话交换机·3cx·企业电话系统
Tigerbot4 天前
2026年2月GEO优化服务商五家选型评测报告出炉!附GEO方法论深度解读!
人工智能·chatgpt