首页 教程 分类 Skills下载 关于
ZH EN JA KO
基础配置

openclaw agent 单次调用命令教程

· 6 分钟

命令概述

openclaw agent 命令允许你从命令行直接向 AI 发送单次请求并获取响应,无需通过频道。它适合快速测试、脚本集成和自动化工作流。

基本用法

openclaw agent "你好,请介绍一下自己"

输出:

你好!我是 OpenClaw AI 助手,可以帮你回答问题、编写代码、
翻译文本等。有什么可以帮你的吗?

指定模型

# 使用配置中定义的模型别名
openclaw agent --model gpt-4o "解释量子计算的基本原理"

# 使用供应商和模型名
openclaw agent --provider openai --model gpt-4o-mini "写一个排序算法"

传入系统提示词

openclaw agent \
  --system "你是一个专业的Python程序员,只用Python回答问题" \
  "实现一个二叉树的中序遍历"

从标准输入读取

# 管道输入
echo "翻译成英文:今天天气很好" | openclaw agent

# 从文件读取
cat error.log | openclaw agent "分析这段日志中的错误原因"

# Here document
openclaw agent <<EOF
请帮我审查以下代码:
def add(a, b):
    return a - b
EOF

流式输出

# 启用流式输出(实时显示生成内容)
openclaw agent --stream "写一篇关于人工智能的短文"

输出格式

# 纯文本(默认)
openclaw agent "你好"

# JSON 格式
openclaw agent --format json "你好"

JSON 输出:

{
  "content": "你好!有什么可以帮你的吗?",
  "model": "gpt-4o-mini",
  "usage": {
    "promptTokens": 12,
    "completionTokens": 15,
    "totalTokens": 27
  },
  "latency": 850
}

调整模型参数

openclaw agent \
  --temperature 0.2 \
  --max-tokens 1000 \
  --top-p 0.9 \
  "给我5个项目名称建议"

使用工具

允许 AI 调用工具:

openclaw agent --tools web_search "今天北京的天气怎么样?"

openclaw agent --tools code_exec "计算 fibonacci(30) 的值"

# 多个工具
openclaw agent --tools web_search,code_exec "搜索Python最新版本并运行测试代码"

多轮对话

虽然 agent 主要用于单次调用,但也支持简单的多轮对话:

# 使用 session ID 维持上下文
openclaw agent --session my-test "我叫张三"
openclaw agent --session my-test "我叫什么名字?"
# 输出: 你叫张三。

脚本集成示例

Shell 脚本中使用

#!/bin/bash
# 自动生成 Git commit message
DIFF=$(git diff --cached)
MESSAGE=$(echo "$DIFF" | openclaw agent --model gpt-4o-mini \
  --system "根据 git diff 生成简洁的 commit message,只输出 message,不要其他内容" \
  --format text)

git commit -m "$MESSAGE"

批量处理

#!/bin/bash
# 批量翻译文件
for file in docs/*.md; do
  openclaw agent --model gpt-4o-mini \
    --system "将以下 Markdown 内容翻译成英文,保持格式" \
    < "$file" > "translated/$(basename $file)"
done

与 jq 配合

# 提取 JSON 中的特定字段
openclaw agent --format json "生成3个随机用户数据" | jq '.content'

退出码

  • 0:成功
  • 1:一般错误
  • 2:认证错误
  • 3:模型不可用
  • 4:速率限制
openclaw agent "测试" || echo "调用失败,退出码: $?"

超时设置

openclaw agent --timeout 30 "一个复杂的问题..."

调试模式

openclaw agent --debug "你好"

输出包含请求和响应的详细信息:

[DEBUG] Provider: openai
[DEBUG] Model: gpt-4o-mini
[DEBUG] Request tokens: 12
[DEBUG] Response time: 850ms
[DEBUG] Response tokens: 15

你好!有什么可以帮你的吗?

总结

openclaw agent 是 OpenClaw CLI 中最灵活的命令之一,将 AI 能力直接带入命令行。它让 AI 调用像其他 Unix 工具一样可以被管道、脚本和自动化流程组合使用。

OpenClaw 是开源免费的个人AI助手,支持 WhatsApp、Telegram、Discord 等多平台接入