# How the Agent Reach `format` Command Cleans and Formats Xiaohongshu API Output

> Learn how the Agent Reach format command cleans Xiaohongshu API output, reducing payload size up to 90% and creating a deterministic schema for LLMs.

- Repository: [Pnant/Agent-Reach](https://github.com/Panniantong/Agent-Reach)
- Tags: how-to-guide
- Published: 2026-08-05

---

**The Agent Reach `format` command for Xiaohongshu uses the `format_xhs_result` function in [`agent_reach/channels/xiaohongshu.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/xiaohongshu.py) to strip raw XHS API responses down to essential fields, reducing payload size by up to 90% while ensuring a deterministic schema for downstream LLM consumption.**

The Agent Reach CLI provides a dedicated formatting pipeline for Xiaohongshu (XiaoHongShu / XHS / 小红书) API data. According to the Panniantong/Agent-Reach source code, this system handles the platform's inconsistent response structures through a three-layer cleaning process: list/dispatch logic, note-level extraction, and comment-level simplification.

## The `format_xhs_result` Entry Point

The primary interface for formatting Xiaohongshu API output is the `format_xhs_result` function, defined at [lines 51-71](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/xiaohongshu.py#L51-L71) of [`agent_reach/channels/xiaohongshu.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/xiaohongshu.py).

This function receives raw JSON data and branches based on input type:

- **List input** — Each element is passed to `_clean_note()`, returning a list of cleaned notes
- **Dict input** — Detects common wrapper keys (`items`, `data → items`, `data → notes`) and processes the wrapped list, or treats the dict as a single note if no wrapper is found
- **Other types** — Returned unchanged (strings, `None`, etc.)

```python
def format_xhs_result(data):
    """Clean XHS API response, keeping only useful fields."""
    # ──► Handles lists (search results) or single objects

```

## Note-Level Transformation with `_clean_note`

The `_clean_note` function, located at [lines 73-141](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/xiaohongshu.py#L73-L141), performs the core field extraction and normalization.

### Field Extraction Strategy

| Step | Action | Purpose |
|------|--------|---------|
| **Normalize nesting** | `inner = note.get("note_card") or note.get("note") or note` | Handles variable wrapper keys (`note_card`, `note`) |
| **Basic metadata** | Copies `id`, `note_id`, `xsec_token`, `title`, `desc`, `type`, `time` | Minimal identifiers for lookups |
| **Content fallback** | Adds `content` if `desc` is missing | Guarantees textual body presence |
| **Author extraction** | Pulls `nickname`, `user_id`, `nick_name` from `user`/`author` object | Strips full profile noise |
| **Engagement metrics** | Collects `liked_count`, `collected_count`, `comment_count`, `share_count` from `interact_info` or top level | Provides popularity signals |
| **Images** | Extracts `url`, `url_default`, `original` URLs only | Removes image metadata bloat |
| **Tags** | Normalizes tag objects to plain strings | Simplifies downstream processing |
| **Comments** | Processes each through `_clean_comment` | Lightweight comment snapshots |

### Comment Cleaning via `_clean_comment`

Comments are simplified at [lines 44-57](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/xiaohongshu.py#L44-L57) to retain only:

- `content`
- Author `nickname`
- `like_count`
- `sub_comment_count`

```python
def _clean_comment(comment):
    """Extract useful fields from a comment."""

```

## Practical Example: Raw to Clean Transformation

```python
>>> from agent_reach.channels.xiaohongshu import format_xhs_result
>>> raw = {
...     "data": {
...         "items": [
...             {
...                 "note_id": "12345",
...                 "title": "My first XHS note",
...                 "desc": "Short description",
...                 "user": {"nickname": "alice", "user_id": "u01"},
...                 "interact_info": {"liked_count": 42},
...                 "image_list": [{"url": "https://example.com/img1.jpg"}],
...                 "tag_list": [{"name": "travel"}],
...             }
...         ]
...     }
... }
>>> clean = format_xhs_result(raw)
>>> clean
[{
    'note_id': '12345',
    'title': 'My first XHS note',
    'desc': 'Short description',
    'user': {'nickname': 'alice', 'user_id': 'u01'},
    'liked_count': 42,
    'images': ['https://example.com/img1.jpg'],
    'tags': ['travel']
}]

```

## Performance and Design Characteristics

The **Xiaohongshu format command** achieves three critical objectives:

- **Token efficiency** — Up to 90% payload reduction by discarding nested structures, unused keys, and binary blobs (per issue #134 referenced in source docstrings)
- **Schema determinism** — Downstream agents receive predictable field shapes regardless of which XHS endpoint emitted the data
- **Operational safety** — Pure JSON transformation with no network I/O; operates only on data already retrieved by the channel's `read` method

## Related Source Files

| File | Role |
|------|------|
| [`agent_reach/channels/xiaohongshu.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/xiaohongshu.py) | Core implementation: `format_xhs_result`, `_clean_note`, `_clean_comment` |
| [`tests/test_xhs_format.py`](https://github.com/Panniantong/Agent-Reach/blob/main/tests/test_xhs_format.py) | Unit tests for cleaning logic and edge case handling |
| [`agent_reach/utils/text.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/utils/text.py) | Generic text-processing utilities (used indirectly) |

## Summary

- The `format` command for Xiaohongshu is implemented in [`agent_reach/channels/xiaohongshu.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/xiaohongshu.py) via the `format_xhs_result` function
- **`_clean_note`** normalizes variable XHS response structures and extracts only essential note fields
- **`_clean_comment`** provides lightweight comment snapshots with content, author, and interaction counts
- The pipeline handles both list and dict inputs, detects common wrapper keys, and produces flat, deterministic output
- Zero network dependencies make the formatting operation safe and fast for LLM prompt preparation

## Frequently Asked Questions

### What fields does the Agent Reach Xiaohongshu formatter keep?

The formatter retains `note_id`, `title`, `desc` (or `content` as fallback), `user` with `nickname` and `user_id`, engagement metrics (`liked_count`, `collected_count`, `comment_count`, `share_count`), image URLs, tag names, and simplified comments. All other metadata is discarded to minimize token usage.

### How does the formatter handle different XHS API response shapes?

`format_xhs_result` detects whether the input is a list or dict, then checks for common wrapper keys (`items`, `data → items`, `data → notes`). It unwraps nested structures as needed before passing elements to `_clean_note`, ensuring consistent output regardless of the source endpoint.

### Where are the tests for the Xiaohongshu formatting logic?

Unit tests reside in [`tests/test_xhs_format.py`](https://github.com/Panniantong/Agent-Reach/blob/main/tests/test_xhs_format.py), covering edge cases including list inputs, single dict inputs, wrapped responses, and verification that redundant fields are properly stripped while essential fields are preserved.

### Can I use `format_xhs_result` outside the Agent Reach CLI?

Yes. The function is importable from `agent_reach.channels.xiaohongshu` and operates as a pure function on JSON data. It requires no CLI context, authentication, or network access—only the raw API response dictionary or list.