Knowledge Graph Integration for Agent Reasoning

Medium
Agents

Knowledge Graph for Agent Reasoning

Knowledge graphs provide structured world knowledge for agent reasoning.

Task

Implement KnowledgeGraph that:

  1. Stores entities (nodes) with typed properties.
  2. Stores typed, weighted relations (edges).
  3. Queries neighbors by entity and optional relation type.
  4. Finds shortest path between entities (BFS, max depth).
  5. Generates LLM-friendly context strings from entity neighborhoods.

Constraints

  • Entities must have unique IDs.
  • BFS must respect max_depth.
  • Context string format: {entity_id} ({type}): {properties}. Relations: {relation_type} → {target}.

Examples

Example 1:
Input: kg.add_entity(Entity('paris', 'city', {'population': 2e6})) kg.add_entity(Entity('france', 'country', {})) kg.add_relation(Relation('paris', 'capital_of', 'france')) kg.query('paris', 'capital_of')
Output: [Entity(id='france', ...)]
Explanation: Follows capital_of relation from paris to france.

Starter Code

from typing import List, Dict, Tuple, Optional, Set
from dataclasses import dataclass, field

@dataclass
class Entity:
    id: str
    entity_type: str
    properties: Dict

@dataclass
class Relation:
    source_id: str
    relation_type: str
    target_id: str
    confidence: float = 1.0

class KnowledgeGraph:
    def __init__(self):
        self.entities: Dict[str, Entity] = {}
        self.relations: List[Relation] = []

    def add_entity(self, entity: Entity) -> None:
        pass

    def add_relation(self, relation: Relation) -> None:
        pass

    def query(self, entity_id: str, relation_type: Optional[str] = None) -> List[Entity]:
        # TODO: Return related entities
        pass

    def find_path(self, start_id: str, end_id: str, max_depth: int = 3) -> Optional[List[str]]:
        # TODO: BFS to find shortest path between entities
        pass

    def to_context(self, entity_id: str, hops: int = 2) -> str:
        # TODO: Build LLM context string from entity neighborhood
        pass
Lines: 1Characters: 0
Ready
The AI Interview - Master AI/ML Interviews