"""知识节点相关 API""" from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.future import select from ..database import get_db from ..dependencies.tenant import get_tenant_id from ..models import ContextNode from ..schemas import ContextNodeCreate from ..services.llm import llm_service router = APIRouter(prefix="/context_nodes", tags=["context"]) @router.get("/") async def list_context_nodes(db: AsyncSession = Depends(get_db)): result = await db.execute(select(ContextNode)) nodes = result.scalars().all() return [ { "id": node.id, "content": node.content, "status": node.status, "version": node.version, "has_embedding": node.embedding is not None, "ai_insights": node.ai_insights, } for node in nodes ] @router.post("/") async def create_context_node( node: ContextNodeCreate, db: AsyncSession = Depends(get_db), tenant_id: int = Depends(get_tenant_id), ): try: embedding = await llm_service.get_embedding_async( node.content, db=db, tenant_id=tenant_id, ) insights = await llm_service.extract_context_insights_async( node.content, db=db, tenant_id=tenant_id, ) except RuntimeError: raise HTTPException(status_code=403, detail="预算超限,AI 调用被阻止(hard limit)") new_node = ContextNode( content=node.content, embedding=embedding if embedding else None, ai_insights=insights, ) db.add(new_node) await db.commit() await db.refresh(new_node) return { "id": new_node.id, "content": new_node.content, "status": new_node.status, "version": new_node.version, "has_embedding": new_node.embedding is not None, "ai_insights": new_node.ai_insights, }