# How to Use the Agent Reach Format Command for XiaoHongShu Output

> Master the Agent Reach format command for XiaoHongShu output. Normalize API responses into clean JSON by extracting key data with the format_xhs_result function.

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

---

**Agent Reach provides 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 normalize verbose XiaoHongShu API responses into clean, agent-ready JSON by extracting only essential fields like identifiers, content, author data, and engagement metrics.**

The **Agent Reach** library (available at `Panniantong/Agent-Reach`) streamlines interactions with social media APIs by providing consistent output formatting across multiple backends. When working with XiaoHongShu (XHS) data, the **Agent Reach format command for XiaoHongShu output**—specifically the `format_xhs_result` function—transforms nested, verbose API payloads into compact structures optimized for AI agent consumption and reduced token usage.

## What Is the `format_xhs_result` Command?

The `format_xhs_result` command is a dedicated formatter defined within the **XiaoHongShuChannel** implementation. This channel abstracts three possible back-ends: OpenCLI, xiaohongshu-mcp, and the legacy xhs-cli. Its primary purpose is to strip away extraneous metadata from XHS API responses while preserving the fields an AI agent actually needs when reading or searching notes. This normalization ensures consistent output shape whether the response contains a single note, a list of notes, or wrapped search results.

## How the Normalization Works

### Detecting Payload Structure

At lines 40-48 of [`agent_reach/channels/xiaohongshu.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/xiaohongshu.py), the formatter first inspects the top-level payload type. If the input is a list, each element is processed individually via the cleaning pipeline. If it is a dictionary, the function searches for note collections under common wrapper keys such as `items`, `data.items`, or `data.notes` (lines 49-56).

### Cleaning Individual Notes

The heavy lifting occurs in the `_clean_note` helper (lines 62-130). This function extracts critical identifiers (`id`, `note_id`), content fields (`title`, `desc`, `content`), author information (`nickname`, `user_id`), and engagement metrics (`liked_count`, `collected_count`, `comment_count`, `share_count`). The implementation at lines 72-98 specifically handles the extraction of these core fields from the deeply nested XHS response structure.

### Normalizing Nested Media and Metadata

The formatter flattens complex nested structures into simple, agent-friendly lists:

- **Images** (lines 99-112): Nested image objects are extracted into a flat list of URLs under the `images` key.
- **Tags** (lines 114-124): Tag objects are normalized to a list of tag names under the `tags` key.
- **Comments** (lines 125-128): If present, comments are processed via `_clean_comment` to retain only `content`, short author name, and basic counters.

### Handling Edge Cases

If the payload is neither a list nor a dictionary, the function returns the data unchanged at line 59, allowing the caller to handle unexpected formats gracefully without throwing errors.

## Practical Implementation Examples

### Direct API Normalization

Use the formatter directly when processing raw XHS API responses:

```python
from agent_reach.channels.xiaohongshu import format_xhs_result

# Raw XHS API response with nested structure

raw_response = {
    "data": {
        "items": [
            {
                "note_card": {
                    "note_id": "12345",
                    "title": "My travel diary",
                    "desc": "A short description",
                    "user": {"nickname": "Alice", "user_id": "u987"},
                    "interact_info": {"liked_count": 42, "comment_count": 5},
                    "image_list": [
                        {"url": "https://example.com/img1.jpg"},
                        {"url": "https://example.com/img2.jpg"},
                    ],
                    "tag_list": [{"name": "travel"}, {"name": "photography"}],
                }
            }
        ]
    }
}

# Normalize to agent-friendly format

clean = format_xhs_result(raw_response)

print(clean)

# Output: [{'note_id': '12345', 'title': 'My travel diary', 'desc': 'A short description', 

#   'user': {'nickname': 'Alice', 'user_id': 'u987'}, 'liked_count': 42, 'comment_count': 5,

#   'images': ['https://example.com/img1.jpg', 'https://example.com/img2.jpg'],

#   'tags': ['travel', 'photography']}]

```

### Channel Integration

When using the high-level Agent Reach API, the formatter applies automatically:

```python
from agent_reach.core import AgentReach

ar = AgentReach()

# The channel automatically calls format_xhs_result for you

note = ar.read("https://www.xiaohongshu.com/explore/12345")
print(note)  # Already in the normalized shape

```

## Summary

- The **`format_xhs_result`** function in [`agent_reach/channels/xiaohongshu.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/xiaohongshu.py) provides the primary **Agent Reach format command for XiaoHongShu output**.
- It supports three backends (OpenCLI, xiaohongshu-mcp, xhs-cli) through the XiaoHongShuChannel abstraction.
- The formatter extracts only essential fields: identifiers, content, author info, and engagement metrics, discarding verbose metadata.
- Nested structures for images, tags, and comments are flattened into simple lists to minimize token usage.
- Both single notes and search result collections are handled automatically, with edge cases passed through unchanged.

## Frequently Asked Questions

### Where is the `format_xhs_result` function defined?

The function is implemented in [`agent_reach/channels/xiaohongshu.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/xiaohongshu.py) as part of the XiaoHongShu channel module. According to the source code, the main logic resides between lines 40 and 130, utilizing helper functions like `_clean_note` for detailed field extraction.

### What fields does the formatter extract from XiaoHongShu notes?

The formatter retains essential identifiers (`note_id`, `id`), content metadata (`title`, `desc`), author details (`nickname`, `user_id`), engagement statistics (`liked_count`, `collected_count`, `comment_count`, `share_count`), plus normalized arrays for `images` and `tags`. This selection targets the specific data points AI agents need for content analysis.

### Does the formatter handle both single notes and bulk search results?

Yes. The function automatically detects whether the input is a single dictionary or a collection. For search results, it normalizes collections found under keys like `items`, `data.items`, or `data.notes` into a consistent list of cleaned note objects, ensuring uniform output regardless of the API endpoint used.

### How does Agent Reach handle unexpected API structures?

If the payload is neither a list nor a dictionary, the function returns the data unchanged at line 59 of [`xiaohongshu.py`](https://github.com/Panniantong/Agent-Reach/blob/main/xiaohongshu.py). This fallback behavior allows downstream error handling or custom processing by the caller without breaking the agent workflow.