Skip to main content

parse_llm_json

Function parse_llm_json 

Source
pub fn parse_llm_json(raw: &str) -> Result<LlmResponse>
Expand description

Parse a raw LLM API text response into an LlmResponse.

Handles the most common formatting quirks LLMs exhibit:

  • Plain JSON
  • JSON wrapped in ```json … ``` markdown fences
  • JSON wrapped in plain ``` … ``` fences
  • Leading / trailing whitespace

§Errors

Returns HsPredictError::LlmResponseParseError if the string cannot be deserialised as LlmResponse.

§Example

use hs_predict::llm::{parse_llm_json, LlmResponse};

let raw = r#"```json
{"hs_code":"291511","confidence":0.85,"rationale":"Acetic acid.","alternatives":[]}
```"#;

let r: LlmResponse = parse_llm_json(raw).unwrap();
assert_eq!(r.hs_code, "291511");