精选副业
‹ 站长专栏
站长原创 · 全文公开

OpenClaw小龙虾运行、AI模型配置及聊天界面使用实操记录

这篇是我本人写的,所以全文放在这里,你不用领体验卡也能读完。文末有生财原帖链接,评论区的讨论在那边。

上一篇链接 https://articles.zsxq.com/id_gfrf35we94gw.html编译与运行代码写完了,... E:\Source\openclaw\openclaw-clone # 进入项目目录 pnpm install # 安装所有依赖预期输出:Packages: +954 Progress: resolved 954, reused 139, downloaded 814, added 954, done常见问题:如果下载很慢,尝试使用国内镜像:pnpm config set registry https://registry.npmmirror.com如果报 sharp 安装失败,运行:pnpm install --ignore-scripts && pnpm rebuild sharp2编译 TypeScriptpnpm build成功标志:没有错误输出生成了 dist/ 目录dist/index.js 文件存在如果报错:查看错误信息,通常是类型错误或导入路径错误检查 tsconfig.json 配置是否正确确保所有文件都已正确创建3配置环境变量# 复制环境变量模板 cp .env.example .env # Windows 用户使用: copy .env.example .env编辑 .env 文件,至少配置一个 AI 模型:# 推荐使用智谱清言(有免费额度) GLM_API_KEY=你的API密钥 GLM_MODEL=glm-4-flash4启动网关node openclaw.mjs gateway start成功启动输出:✓ Found GLM_API_KEY in environment Starting OpenClaw Gateway... ✓ GLM/智谱清言 AI Provider initialized (智谱AI) ✓ Gateway started successfully Gateway is running: WebSocket: ws://0.0.0.0:3100 HTTP API: http://0.0.0.0:3101 Press Ctrl+C to stop5验证运行状态打开浏览器访问以下地址:http://localhost:3101/API 文档首页http://localhost:3101/health健康检查http://localhost:3101/sta...)🎉 小龙虾已经跑起来了!访问 http://localhost:3101/chat 开始和小龙虾聊天吧!配置 AI 模型小龙虾支持多种 AI 模型,推荐使用中国的 AI 模型(注册简单、有免费额度)。1支持的 AI 模型模型 环境变量 价格 推荐智谱清言 GLM GLM_API_KEY 免费500万token/月 ⭐ 首推DeepSeek 深度求索 DEEPSEEK_API_KEY ¥1/百万token 最便宜通义千问 Qwen QWEN_API_KEY ¥2/百万token 阿里云Moonshot/Kimi MOONSHOT_API_KEY ¥12/百万token 长上下文Anthropic Claude ANTHROPIC_API_KEY $3/百万token 国际2获取智谱清言 API Key(推荐)步骤:访问 https://open.bigmodel.cn/点击右上角「登录」,使用手机号或微信注册登录后,点击右上角头像 → 「API密钥」或直接访问 https://open.bigmodel.cn/usercenter/apikeys点击「创建API密钥」,输入...)免费额度:glm-4-flash: 500万 tokens/月glm-4: 100万 tokens/月glm-4v: 50万 tokens/月3配置 .env 文件编辑项目根目录的 .env 文件:# ===== AI 模型配置(选择一个即可)=====# 方案1:智谱清言 GLM(推荐 - 有免费额度)GLM_API_KEY=你的API密钥粘贴在这里GLM_MODEL=glm-4-flash# 方案2:DeepSeek(最便宜)# DEEPSEEK_API_KEY=sk-your-key-here# DEEPSEEK_MODEL=deepseek-chat# 方案3:通义千问# QWEN_API_KEY=sk-your-key-here# QWEN_MODEL=qwen-turbo# 方案4:Moonshot/Kimi# MOONSHOT_API_KEY=sk-your-key-here# MOONSHOT_MODEL=moonshot-v1-8k注意:只需要配置一个 AI 模型即可配置后需要重新编译并重启网关系统会按优先级自动选择:GLM → DeepSeek → Qwen → Moonshot → Anthropic4重启验证# 1. 停止当前网关(Ctrl+C) # 2. 重新编译(因为修改了代码才需要) pnpm build # 3. 重新启动 node openclaw.mjs gateway start验证成功标志:✓ Found GLM_API_KEY in environment ✓ GLM/智谱清言 AI Provider initialized (智谱AI)🎉 AI 配置完成!现在小龙虾已经接入了智能大脑,可以进行智能对话了! 聊天界面小龙虾内置了一个漂亮的网页聊天界面,让你可以直接在浏览器中与它对话。1访问聊天界面确保网关已启动,然后访问:http://localhost:3101/chat2界面功能实时连接状态 - 显示 WebSocket 连接状态和运行时间消息输入框 - 输入消息按回车或点击发送按钮快捷按钮 - Ping、状态、帮助、打招呼、清空聊天消息气泡 - 区分用户消息和小龙虾回复深色主题 - 舒适的暗色界面3public/index.html 聊天页面代码如果聊天页面不存在,需要创建 public/index.html 文件📄 查看完整代码(较长,点击展开)<!DOCTYPE html><html lang="zh-CN"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>OpenClaw 小龙虾 - 聊天</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif; background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%); min-height: 100vh; color: #e8e8e8; display: flex; flex-direction: column; } header { background: rgba(0,0,0,0.3); padding: 15px 20px; display: flex; align-items: center; justify-content: center; gap: 15px; border-bottom: 1px solid rgba(255,255,255,0.1); } .logo { font-size: 2em; } h1 { font-size: 1.4em; color: #ff6b6b; } .status { font-size: 0.85em; color: #888; } .status.connected { color: #6bcb77; } .status::before { content: '● '; } #chat-container { flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 15px; } .message { max-width: 80%; padding: 12px 16px; border-radius: 15px; line-height: 1.5; word-wrap: break-word; } .message.user { background: linear-gradient(135deg, #667eea, #764ba2); align-self: flex-end; border-bottom-right-radius: 5px; } .message.bot { background: rgba(255,255,255,0.1); align-self: flex-start; border-bottom-left-radius: 5px; } .message .time { font-size: 0.75em; color: rgba(255,255,255,0.5); margin-top: 5px; text-align: right; } #input-area { background: rgba(0,0,0,0.3); padding: 15px 20px; border-top: 1px solid rgba(255,255,255,0.1); } #input-row { display: flex; gap: 10px; margin-bottom: 10px; } #message-input { flex: 1; padding: 12px 15px; background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.2); border-radius: 25px; color: #fff; font-size: 1em; outline: none; } #message-input:focus { border-color: #ff6b6b; } #send-btn { padding: 12px 25px; background: linear-gradient(135deg, #ff6b6b, #ff8e8e); border: none; border-radius: 25px; color: #fff; font-weight: bold; cursor: pointer; } #send-btn:hover { transform: scale(1.05); } .quick-btns { display: flex; gap: 8px; flex-wrap: wrap; } .quick-btn { padding: 6px 12px; background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.2); border-radius: 15px; color: #a8d8ea; font-size: 0.85em; cursor: pointer; } .quick-btn:hover { background: rgba(255,255,255,0.2); } </style></head><body> <header> <span class="logo">🦞</span> <div> <h1>OpenClaw 小龙虾</h1> <div id="status" class="status">连接中...</div> </div> </header> <div id="chat-container"></div> <div id="input-area"> <div id="input-row"> <input type="text" id="message-input" placeholder="输入消息..."> <button id="send-btn">发送</button> </div> <div class="quick-btns"> <button class="quick-btn" onclick="send('ping')">Ping</button> <button class="quick-btn" onclick="send('状态')">状态</button> <button class="quick-btn" onclick="send('帮助')">帮助</button> <button class="quick-btn" onclick="send('你好')">打招呼</button> <button class="quick-btn" onclick="clearChat()">清空聊天</button> </div> </div> <script> const chat = document.getElementById('chat-container'); const input = document.getElementById('message-input'); const status = document.getElementById('status'); let ws, startTime = Date.now(); function connect() { ws = new WebSocket('ws://localhost:3100'); ws.onopen = () => { status.textContent = '已连接'; status.className = 'status connected'; addMessage('bot', '🦞 你好!我是小龙虾,有什么可以帮你的?'); }; ws.onclose = () => { status.textContent = '已断开,重连中...'; status.className = 'status'; setTimeout(connect, 3000); }; ws.onmessage = (e) => { const msg = JSON.parse(e.data); if (msg.type === 'message' && msg.payload?.text) { addMessage('bot', msg.payload.text); } }; } function addMessage(type, text) { const div = document.createElement('div'); div.className = 'message ' + type; div.innerHTML = text.replace(/\\n/g, '<br>') + '<div class="time">' + new Date().toLocaleTimeString() + '</div>'; chat.appendChild(div); chat.scrollTop = chat.scrollHeight; } function send(text) { if (!text) text = input.value.trim(); if (!text || ws.readyState !== 1) return; addMessage('user', text); ws.send(JSON.stringify({ type: 'message', id: 'msg_' + Date.now(), payload: { text, channel: 'web', chatId: 'web-chat' } })); input.value = ''; } function clearChat() { chat.innerHTML = ''; } input.addEventListener('keypress', (e) => { if (e.key === 'Enter') send(); }); document.getElementById('send-btn').addEventListener('click', () => send()); connect(); </script></body></html>🎉 聊天界面完成!现在你可以通过浏览器和小龙虾愉快地聊天了!?常见问题排查遇到问题不要慌!这里列出了常见问题和解决方案。1pnpm install 失败症状:下载超时、网络错误、sharp 安装失败解决方案:# 1. 使用国内镜像 pnpm config set registry https://registry.npmmirror.com # 2. 清理缓存重试 pnpm store prune pnpm install # 3. 如果 sharp 失败 pnpm install --ignore-scripts pnpm rebuild sharp2pnpm build 编译错误症状:TypeScript 类型错误、找不到模块解决方案:检查错误信息中的文件名和行号确保所有 import 路径以 .js 结尾(ESM 要求)检查 tsconfig.json 是否正确运行 pnpm typecheck 单独检查类型3网关启动失败症状:端口被占用、模块找不到解决方案:# 检查端口是否被占用 netstat -ano | findstr :3100 netstat -ano | findstr :3101 # 使用其他端口启动 node openclaw.mjs gateway start --port 3200 --http-port 3201 # 确保已编译 pnpm build4AI 不回复 / 使用简单响应症状:小龙虾只会简单回复,不使用 AI 模型检查清单:确认 .env 文件中配置了 API Key确认 API Key 正确(没有多余空格)确认运行了 pnpm build 重新编译确认重启了网关查看启动日志是否显示 "✓ GLM/智谱清言 AI Provider initialized"5聊天页面无法连接症状:页面显示"连接中..."或"已断开"解决方案:确认网关正在运行确认 WebSocket 端口 3100 没有被防火墙阻止尝试用 ws://127.0.0.1:3100 代替 localhost打开浏览器控制台(F12)查看错误信息6API 返回错误常见 API 错误:401 UnauthorizedAPI Key 无效或过期403 Forbidden余额不足或权限不够429 Too Many Requests请求太频繁,稍后重试500 Internal Error服务端错误,稍后重试还有问题?查看项目 GitHub Issues 或加入社区讨论:https://github.com/openclaw/openclaw⚙运行机制详解(带工具调用)通过一个实际案例,详细了解小龙虾内部是如何工作的。这是一个带有工具调用能力的智能助手!0案例场景用户在浏览器打开聊天页面,输入:"今天天气怎么样?"小龙虾调用天气API,返回深圳市宝安区的实时天气。1完整流程图┌─────────────────────────────────────────────────────────────────┐│ 用户浏览器 (聊天页面) ││ [输入框] 今天天气怎么样? [发送] │└─────────────────────────────┬───────────────────────────────────┘ │ ① WebSocket 发送 ▼┌─────────────────────────────────────────────────────────────────┐│ Gateway WebSocket Server ││ ② handleChatMessage() 接收消息 ││ ③ detectIntent() 意图识别 → 检测到"天气"关键词 ││ ④ 调用 getWeather() 工具函数 │└─────────────────────────────┬───────────────────────────────────┘ │ ⑤ HTTP 请求 ▼┌─────────────────────────────────────────────────────────────────┐│ 和风天气 API (qweather.com) ││ GET /v7/weather/now?location=101280604 ││ 返回: { temp:"26", text:"多云", humidity:"75", windDir:"东南风" }│└─────────────────────────────┬───────────────────────────────────┘ │ ⑥ 返回天气数据 ▼┌─────────────────────────────────────────────────────────────────┐│ Gateway WebSocket Server ││ ⑦ 将天气数据注入 AI 上下文 ││ ⑧ 调用智谱清言 API,让 AI 组织自然语言回复 │└─────────────────────────────┬───────────────────────────────────┘ │ ⑨ AI 生成回复 ▼┌─────────────────────────────────────────────────────────────────┐│ 智谱清言 AI 服务器 ││ 收到上下文: 用户问天气 + 实时天气数据 ││ 生成: "🌤️ 深圳宝安区现在26°C,多云,适合外出哦!" │└─────────────────────────────┬───────────────────────────────────┘ │ ⑩ WebSocket 推送 ▼┌─────────────────────────────────────────────────────────────────┐│ 用户浏览器 ││ [小龙虾] 🌤️ 深圳宝安区现在的天气: ││ • 天气:多云 ││ • 温度:26°C(体感 28°C) ││ • 湿度:75% ││ • 风况:东南风 3级 ││ 今天比较舒适,适合外出哦! │└─────────────────────────────────────────────────────────────────┘2核心步骤解析步骤说明代码位置① 发送用户点击发送,WebSocket 将消息传到服务器public/index.html② 接收服务器解析 JSON,提取消息内容ws-server.ts③ 意图识别检测关键词"天气",决定调用天气工具detectIntent()④ 工具调用调用 getWeather() 获取实时天气tools/weather.ts⑤⑥ API请求和风天气API,获取深圳宝安区天气qweather.com⑦⑧ AI将天气数据+用户问题发给AI,生成自然回复callGLM()⑨⑩ 返回AI 回复通过 WebSocket 推送给用户sendMessage()意图识别代码根据关键词判断用户意图,决定是否调用工具📄 查看代码// 工具定义const TOOLS = [ { name: 'weather', description: '查询中国城市实时天气', keywords: ['天气', '气温', '温度', '下雨', '晴天', '多云'], handler: async () => await getWeather('深圳宝安') }, { name: 'time', description: '查询当前时间', keywords: ['时间', '几点', '日期', '今天'], handler: async () => new Date().toLocaleString('zh-CN') }];// 意图识别function detectIntent(text: string): Tool | null { for (const tool of TOOLS) { for (const keyword of tool.keywords) { if (text.includes(keyword)) { return tool; // 匹配到工具 } } } return null; // 不需要工具,直接让 AI 回答}4天气工具代码调用和风天气API获取实时天气数据📄 查看代码// 城市代码映射const CITY_CODES = { '深圳宝安': '101280604', '深圳': '101280601', '广州': '101280101', '北京': '101010100', '上海': '101020100',};// 默认城市const DEFAULT_CITY = '深圳宝安';// 获取实时天气async function getWeather(cityName?: string) { const apiKey = process.env.QWEATHER_API_KEY; const city = cityName || DEFAULT_CITY; const code = CITY_CODES[city] || '101280604'; const url = `https://devapi.qweather.com/v7/weather/now?location=${cod... const response = await fetch(url); const data = await response.json(); return { city: '深圳市', district: '宝安区', temp: data.now.temp, // 温度 text: data.now.text, // 天气状况 humidity: data.now.humidity, // 湿度 windDir: data.now.windDir, // 风向 windScale: data.now.windScale // 风力 };}5有工具 vs 无工具 对比场景无工具调用有工具调用问"天气""抱歉,我无法获取实时天气...""🌤️ 深圳宝安区26°C,多云..."问"几点了""请查看您的设备时间""现在是 10:30:46"数据来源AI训练数据(可能过时)实时API调用用户体验❌ 不实用✅ 真正的助手6工具系统架构┌─────────────────────────────────────────────────────────────┐│ 小龙虾工具系统 ││ ││ 用户消息 ──► 意图识别 ──► 工具调度 ──► AI润色 ──► 回复 ││ │ ││ ▼ ││ ┌─────────────────────────────────────────────────────┐ ││ │ 工具注册中心 │ ││ │ │ ││ │ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ │ ││ │ │ 天气 │ │ 时间 │ │ 新闻 │ │ 翻译 │ │ ││ │ │weather │ │ time │ │ news │ │translate│ │ ││ │ └───┬────┘ └───┬────┘ └───┬────┘ └───┬────┘ │ ││ │ │ │ │ │ │ ││ │ ▼ ▼ ▼ ▼ │ ││ │ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ │ ││ │ │和风天气│ │系统时间│ │ 新闻 │ │ 翻译 │ │ ││ │ │ API │ │ │ │ API │ │ API │ │ ││ │ └────────┘ └────────┘ └────────┘ └────────┘ │ ││ └─────────────────────────────────────────────────────┘ ││ ││ 特点: 按需调用 | 可扩展 | 结果注入AI | AI润色输出 │└─────────────────────────────────────────────────────────────┘7环境变量配置 (.env)# ===== AI 模型配置 =====GLM_API_KEY=your-glm-api-keyGLM_MODEL=glm-4-flash# ===== 天气服务配置 =====# 和风天气(免费版)- https://dev.qweather.com/QWEATHER_API_KEY=your-qweather-a... 默认城市(用户未指定时使用)DEFAULT_CITY=深圳宝安DEFAULT_CITY_CODE=101280604# ===== 网关配置 =====GATEWAY_WS_PORT=3100GATEWAY_HTTP_PORT=3101🎉 理解了运行机制!现在你知道小龙虾是如何工作的了:意图识别 → 工具调用 → AI润色 → 返回用户这就是一个真正实用的AI助手的工作方式!

社群里还有 966 篇别人的实操复盘

体验卡免费,不花一分钱3 天看遍社群近 180 天全部内容正式加入 72 小时内无理由退款
生财有术体验卡
领取体验卡的二维码

长按保存这张二维码,打开微信扫一扫,从相册选这张图即可添加;电脑上直接用微信扫码。

我写的这些免费读。体验卡免费领,3 天内可以查阅社群近 180 天的全部内容。
站长专栏的其他文章
书情
从0到1搭建OpenClaw项目:完整教程及项目配置文件详解
2026-02-26 · 约 13862 字
读全文
书情
期待生财马拉松的举办
2026-02-24 · 约 843 字
读全文
书情
Claude Code命令完整教程:小白必会TOP 10命令及日常使用技巧
2026-02-14 · 约 9528 字
读全文