AnanthaJson.ResponseParser (llm_utils v0.1.0)

Copy Markdown View Source

Single entry point for all LLM JSON parsing.

Uses JsonRemedy.repair/1 as the only decoding path. It handles:

  • Markdown code fence extraction (json,, etc.)
  • Malformed JSON repair (unquoted keys, single quotes, trailing commas)
  • Plain text detection
  • Structural repair (missing braces, brackets)
  • Concatenated JSON detection (multiple JSON objects merged together)

Summary

Functions

Parses LLM response content and returns the first complete JSON object.

Parses LLM response and extracts a specific key value.

Parses LLM response and returns a decoded JSON array.

Finds the first JSON object in content that contains the specified key.

Parses LLM content with relaxed JSON handling.

Functions

parse(content)

@spec parse(String.t()) :: {:ok, map()} | {:error, atom()}

Parses LLM response content and returns the first complete JSON object.

Handles markdown wrapping, plain JSON, and concatenated JSON. Returns {:ok, map} for valid JSON objects, or {:error, atom} on failure.

parse_and_extract(content, key)

@spec parse_and_extract(String.t(), String.t()) :: {:ok, any()} | {:error, atom()}

Parses LLM response and extracts a specific key value.

parse_array(content)

@spec parse_array(String.t()) :: {:ok, list()} | {:error, atom()}

Parses LLM response and returns a decoded JSON array.

Uses JsonRemedy.repair/1 to decode the content. If the result is a list, returns it as {:ok, list}. Otherwise returns {:error, :not_an_array}.

parse_first_with_key(content, key)

@spec parse_first_with_key(String.t(), String.t()) :: {:ok, map()} | {:error, atom()}

Finds the first JSON object in content that contains the specified key.

Uses JsonExtractor.extract_all_objects/1 to locate all JSON strings within the content, decodes each one with JsonRemedy.repair/1, and returns the first decoded object that contains the given key.

parse_relaxed(content)

@spec parse_relaxed(String.t()) :: {:ok, map() | list()} | {:error, atom()}

Parses LLM content with relaxed JSON handling.

Uses JsonRemedy.repair/1 which handles unquoted keys, single quotes, trailing commas, and other common LLM output issues natively. Returns {:ok, result} for any valid parsed result (map or list).