ParseTyped 执行类型化解析
(ctx context.Context, text string, spec TypedOutputSpec)
| 112 | |
| 113 | // ParseTyped 执行类型化解析 |
| 114 | func ParseTyped(ctx context.Context, text string, spec TypedOutputSpec) (*TypedParseResult, error) { |
| 115 | result := &TypedParseResult{ |
| 116 | RawText: text, |
| 117 | Success: false, |
| 118 | } |
| 119 | |
| 120 | // 创建目标实例 |
| 121 | if spec.StructType == nil { |
| 122 | return nil, errors.New("struct type is required") |
| 123 | } |
| 124 | |
| 125 | targetType := reflect.TypeOf(spec.StructType) |
| 126 | if targetType.Kind() == reflect.Ptr { |
| 127 | targetType = targetType.Elem() |
| 128 | } |
| 129 | |
| 130 | target := reflect.New(targetType).Interface() |
| 131 | |
| 132 | // 创建解析器 |
| 133 | parser := NewTypedParser(spec.Schema) |
| 134 | |
| 135 | // 解析 |
| 136 | if err := parser.ParseInto(ctx, text, target); err != nil { |
| 137 | if !spec.AllowTextBackup { |
| 138 | return result, fmt.Errorf("parse failed: %w", err) |
| 139 | } |
| 140 | result.ValidationErrors = append(result.ValidationErrors, err.Error()) |
| 141 | return result, nil |
| 142 | } |
| 143 | |
| 144 | result.Data = target |
| 145 | result.Success = true |
| 146 | |
| 147 | // 提取 JSON(用于记录) |
| 148 | rawJSON, _ := extractJSONSegment(text) |
| 149 | result.RawJSON = rawJSON |
| 150 | |
| 151 | // 检查必填字段 |
| 152 | if len(spec.RequiredFields) > 0 { |
| 153 | var dataMap map[string]any |
| 154 | if err := json.Unmarshal([]byte(rawJSON), &dataMap); err == nil { |
| 155 | result.MissingFields = checkRequiredFields(dataMap, spec.RequiredFields) |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | // 自定义验证 |
| 160 | if spec.CustomValidation != nil { |
| 161 | if err := spec.CustomValidation(target); err != nil { |
| 162 | result.ValidationErrors = append(result.ValidationErrors, err.Error()) |
| 163 | if spec.Strict { |
| 164 | result.Success = false |
| 165 | return result, fmt.Errorf("custom validation failed: %w", err) |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | return result, nil |
| 171 | } |