Parse 实现结构化解析。
(ctx context.Context, text string, spec OutputSpec)
| 40 | |
| 41 | // Parse 实现结构化解析。 |
| 42 | func (p *JSONParser) Parse(ctx context.Context, text string, spec OutputSpec) (*ParseResult, error) { |
| 43 | if !spec.Enabled { |
| 44 | return nil, errors.New("structured output is disabled") |
| 45 | } |
| 46 | |
| 47 | rawJSON, err := extractJSONSegment(text) |
| 48 | if err != nil { |
| 49 | return nil, fmt.Errorf("extract json: %w", err) |
| 50 | } |
| 51 | |
| 52 | var data any |
| 53 | if err := json.Unmarshal([]byte(rawJSON), &data); err != nil { |
| 54 | return nil, fmt.Errorf("json unmarshal: %w", err) |
| 55 | } |
| 56 | |
| 57 | missing := checkRequiredFields(data, spec.RequiredFields) |
| 58 | |
| 59 | return &ParseResult{ |
| 60 | RawText: text, |
| 61 | RawJSON: rawJSON, |
| 62 | Data: data, |
| 63 | MissingFields: missing, |
| 64 | }, nil |
| 65 | } |
| 66 | |
| 67 | // extractJSONSegment 尝试在文本中找到第一个配平的 JSON 对象/数组片段。 |
| 68 | func extractJSONSegment(text string) (string, error) { |
nothing calls this directly
no test coverage detected