modify knowledge writer

This commit is contained in:
phernandez
2025-01-07 21:45:18 -06:00
parent 1c6836d83f
commit 286addb221
4 changed files with 177 additions and 60 deletions
@@ -115,14 +115,22 @@ async def add_observations(
@router.get("/entities/{path_id:path}", response_model=EntityResponse)
async def get_entity(path_id: PathId, knowledge_service: KnowledgeServiceDep) -> EntityResponse:
"""Get a specific entity by ID."""
async def get_entity(
knowledge_service: KnowledgeServiceDep,
path_id: PathId,
content: bool = False, # New parameter
) -> EntityResponse:
"""Get a specific entity by ID.
Args:
path_id: Entity path ID
content: If True, include full file content
"""
try:
entity = await knowledge_service.get_entity_by_path_id(path_id)
entity_response = EntityResponse.model_validate(entity)
# if the entity is a note, we add the content via reading from the file
if entity_response.entity_type == "note":
if content: # Load content if requested
content = await knowledge_service.read_entity_content(entity)
entity_response.content = content
@@ -130,7 +138,6 @@ async def get_entity(path_id: PathId, knowledge_service: KnowledgeServiceDep) ->
except EntityNotFoundError:
raise HTTPException(status_code=404, detail=f"Entity with {path_id} not found")
@router.post("/nodes", response_model=EntityListResponse)
async def open_nodes(
data: OpenNodesRequest, entity_service: EntityServiceDep
+61 -34
View File
@@ -4,7 +4,13 @@ from basic_memory.models import Entity as EntityModel
class KnowledgeWriter:
"""Formats entities into markdown files."""
"""Formats entities into markdown files.
Content handling:
1. If raw content is provided, use it directly
2. If structured data exists (observations/relations), generate structured content
3. If neither, create basic content from name/summary
"""
async def format_frontmatter(self, entity: EntityModel) -> dict:
"""Generate frontmatter metadata for entity."""
@@ -18,43 +24,64 @@ class KnowledgeWriter:
frontmatter.update(entity.entity_metadata)
return frontmatter
async def format_content(self, entity: EntityModel, content: str) -> str:
"""Format entity content as markdown."""
sections = [
f"# {entity.name}\n",
"", # Empty line after name
]
async def format_content(self, entity: EntityModel, content: str = None) -> str:
"""Format entity content as markdown.
Args:
entity: Entity to format
content: Optional raw content to use instead of generating structured content
Returns:
Formatted markdown content
"""
# If raw content provided, use it directly
if content is not None:
return content
if entity.summary:
sections.extend([entity.summary, ""])
# Otherwise, build structured content from entity data
sections = []
# Only add entity name as title if we don't have structured content
# This prevents duplicate titles when raw content already has a title
if not (entity.observations or entity.outgoing_relations):
sections.extend([
f"# {entity.name}",
"", # Empty line after title
])
if entity.summary:
sections.extend([entity.summary, ""])
# Add observations if present
if entity.observations:
sections.extend(
[
"## Observations",
"<!-- Format: - [category] Content text #tag1 #tag2 (optional context) -->",
"", # Empty line after format comment
*[
f"- [{obs.category}] {obs.content}"
+ (f" ({obs.context})" if obs.context else "")
for obs in entity.observations
],
"",
]
)
sections.extend([
"## Observations",
"<!-- Format: - [category] Content text #tag1 #tag2 (optional context) -->",
"", # Empty line after format comment
])
for obs in entity.observations:
line = f"- [{obs.category}] {obs.content}"
if obs.context:
line += f" ({obs.context})"
sections.append(line)
sections.append("") # Empty line after observations
# only outgoing relations are included in entity file
# Add relations if present
if entity.outgoing_relations:
sections.extend(
[
"## Relations",
"<!-- Format: - relation_type [[Entity]] (context) -->"
"", # Empty line after format comment
]
)
# Outgoing relations (entity is "from")
sections.extend([
"## Relations",
"<!-- Format: - relation_type [[Entity]] (context) -->",
"", # Empty line after format comment
])
for rel in entity.outgoing_relations:
sections.append(f"- {rel.relation_type} [[{rel.to_entity.name}]] ")
line = f"- {rel.relation_type} [[{rel.to_entity.name}]]"
if rel.context:
line += f" ({rel.context})"
sections.append(line)
sections.append("") # Empty line after relations
return "\n".join(sections)
# Return joined sections, ensure content isn't empty
content = "\n".join(sections).strip()
return content if content else f"# {entity.name}"