(ctx context.Context, eid int64, chunk *model.DocumentChunk, entities []ExtractedEntity)
| 220 | } |
| 221 | |
| 222 | func (s *EntityExtractionService) persistEntities(ctx context.Context, eid int64, chunk *model.DocumentChunk, entities []ExtractedEntity) error { |
| 223 | tx := s.db.Begin() |
| 224 | defer func() { |
| 225 | if r := recover(); r != nil { |
| 226 | tx.Rollback() |
| 227 | } |
| 228 | }() |
| 229 | |
| 230 | var library model.Library |
| 231 | if err := tx.Select("id", "space_id"). |
| 232 | Where("eid = ? AND id = ?", eid, chunk.LibraryID). |
| 233 | First(&library).Error; err != nil { |
| 234 | tx.Rollback() |
| 235 | return err |
| 236 | } |
| 237 | |
| 238 | var relations []model.EntityChunkRelation |
| 239 | const minAutoLLMConfidence = 0.85 |
| 240 | seenEntityIDs := make(map[int64]struct{}) |
| 241 | createdEntities := make(map[int64]*model.Entity) |
| 242 | for _, e := range entities { |
| 243 | if e.Confidence < minAutoLLMConfidence { |
| 244 | continue |
| 245 | } |
| 246 | entityModel, created, err := model.GetOrCreateEntityWithDBAndCreated(tx, eid, e.Type, e.Name) |
| 247 | if err != nil { |
| 248 | tx.Rollback() |
| 249 | return err |
| 250 | } |
| 251 | if created { |
| 252 | createdEntities[entityModel.ID] = entityModel |
| 253 | } |
| 254 | if _, ok := seenEntityIDs[entityModel.ID]; ok { |
| 255 | continue |
| 256 | } |
| 257 | seenEntityIDs[entityModel.ID] = struct{}{} |
| 258 | |
| 259 | relations = append(relations, model.EntityChunkRelation{ |
| 260 | Eid: eid, |
| 261 | EntityID: entityModel.ID, |
| 262 | SpaceID: library.SpaceID, |
| 263 | LibraryID: chunk.LibraryID, |
| 264 | FileID: chunk.FileID, |
| 265 | ChunkID: chunk.ID, |
| 266 | ChunkType: chunk.ChunkType, |
| 267 | Status: model.EntityRelationStatusActive, |
| 268 | Confidence: e.Confidence, |
| 269 | Source: model.EntityRelationSourceAutoLLM, |
| 270 | }) |
| 271 | } |
| 272 | |
| 273 | if err := model.ReplaceEntityChunkRelationsBySourceWithDB(tx, eid, chunk.ID, model.EntityRelationSourceAutoLLM, relations); err != nil { |
| 274 | tx.Rollback() |
| 275 | return err |
| 276 | } |
| 277 | |
| 278 | if err := tx.Commit().Error; err != nil { |
| 279 | return err |
no test coverage detected