(ctx context.Context, backend backends.BackendProtocol)
| 166 | } |
| 167 | |
| 168 | func demonstrateWithSchema(ctx context.Context, backend backends.BackendProtocol) { |
| 169 | // 定义 JSON Schema |
| 170 | schema := &memory.JSONSchema{ |
| 171 | Type: "object", |
| 172 | Properties: map[string]*memory.JSONSchema{ |
| 173 | "user_name": {Type: "string"}, |
| 174 | "role": {Type: "string"}, |
| 175 | "task_status": { |
| 176 | Type: "string", |
| 177 | Enum: []any{"not_started", "in_progress", "completed"}, |
| 178 | }, |
| 179 | "preferences": { |
| 180 | Type: "array", |
| 181 | Items: &memory.JSONSchema{Type: "string"}, |
| 182 | }, |
| 183 | }, |
| 184 | Required: []string{"user_name", "task_status"}, |
| 185 | } |
| 186 | |
| 187 | manager, err := memory.NewWorkingMemoryManager(&memory.WorkingMemoryConfig{ |
| 188 | Backend: backend, |
| 189 | BasePath: "/working_memory_schema/", |
| 190 | Scope: memory.ScopeThread, |
| 191 | Schema: schema, |
| 192 | }) |
| 193 | if err != nil { |
| 194 | log.Fatalf("create manager with schema: %v", err) |
| 195 | } |
| 196 | |
| 197 | threadID := "structured-session" |
| 198 | resourceID := "demo" |
| 199 | |
| 200 | // 有效的 JSON(符合 schema) |
| 201 | validJSON := `{ |
| 202 | "user_name": "Alice", |
| 203 | "role": "Engineer", |
| 204 | "task_status": "in_progress", |
| 205 | "preferences": ["TypeScript", "Functional Programming"] |
| 206 | }` |
| 207 | |
| 208 | err = manager.Update(ctx, threadID, resourceID, validJSON) |
| 209 | if err != nil { |
| 210 | log.Fatalf("unexpected error with valid JSON: %v", err) |
| 211 | } |
| 212 | fmt.Println("✓ 有效的 JSON 更新成功") |
| 213 | |
| 214 | // 无效的 JSON(缺少必需字段) |
| 215 | invalidJSON := `{ |
| 216 | "user_name": "Bob" |
| 217 | }` |
| 218 | |
| 219 | err = manager.Update(ctx, threadID, resourceID, invalidJSON) |
| 220 | if err != nil { |
| 221 | fmt.Printf("✓ 无效的 JSON 被拒绝(预期行为): %v\n", err) |
| 222 | } else { |
| 223 | fmt.Println("❌ 无效的 JSON 应该被拒绝") |
| 224 | } |
| 225 |
no test coverage detected