11.3 LLM任务

llm-task 是一个可选的插件工具,用于运行纯JSON的LLM任务并返回结构化输出,可选地针对JSON Schema进行验证。

概述

llm-task工具允许你运行独立的LLM任务,这些任务不暴露任何工具给模型,专注于生成结构化的JSON输出。

主要特点

  • 纯JSON输出: 不使用任何工具的独立运行
  • Schema验证: 可选的JSON Schema验证
  • 结构化响应: 保证输出格式一致性
  • 插件工具: 作为可选插件提供

安装

# 安装llm-task插件
openclaw plugins install llm-task

基本用法

{
  "tool": "llm-task",
  "prompt": "生成一个包含姓名和年龄的人物信息",
  "schema": {
    "type": "object",
    "properties": {
      "name": { "type": "string" },
      "age": { "type": "number" }
    },
    "required": ["name", "age"]
  }
}

工具参数

  • prompt: 发送给LLM的提示
  • schema: 可选的JSON Schema用于验证输出
  • model: 可选的模型覆盖
  • temperature: 可选的温度参数
  • maxTokens: 可选的最大token数

Schema验证

使用JSON Schema确保输出格式:

{
  "tool": "llm-task",
  "prompt": "列出三种编程语言",
  "schema": {
    "type": "object",
    "properties": {
      "languages": {
        "type": "array",
        "items": { "type": "string" },
        "minItems": 3,
        "maxItems": 3
      }
    },
    "required": ["languages"]
  }
}

配置

{
  "plugins": {
    "llm-task": {
      "enabled": true,
      "defaultModel": "gpt-4",
      "defaultTemperature": 0.7,
      "maxRetries": 3
    }
  }
}

使用场景

  • 数据提取: 从文本中提取结构化数据
  • 内容生成: 生成符合特定格式的内容
  • 分类任务: 文本分类和标注
  • 格式转换: 将非结构化文本转换为结构化JSON
  • 批处理: 批量处理文本任务

高级示例

复杂Schema

{
  "tool": "llm-task",
  "prompt": "分析这篇文章的情感和主题",
  "schema": {
    "type": "object",
    "properties": {
      "sentiment": {
        "type": "string",
        "enum": ["positive", "negative", "neutral"]
      },
      "topics": {
        "type": "array",
        "items": { "type": "string" }
      },
      "confidence": {
        "type": "number",
        "minimum": 0,
        "maximum": 1
      }
    },
    "required": ["sentiment", "topics", "confidence"]
  }
}

嵌套对象

{
  "tool": "llm-task",
  "prompt": "生成一个用户资料",
  "schema": {
    "type": "object",
    "properties": {
      "user": {
        "type": "object",
        "properties": {
          "name": { "type": "string" },
          "email": { "type": "string", "format": "email" },
          "address": {
            "type": "object",
            "properties": {
              "city": { "type": "string" },
              "country": { "type": "string" }
            }
          }
        }
      }
    }
  }
}

错误处理

  • Schema验证失败: 如果输出不符合schema,工具会重试
  • 解析错误: 无效的JSON会触发重试
  • 超时: 超过maxRetries后返回错误

最佳实践

  • 使用清晰的提示描述期望的输出
  • 定义详细的JSON Schema以确保输出质量
  • 为复杂任务增加maxTokens
  • 使用适当的temperature控制创造性
  • 实施重试和错误处理逻辑
提示
llm-task非常适合需要可预测、结构化输出的场景。通过JSON Schema验证,可以确保输出始终符合期望格式。