通过http的方式调用OpenClaw
通过http的方式调用OpenClaw
架构回顾
text
┌─────────────────────────────────────────────────────────────────────┐
│ 完整数据流 │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ B电脑 A电脑 │
│ ┌──────────────────┐ ┌──────────────────────┐ │
│ │ D:\test.xlsx │ │ OpenClaw │ │
│ │ (原始数据) │ │ (已配置提示词+工具) │ │
│ └────────┬─────────┘ └──────────┬───────────┘ │
│ │ │ │
│ │ │ 1. 用户说 │
│ │ │ "分析数据test.xlsx"│
│ │ ▼ │
│ ┌──────────────────┐ ┌──────────────────────┐ │
│ │ B电脑数据API │◄───────────────────│ OpenClaw调用 │ │
│ │ /api/reliability/│ 2. 请求分析 │ (使用md中配置的方法) │ │
│ │ data/preprocess │ 文件名参数 │ │ │
│ └────────┬─────────┘ └──────────┬───────────┘ │
│ │ │ │
│ │ 3. 返回JSON分析结果 │ │
│ └──────────────────────────────────────────►│ │
│ │ │
│ │ 4. AI解读JSON │
│ │ 生成最终报告 │
│ │ │
│ │ 5. 自动写入 │
│ │ workspace入库 │
└─────────────────────────────────────────────────────────────────────┘
核心思路:B电脑直接调用OpenClaw的API,发送和WebUI一模一样的指令("分析数据test.xlsx"),OpenClaw会自动:
- 理解指令
- 调用B电脑的 /api/reliability/data/preprocess?filename=test.xlsx
- 获取JSON数据
- 按照你已配置的md提示词生成分析报告
- 自动将结果写入workspace(入库)
完整解决方案
📁 A电脑:确认配置(一次性)
确保OpenClaw的Gateway已启动并监听局域网:
bash
在A电脑上执行
openclaw gateway start --bind 0.0.0.0 --port 18789
💻 B电脑:调用脚本
创建 C:\openclaw_client\call_analyzer.ps1(PowerShell脚本):
powershell
OpenClaw 分析调用脚本 - B电脑
模拟WebUI行为,发送"分析数据test.xlsx"指令
param(
[Parameter(Mandatory=$true)]
[string]$FileName, *#* *例如: test.xlsx*
[string]$OpenClawHost = "http://192.168.8.100:18789",
[string]$ApiToken = "admin123",
[switch]$SaveResult *#* *是否保存结果到本地文件*
)
*# 构建指令(和WebUI中说的一模一样)*
instruction = "分析数据FileName"
Write-Host "=" * 60 -ForegroundColor Cyan
Write-Host "OpenClaw 数据分析调用" -ForegroundColor Cyan
Write-Host "=" * 60 -ForegroundColor Cyan
Write-Host "指令: $instruction" -ForegroundColor Yellow
Write-Host "目标: $OpenClawHost" -ForegroundColor Gray
*# 构建请求体(不传文件,因为OpenClaw会自己调用B电脑的API)*
$body = @{
model = "openclaw/default"
input = @(
@{
type = "message"
role = "user"
content = $instruction
}
)
stream = $false
*#* *使用文件名作为session_id的一部分,便于后续追问*
user = "b_computer_([System.IO.Path]::GetFileNameWithoutExtension(FileName))"
} | ConvertTo-Json -Depth 10
$startTime = Get-Date
try {
Write-Host "`n****⏳ 正在调用OpenClaw..." -ForegroundColor Gray
response = Invoke-RestMethod -Uri "OpenClawHost/v1/responses" `
-Method Post `
-Headers @{
"Authorization" = "Bearer $ApiToken"
"Content-Type" = "application/json"
} `
-Body $body `
-ErrorAction Stop
elapsed = (Get-Date) - startTime
**Write-Host "**✅ 分析完成!耗时 ([math]::Round(elapsed.TotalSeconds, 1)) 秒" -ForegroundColor Green
**Write-Host "**📁 结果已自动存入A电脑workspace" -ForegroundColor Green
*#* *提取并显示结果*
resultText = response.output[0].content[0].text
Write-Host "`n" + "=" * 60 -ForegroundColor Cyan
**Write-Host "**📊 分析结果" -ForegroundColor Cyan
Write-Host "=" * 60 -ForegroundColor Cyan
Write-Host $resultText
*#* *可选:保存到本地文件*
if ($SaveResult) {
outputFile = "env:USERPROFILE\Desktop\analysis_([System.IO.Path]::GetFileNameWithoutExtension(FileName))_$(Get-Date -Format 'yyyyMMdd_HHmmss').md"
resultText | Out-File -FilePath outputFile -Encoding utf8
Write-Host "`n****💾 结果已同时保存到: $outputFile" -ForegroundColor Gray
}
*#* *返回session信息供后续使用*
return @{
Success = $true
SessionId = $response.user
Result = $resultText
ElapsedSeconds = $elapsed.TotalSeconds
}
}
catch {
**Write-Host "**❌ 调用失败: $_" -ForegroundColor Red
*#* *尝试读取错误详情*
if ($_.Exception.Response) {
reader = New-Object System.IO.StreamReader(_.Exception.Response.GetResponseStream())
errorBody = reader.ReadToEnd()
Write-Host "错误详情: $errorBody" -ForegroundColor Red
}
return @{
Success = $false
Error = $_.Exception.Message
}
}
🐍 Python版本(如果你更熟悉Python)
python
*#!/usr/bin/env python3*
"""
OpenClaw 分析调用脚本 - B电脑
发送"分析数据test.xlsx"指令,让OpenClaw自动调用B电脑API
"""
import requests
import json
import sys
import time
from datetime import datetime
*# ========== 配置 ==========*
OPENCLAW_HOST = "http://192.168.8.100:18789"
API_TOKEN = "admin123"
*# ==========================*
def analyze_file(file_name: str, save_result: bool = False) -> dict:
"""通过OpenClaw分析Excel文件"""
*#* *构建和WebUI一模一样的指令*
instruction = f"分析数据{file_name}"
print("=" * 60)
print("OpenClaw 数据分析调用")
print("=" * 60)
print(f"指令: {instruction}")
print(f"目标: {OPENCLAW_HOST}")
*#* *构建请求*
payload = {
"model": "openclaw/default",
"input": [
{
"type": "message",
"role": "user",
"content": instruction
}
],
"stream": False,
*#* *使用文件名作为session_id*
"user": f"b_computer_{file_name.replace('.xlsx', '').replace('.xls', '')}"
}
headers = {
"Authorization": f"Bearer {API_TOKEN}",
"Content-Type": "application/json"
}
start_time = time.time()
try:
print("\n****⏳ 正在调用OpenClaw...")
response = requests.post(
f"{OPENCLAW_HOST}/v1/responses",
headers=headers,
json=payload,
timeout=120
)
elapsed = time.time() - start_time
if response.status_code == 200:
result = response.json()
*#* *提取结果文本*
result_text = None
for item in result.get("output", []):
if item.get("type") == "message":
for part in item.get("content", []):
if part.get("type") == "output_text":
result_text = part.get("text")
break
print(f"\n****✅ 分析完成!耗时 {elapsed:.1f} 秒")
**print("**📁 结果已自动存入A电脑workspace")
print("\n" + "=" * 60)
**print("**📊 分析结果")
print("=" * 60)
print(result_text)
*#* *可选:保存到本地*
if save_result:
output_file = f"C:/Users/{os.getlogin()}/Desktop/analysis_{file_name.replace('.xlsx', '')}{datetime.now().strftime('%Y%m%d%H%M%S')}.md"
with open(output_file, 'w', encoding='utf-8') as f:
f.write(result_text)
print(f"\n****💾 结果已同时保存到: {output_file}")
return {
"success": True,
"result": result_text,
"elapsed": elapsed
}
else:
error_msg = f"API错误: {response.status_code} - {response.text[:200]}"
print(f"\n****❌ {error_msg}")
return {"success": False, "error": error_msg}
except Exception as e:
print(f"\n****❌ 调用失败: {e}")
return {"success": False, "error": str(e)}
if name == "main":
if len(sys.argv) < 2:
print("用法: python call_analyzer.py <文件名>")
print("示例: python call_analyzer.py test.xlsx")
sys.exit(1)
file_name = sys.argv[1]
save_flag = "--save" in sys.argv
analyze_file(file_name, save_flag)
📝 使用示例
方式1:单个文件分析
powershell
*# PowerShell*
.\call_analyzer.ps1 -FileName "test.xlsx"
*# 保存结果到本地*
.\call_analyzer.ps1 -FileName "test.xlsx" -SaveResult
bash
*# Python*
python call_analyzer.py test.xlsx
python call_analyzer.py test.xlsx --save
方式2:批量分析多个文件
创建 batch_analyze.ps1:
powershell
*** 批量分析多个Excel文件 ***
$files = @(
"test.xlsx",
"sales_report.xlsx",
"quality_data.xlsx"
)
foreach (file in files) {
Write-Host "`n" + ("-" * 50) -ForegroundColor Gray
.\call_analyzer.ps1 -FileName $file
Start-Sleep -Seconds 2 *#* *避免请求过快*
}
方式3:定时自动分析
powershell
*# 使用Windows计划任务,每天早上8点分析*
*# 创建计划任务脚本 auto_analyze.ps1*
$today = Get-Date -Format "yyyyMMdd"
file = "D:\daily_data\today.xlsx"
if (Test-Path $file) {
.\call_analyzer.ps1 -FileName $file -SaveResult
} else {
Write-Host "文件不存在: $file"
}
🔍 验证结果已入库
分析完成后,可以在A电脑查看入库结果:
bash
*# 在A电脑上执行*
*# 查看当天的会话记录*
cat ~/.openclaw/workspace/memory/$(date +%Y-%m-%d).md
*# 查看长期记忆中的关键信息*
cat ~/.openclaw/workspace/MEMORY.md
*# 搜索特定内容*
grep -r "test.xlsx" ~/.openclaw/workspace/
📊 完整数据流总结
| 步骤 | 执行者 | 动作 | 结果 |
|---|---|---|---|
| 1 | B电脑脚本 | 发送 分析数据test.xlsx 到OpenClaw API | HTTP请求 |
| 2 | OpenClaw (A电脑) | 理解指令,按md配置调用B电脑API | GET /api/reliability/data/preprocess?filename=test.xlsx |
| 3 | B电脑API | 解析Excel,返回JSON数据 | 结构化数据 |
| 4 | OpenClaw | AI解读JSON,按提示词生成报告 | Markdown报告 |
| 5 | OpenClaw | 自动写入workspace | ~/.openclaw/workspace/memory/YYYY-MM-DD.md |
| 6 | B电脑脚本 | 接收并显示结果 | 终端输出 |
✅ 关键优势
- 完全复用WebUI配置:脚本发送的指令和WebUI完全一样,OpenClaw会使用你已有的md提示词和工具配置
- 无需修改A电脑:不需要额外配置,直接用现有的OpenClaw服务
- 自动入库:OpenClaw原生就会把所有对话写入workspace,无需额外代码
- 支持追问:使用相同的session_id可以继续对话
- 简单易用:一行命令就能得到分析结果
现在你只需要运行 .\call_analyzer.ps1 -FileName "test.xlsx",就能得到和WebUI完全一样的分析结果,并且结果会自动入库到A电脑的workspace!