跳转到内容

cap_llm_inspect — 图像分析

源码:cap_llm_inspect.c · 头文件:cap_llm_inspect.h

cap_llm_inspect与 LLM 产生交互的代表实现。它展示了一种特殊模式:一个 Capability 在被 LLM 调用执行时,会反过来再次发起 LLM 推理(嵌套 LLM 调用),用于分析本地图像文件。

这种模式适用于需要 LLM 能力作为子任务的场景,例如:

  • 图像理解(本模块)
  • 文本摘要
  • 代码解释

cap_llm_inspect 注册了单个 Callable inspect_image

工具 IDinspect_image
描述Analyze a local image from an absolute path.
Confirm the path first, then provide a prompt describing what to inspect.
输入{ "path": "<绝对路径>", "prompt": "<分析提示>" }
输出LLM 对图像的文本描述

典型调用场景:

Diagram

cap_llm_inspect 的实现极为简洁(约 110 行),核心逻辑:

static const char *CAP_LLM_INSPECT_SYSTEM_PROMPT =
    "You analyze local image files for the ESP-Claw. "
    "Describe visible content plainly and briefly. "
    "If the image is unclear, say what is uncertain instead of guessing.";

static esp_err_t cap_llm_inspect_execute(const char *input_json,
                                          const claw_cap_call_context_t *ctx,
                                          char *output, size_t output_size)
{
    // 1. 解析 path 和 prompt
    claw_media_asset_t asset = {
        .kind = CLAW_MEDIA_ASSET_KIND_LOCAL_PATH,
        .path = path_json->valuestring,
    };

    // 2. 构造多模态请求(独立 system prompt + 用户 prompt + 图像)
    claw_llm_media_request_t request = {
        .system_prompt = CAP_LLM_INSPECT_SYSTEM_PROMPT,
        .user_prompt   = prompt_json->valuestring,
        .media         = &asset,
        .media_count   = 1,
    };

    // 3. 嵌套调用 LLM,结果写入 output
    char *analysis = NULL;
    err = claw_core_llm_infer_media(&request, &analysis, &error_message);
    snprintf(output, output_size, "%s", analysis);
    free(analysis);
}

claw_core_llm_infer_media 是一次独立的 LLM 调用,与正在处理用户请求的 Agent 对话完全隔离:

  • 使用专属的 system_prompt(专注于图像描述,不携带对话历史)
  • 不消耗当前 session 的 token 配额
  • 不触发 cap_skill 的工具可见性管理
  • 支持图像作为输入(依赖底层 LLM 提供者的多模态能力)
if (err != ESP_OK) {
    snprintf(output, output_size,
             "Error: image analysis failed (%s)%s%s",
             esp_err_to_name(err),
             error_message ? ": " : "",
             error_message ? error_message : "");
    free(error_message);
    return err;
}

若底层 LLM 不支持多模态,或图像路径不存在,错误信息直接写入 output 返回给调用方(LLM 或自动化规则)。

cap_llm_inspect 展示了几个重要设计选择:

  1. 独立 system prompt:图像分析不应受对话历史干扰,使用固定的专用提示词保证输出一致性

  2. 路径确认原则:描述中明确要求 “Confirm the path first”——LLM 在调用前应先通过 cap_fileslist_dir 确认文件存在,避免因路径错误浪费 LLM 调用

  3. 无状态cap_llm_inspect 不持有任何状态,每次调用都是独立的推理任务

  4. 关注点分离:图像下载由 cap_im_tg 负责,路径管理由 cap_files 负责,分析逻辑集中在 cap_llm_inspect

基于同样的模式,可以实现:

  • inspect_audio:分析音频文件(需 LLM 支持音频输入)
  • summarize_document:对文本文件进行摘要(调用文本推理接口)
  • classify_image:使用专用 system prompt 对图像分类