Phase 3: Skills & Context — skill system, personal context, context layering
Backend: - Skill model + migration (with FK on chats.skill_id) - Personal + general skill CRUD services with access isolation - Admin skill CRUD endpoints (POST/GET/PATCH/DELETE /admin/skills) - User skill CRUD endpoints (POST/GET/PATCH/DELETE /skills/) - Personal context GET/PUT at /users/me/context - Extended context assembly: primary + personal context + skill prompt - Chat creation/update now accepts skill_id with validation Frontend: - Skill selector dropdown in chat header (grouped: general + personal) - Reusable skill editor form component - Admin skills management page (/admin/skills) - Personal skills page (/skills) - Personal context editor page (/profile/context) - Updated sidebar: Skills, My Context nav items + admin skills link - English + Russian translations for all skill/context UI Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -9,31 +9,48 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.config import settings
|
||||
from app.models.chat import Chat
|
||||
from app.models.message import Message
|
||||
from app.services.context_service import DEFAULT_SYSTEM_PROMPT, get_primary_context
|
||||
from app.models.skill import Skill
|
||||
from app.services.context_service import DEFAULT_SYSTEM_PROMPT, get_primary_context, get_personal_context
|
||||
from app.services.chat_service import get_chat, save_message
|
||||
|
||||
client = AsyncAnthropic(api_key=settings.ANTHROPIC_API_KEY)
|
||||
|
||||
|
||||
async def assemble_context(
|
||||
db: AsyncSession, chat_id: uuid.UUID, user_message: str
|
||||
db: AsyncSession, chat_id: uuid.UUID, user_id: uuid.UUID, user_message: str
|
||||
) -> tuple[str, list[dict]]:
|
||||
"""Assemble system prompt and messages for Claude API."""
|
||||
system_parts = []
|
||||
|
||||
# 1. Primary context
|
||||
ctx = await get_primary_context(db)
|
||||
system_prompt = ctx.content if ctx and ctx.content.strip() else DEFAULT_SYSTEM_PROMPT
|
||||
system_parts.append(ctx.content if ctx and ctx.content.strip() else DEFAULT_SYSTEM_PROMPT)
|
||||
|
||||
# 2. Conversation history
|
||||
# 2. Personal context
|
||||
personal_ctx = await get_personal_context(db, user_id)
|
||||
if personal_ctx and personal_ctx.content.strip():
|
||||
system_parts.append(f"---\nUser Context:\n{personal_ctx.content}")
|
||||
|
||||
# 3. Active skill system prompt
|
||||
chat = await get_chat(db, chat_id, user_id)
|
||||
if chat.skill_id:
|
||||
result = await db.execute(select(Skill).where(Skill.id == chat.skill_id))
|
||||
skill = result.scalar_one_or_none()
|
||||
if skill and skill.is_active:
|
||||
system_parts.append(f"---\nSpecialist Role ({skill.name}):\n{skill.system_prompt}")
|
||||
|
||||
system_prompt = "\n\n".join(system_parts)
|
||||
|
||||
# 4. Conversation history
|
||||
result = await db.execute(
|
||||
select(Message)
|
||||
.where(Message.chat_id == chat_id, Message.role.in_(["user", "assistant"]))
|
||||
.order_by(Message.created_at.asc())
|
||||
)
|
||||
history = result.scalars().all()
|
||||
|
||||
messages = [{"role": msg.role, "content": msg.content} for msg in history]
|
||||
|
||||
# 3. Current user message
|
||||
# 5. Current user message
|
||||
messages.append({"role": "user", "content": user_message})
|
||||
|
||||
return system_prompt, messages
|
||||
@@ -56,7 +73,7 @@ async def stream_ai_response(
|
||||
|
||||
try:
|
||||
# Assemble context
|
||||
system_prompt, messages = await assemble_context(db, chat_id, user_message)
|
||||
system_prompt, messages = await assemble_context(db, chat_id, user_id, user_message)
|
||||
|
||||
# Stream from Claude
|
||||
full_content = ""
|
||||
|
||||
@@ -9,7 +9,7 @@ from app.models.message import Message
|
||||
from app.models.user import User
|
||||
|
||||
|
||||
async def create_chat(db: AsyncSession, user: User, title: str | None = None) -> Chat:
|
||||
async def create_chat(db: AsyncSession, user: User, title: str | None = None, skill_id: uuid.UUID | None = None) -> Chat:
|
||||
count = await db.scalar(
|
||||
select(func.count()).select_from(Chat).where(
|
||||
Chat.user_id == user.id, Chat.is_archived == False # noqa: E712
|
||||
@@ -21,7 +21,7 @@ async def create_chat(db: AsyncSession, user: User, title: str | None = None) ->
|
||||
detail="Chat limit reached. Archive or delete existing chats.",
|
||||
)
|
||||
|
||||
chat = Chat(user_id=user.id, title=title or "New Chat")
|
||||
chat = Chat(user_id=user.id, title=title or "New Chat", skill_id=skill_id)
|
||||
db.add(chat)
|
||||
await db.flush()
|
||||
return chat
|
||||
@@ -51,12 +51,15 @@ async def get_chat(db: AsyncSession, chat_id: uuid.UUID, user_id: uuid.UUID) ->
|
||||
async def update_chat(
|
||||
db: AsyncSession, chat_id: uuid.UUID, user_id: uuid.UUID,
|
||||
title: str | None = None, is_archived: bool | None = None,
|
||||
skill_id: uuid.UUID | None = None,
|
||||
) -> Chat:
|
||||
chat = await get_chat(db, chat_id, user_id)
|
||||
if title is not None:
|
||||
chat.title = title
|
||||
if is_archived is not None:
|
||||
chat.is_archived = is_archived
|
||||
if skill_id is not None:
|
||||
chat.skill_id = skill_id
|
||||
await db.flush()
|
||||
return chat
|
||||
|
||||
|
||||
@@ -23,6 +23,34 @@ async def get_primary_context(db: AsyncSession) -> ContextFile | None:
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_personal_context(db: AsyncSession, user_id: uuid.UUID) -> ContextFile | None:
|
||||
result = await db.execute(
|
||||
select(ContextFile).where(ContextFile.type == "personal", ContextFile.user_id == user_id)
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def upsert_personal_context(
|
||||
db: AsyncSession, user_id: uuid.UUID, content: str
|
||||
) -> ContextFile:
|
||||
ctx = await get_personal_context(db, user_id)
|
||||
if ctx:
|
||||
ctx.content = content
|
||||
ctx.version = ctx.version + 1
|
||||
ctx.updated_by = user_id
|
||||
else:
|
||||
ctx = ContextFile(
|
||||
type="personal",
|
||||
user_id=user_id,
|
||||
content=content,
|
||||
version=1,
|
||||
updated_by=user_id,
|
||||
)
|
||||
db.add(ctx)
|
||||
await db.flush()
|
||||
return ctx
|
||||
|
||||
|
||||
async def upsert_primary_context(
|
||||
db: AsyncSession, content: str, admin_user_id: uuid.UUID
|
||||
) -> ContextFile:
|
||||
|
||||
97
backend/app/services/skill_service.py
Normal file
97
backend/app/services/skill_service.py
Normal file
@@ -0,0 +1,97 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.skill import Skill
|
||||
|
||||
|
||||
async def get_accessible_skills(
|
||||
db: AsyncSession, user_id: uuid.UUID, include_general: bool = True
|
||||
) -> list[Skill]:
|
||||
conditions = [Skill.user_id == user_id]
|
||||
if include_general:
|
||||
conditions.append(Skill.user_id.is_(None))
|
||||
stmt = select(Skill).where(or_(*conditions), Skill.is_active == True).order_by(Skill.sort_order) # noqa: E712
|
||||
result = await db.execute(stmt)
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
async def get_skill(db: AsyncSession, skill_id: uuid.UUID, user_id: uuid.UUID | None = None) -> Skill:
|
||||
result = await db.execute(select(Skill).where(Skill.id == skill_id))
|
||||
skill = result.scalar_one_or_none()
|
||||
if not skill:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Skill not found")
|
||||
# Access check: must be general or owned by user
|
||||
if user_id and skill.user_id is not None and skill.user_id != user_id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Skill not found")
|
||||
return skill
|
||||
|
||||
|
||||
async def validate_skill_accessible(db: AsyncSession, skill_id: uuid.UUID, user_id: uuid.UUID) -> None:
|
||||
"""Validate skill exists and is accessible by user (general or owned). Raises 404 if not."""
|
||||
await get_skill(db, skill_id, user_id)
|
||||
|
||||
|
||||
# --- Personal skills ---
|
||||
|
||||
async def create_personal_skill(db: AsyncSession, user_id: uuid.UUID, **kwargs) -> Skill:
|
||||
skill = Skill(user_id=user_id, **kwargs)
|
||||
db.add(skill)
|
||||
await db.flush()
|
||||
return skill
|
||||
|
||||
|
||||
async def update_personal_skill(db: AsyncSession, skill_id: uuid.UUID, user_id: uuid.UUID, **kwargs) -> Skill:
|
||||
skill = await get_skill(db, skill_id, user_id)
|
||||
if skill.user_id != user_id:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Cannot edit general skills")
|
||||
for key, value in kwargs.items():
|
||||
if value is not None:
|
||||
setattr(skill, key, value)
|
||||
await db.flush()
|
||||
return skill
|
||||
|
||||
|
||||
async def delete_personal_skill(db: AsyncSession, skill_id: uuid.UUID, user_id: uuid.UUID) -> None:
|
||||
skill = await get_skill(db, skill_id, user_id)
|
||||
if skill.user_id != user_id:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Cannot delete general skills")
|
||||
await db.delete(skill)
|
||||
|
||||
|
||||
# --- General (admin) skills ---
|
||||
|
||||
async def get_general_skills(db: AsyncSession) -> list[Skill]:
|
||||
result = await db.execute(
|
||||
select(Skill).where(Skill.user_id.is_(None)).order_by(Skill.sort_order)
|
||||
)
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
async def create_general_skill(db: AsyncSession, **kwargs) -> Skill:
|
||||
skill = Skill(user_id=None, **kwargs)
|
||||
db.add(skill)
|
||||
await db.flush()
|
||||
return skill
|
||||
|
||||
|
||||
async def update_general_skill(db: AsyncSession, skill_id: uuid.UUID, **kwargs) -> Skill:
|
||||
result = await db.execute(select(Skill).where(Skill.id == skill_id, Skill.user_id.is_(None)))
|
||||
skill = result.scalar_one_or_none()
|
||||
if not skill:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="General skill not found")
|
||||
for key, value in kwargs.items():
|
||||
if value is not None:
|
||||
setattr(skill, key, value)
|
||||
await db.flush()
|
||||
return skill
|
||||
|
||||
|
||||
async def delete_general_skill(db: AsyncSession, skill_id: uuid.UUID) -> None:
|
||||
result = await db.execute(select(Skill).where(Skill.id == skill_id, Skill.user_id.is_(None)))
|
||||
skill = result.scalar_one_or_none()
|
||||
if not skill:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="General skill not found")
|
||||
await db.delete(skill)
|
||||
Reference in New Issue
Block a user