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

= = =

相关推荐
冲上云霄的Jayden11 小时前
Spring Ai WebClient、RestClient设置代理
spring·webclient·代理·restclient·gemini·region·springai
追风哥哥12 小时前
transformer 注意力机制解析
人工智能·深度学习·神经网络·机器学习·语言模型·chatgpt·transformer
张驰咨询公司17 小时前
AI替代MBB?实测DeepSeek、Kimi、ChatGPT做六西格玛分析的准确度对比
人工智能·chatgpt·六西格玛·六西格玛绿带培训·六西格玛培训公司·精益六西格玛培训
weixin_4166600717 小时前
解决方案:DeepSeek/ChatGPT生成的内容,如何无损转为Word文档?
chatgpt·word·论文·数学公式·deepseek
Agent产品评测局18 小时前
企业采购自动化落地,供应商全生命周期管控实现方案:智能体驱动下的全链路提效与合规治理
运维·人工智能·ai·chatgpt·自动化
yingxiao88821 小时前
ChatGPT广告六周内年化收入破1亿美元;《Kingshot》用户支出破10亿美元
人工智能·chatgpt·字节跳动·游戏资讯·行业资讯·以闪亮之名
Agent产品评测局2 天前
物流供应链自动化解决方案选型,全链路提效指南:从硬件集成到AI Agent的演进路径
运维·人工智能·ai·chatgpt·自动化
智算菩萨2 天前
GPT-5.4 进阶思考模式全面解析:从推理等级到实战提示词,代码、论文、数据处理一站通
人工智能·gpt·深度学习·机器学习·语言模型·自然语言处理·chatgpt
芯智工坊2 天前
每周一个开源项目 #4:ChatGPT-Next-Web 增强版
前端·chatgpt·开源
chehaoman2 天前
2026年ChatGPT技术拆解:架构、训练与国内镜像使用方案
chatgpt