saveGraph serializes and persists the knowledge graph to storage.
(graph KnowledgeGraph)
| 150 | |
| 151 | // saveGraph serializes and persists the knowledge graph to storage. |
| 152 | func (k knowledgeBase) saveGraph(graph KnowledgeGraph) error { |
| 153 | items := make([]kbItem, 0, len(graph.Entities)+len(graph.Relations)) |
| 154 | |
| 155 | for _, entity := range graph.Entities { |
| 156 | items = append(items, kbItem{ |
| 157 | Type: "entity", |
| 158 | Name: entity.Name, |
| 159 | EntityType: entity.EntityType, |
| 160 | Observations: entity.Observations, |
| 161 | }) |
| 162 | } |
| 163 | |
| 164 | for _, relation := range graph.Relations { |
| 165 | items = append(items, kbItem{ |
| 166 | Type: "relation", |
| 167 | From: relation.From, |
| 168 | To: relation.To, |
| 169 | RelationType: relation.RelationType, |
| 170 | }) |
| 171 | } |
| 172 | |
| 173 | itemsJSON, err := json.Marshal(items) |
| 174 | if err != nil { |
| 175 | return fmt.Errorf("failed to marshal items: %w", err) |
| 176 | } |
| 177 | |
| 178 | if err := k.s.Write(itemsJSON); err != nil { |
| 179 | return fmt.Errorf("failed to write to store: %w", err) |
| 180 | } |
| 181 | return nil |
| 182 | } |
| 183 | |
| 184 | // createEntities adds new entities to the graph, skipping duplicates by name. |
| 185 | // It returns the new entities that were actually added. |