Agent Reach Format Command for XiaoHongShu API Output Processing: A Complete Guide

Agent Reach provides the format_xhs_result function in agent_reach/channels/xiaohongshu.py to normalize verbose XiaoHongShu API responses into compact, AI-friendly structures.

The Panniantong/Agent-Reach repository implements intelligent output processing for social media APIs, with dedicated handling for XiaoHongShu (XHS) content. The Agent Reach format command for XiaoHongShu API output processing strips away nested metadata and reduces token payload when feeding data to language models. This ensures consistent data shapes across single notes, search results, and paginated collections regardless of which backend (OpenCLI, xiaohongshu-mcp, or legacy xhs-cli) returns the raw data.

How format_xhs_result Normalizes XHS Responses

The formatter acts as a sanitation layer between the XHS API and your AI agents. It solves two critical problems: the API returns deeply nested objects with redundant fields, and different backends structure their responses differently.

Detecting List vs. Dictionary Payloads

In agent_reach/channels/xiaohongshu.py (lines 40–48), the function first inspects the top-level payload type. If the input is a list, each element is processed individually. If it is a dictionary, the code searches for the actual note collection under common wrapper keys such as items, data.items, or data.notes.

This detection logic ensures that whether you receive a direct note array or a wrapped search result, the formatter finds the content without manual unpacking.

Normalizing Note Collections

Once the collection is identified (lines 49–56), the function returns a standardized list of cleaned dictionaries. This step guarantees that downstream code always receives a predictable list structure, even when the original API returns a single object or a paginated wrapper.

Extracting Core Fields with _clean_note

The heavy lifting occurs in _clean_note (lines 62–130). This helper extracts only the fields an AI agent needs:

  • Identifiers: id, note_id
  • Content: title, desc, content
  • Author info: nickname, user_id
  • Engagement metrics: liked_count, collected_count, comment_count, share_count

According to the source code, the function deliberately discards UI-specific metadata, internal tracking IDs, and display configuration objects that consume tokens without adding semantic value.

Handling Images, Tags, and Comments

The formatter flattens nested structures into simple arrays:

  • Images (lines 99–112): Extracts URLs from nested image_list objects into a flat list of strings under the key images.
  • Tags (lines 114–124): Converts tag_list objects into a simple array of tag names.
  • Comments (lines 125–128): Processes comment arrays through _clean_comment to retain only content, author nickname, and basic counters.

If the payload is neither a list nor a dictionary (line 59), the function returns it untouched, allowing the caller to handle unexpected formats gracefully.

Source Code Implementation Details

The XiaoHongShu channel implementation resides in agent_reach/channels/xiaohongshu.py. The format_xhs_result function serves as the public API, while _clean_note remains the internal workhorse for field extraction.

The channel inherits from the abstract base class defined in agent_reach/channels/base.py, which specifies the interface for can_handle, read, search, and check methods. Core routing logic in agent_reach/core.py automatically invokes the formatter when processing read or search calls, and the CLI entry point in agent_reach/cli.py exposes this functionality via the read sub-command.

Practical Code Examples

Normalizing a Raw API Response

from agent_reach.channels.xiaohongshu import format_xhs_result

# Raw XHS API payload with nested structures

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"}],
                }
            }
        ]
    }
}

# Process through Agent Reach format command

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']}]

Using the Formatter via AgentReach Core

from agent_reach.core import AgentReach

ar = AgentReach()

# The channel automatically calls format_xhs_result when reading

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

Summary

  • The format_xhs_result function in agent_reach/channels/xiaohongshu.py normalizes XHS API output by extracting only essential fields.
  • It handles three backend variants (OpenCLI, xiaohongshu-mcp, xhs-cli) and multiple wrapper formats (items, data.items, data.notes).
  • The _clean_note helper (lines 62–130) extracts IDs, content, author info, and engagement metrics while discarding UI metadata.
  • Images and tags are flattened into simple arrays to minimize token usage for LLM consumption.
  • The formatter is automatically invoked by the AgentReach core when processing read or search operations.

Frequently Asked Questions

What is the format_xhs_result command in Agent Reach?

The format_xhs_result command is a utility function defined in agent_reach/channels/xiaohongshu.py that processes raw XiaoHongShu API responses. It strips away verbose nested structures and returns a clean, consistent dictionary format suitable for AI agent consumption, significantly reducing token costs when sending data to language models.

How does Agent Reach handle XiaoHongShu API list responses?

Agent Reach detects list structures at line 40 of xiaohongshu.py and iterates through each element with _clean_note. For dictionary payloads, it searches common collection keys like items, data.items, or data.notes to locate the actual note array before processing, ensuring consistent output regardless of the backend wrapper format.

Which fields does the XHS formatter extract from API responses?

According to the source code in lines 72–98, the formatter extracts identifiers (note_id, id), content fields (title, desc), author information (nickname, user_id), and engagement metrics (liked_count, collected_count, comment_count, share_count). It also normalizes nested image lists and tag collections into flat arrays.

Where is the XiaoHongShu formatting logic implemented in Agent Reach?

The formatting logic is implemented in agent_reach/channels/xiaohongshu.py within the XiaoHongShuChannel class. The public format_xhs_result function handles payload detection and collection normalization, while the private _clean_note method (lines 62–130) performs the detailed field extraction and data cleaning.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →