李升伟 编译
(🎨 封面由 Gemini 中的 Imagen 3 生成!)
欢迎来到我的谷歌AI工具构建系列博客!本文将带您创建一个由Gemini驱动并托管在Cloud Run上的简易聊天应用。如果您正在探索大语言模型或希望将AI集成到网页应用中,那么您来对地方了。让我们开始学习吧!
👩🏫 我们要构建什么?
我们将开发一个基于网页的聊天界面,该界面连接Gemini API并返回对话式响应。应用将运行在Cloud Run上,并使用Cloud Build和Artifact Registry进行容器化部署。
完成本教程后,您将能够:
• 搭建与Gemini API交互的Python网页应用
• 使用Docker容器化应用
• 通过谷歌云工具将应用部署至Cloud Run
• 开始思考如何将大语言模型集成到自己的项目中
想象一下,这不是HAL(注:电影《2001太空漫游》中的人工智能),而是更聪明的智能助手。🤖💬 让我们开始吧!
📝 前置条件
开始前请确保您已具备:
• 谷歌云项目
• 安装并认证gcloud命令行工具
• 已安装Docker
• 项目中已启用Vertex AI API
💻 可选:使用Cloud Shell获得全配置环境
⚙️ 第一步:克隆聊天应用模板
首先获取预建的Python Flask应用:
git clone https://github.com/ChloeCodesThings/chat-app-demo
cd chat-app-demo
您将看到应用包含:
• app.py - Flask路由和Gemini API逻辑
• index.html - 基础聊天界面
• Dockerfile - 容器构建指南
🐳📁 第二步:使用Cloud Build构建Docker镜像
首先设置环境变量:
export PROJECT_ID=$(gcloud config get-value project)
export REGION=us-central1
export AR_REPO=chat-app-repo
export SERVICE_NAME=chat-gemini-app
创建Artifact Registry仓库:
gcloud artifacts repositories create
�
�
�
�
�
�
−
−
�
�
�
�
�
�
�
�
�
�
−
�
�
�
�
�
�
�
�
�
�
�
�
−
−
�
�
�
�
�
�
�
�
AR
R
EPO −−repository−format=docker −−location=REGION
然后构建并推送镜像:
gcloud builds submit --tag
�
�
�
�
�
�
−
�
�
�
�
�
�
.
�
�
�
.
�
�
�
/
REGION−docker.pkg.dev/PROJECT_ID/
�
�
�
�
�
�
/
AR
R
EPO/SERVICE_NAME
🚀 第三步:部署至Cloud Run
现在部署应用:
gcloud run deploy
�
�
�
�
�
�
�
�
�
�
�
−
−
�
�
�
�
�
SERVICE
N
AME −−image=REGION-docker.pkg.dev/
�
�
�
�
�
�
�
�
�
/
PROJECT
I
D/AR_REPO/
�
�
�
�
�
�
�
�
�
�
�
−
−
�
�
�
�
�
�
�
�
�
�
�
�
�
�
�
−
−
�
�
�
�
�
�
SERVICE
N
AME −−platform=managed −−region=REGION
–allow-unauthenticated
–set-env-vars=GCP_PROJECT=
�
�
�
�
�
�
�
�
�
,
�
�
�
�
�
�
�
�
�
PROJECT
I
D,GCP
R
EGION=REGION
您将获得类似 https://chat-gemini-app-xxxxxx.run.app 的URL,打开即可与Gemini对话!
🔎✨ 第四步:Gemini集成原理
让我们看看后端逻辑。在app.py中实现核心功能:
from vertexai.preview.language_models import ChatModel
def create_session():
chat_model = ChatModel.from_pretrained(“gemini-2.0-flash”)
chat = chat_model.start_chat()
return chat
def response(chat, message):
result = chat.send_message(message)
return result.text
当用户提交消息时,应用会:
创建新聊天会话
向Gemini模型发送消息
以JSON格式返回响应
🤸♀️ 立即体验!
尝试输入问题如:
“什么是Google Cloud Platform?”
…您将获得情境化的大语言模型生成响应。
🎯 下一步?
恭喜完成!🥳 这只是开始!后续我们将探讨:
• 增强聊天界面
• 保持会话持久化
• 使用系统提示塑造Gemini响应
• 通过Firebase认证或API网关保护端点
🎊 为自己点赞!
本文您学会了:
• 使用Gemini构建并部署Flask聊天应用
• 用Docker容器化并推送至Artifact Registry
• 以最小配置部署到Cloud Run
下次见! -Chloe
(翻译说明:保留技术术语原名;"HAL"添加注释说明;"SmarterChild"译为"更聪明的智能助手"保持语境;emoji表情符号全部保留;代码块和命令行保持原格式;中文标点符号规范使用)
原文链接:https://dev.to/chloecondon/using-the-gemini-api-on-cloud-run-to-build-a-chat-application-4673