Spaces:
Running

File size: 11,158 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
"""Knowledge, memory and prompt endpoints (Phase 12).



Knowledge (business documents; managers upload, everyone can search):



* ``GET /knowledge/docs`` / ``POST /knowledge/docs`` / ``DELETE /knowledge/docs/{id}``

  (upload JSON: ``content_base64`` + ``filename``, or ``text``, or ``url``);

* ``GET /knowledge/docs/{id}/chunks``; ``GET /knowledge/search?q=`` (hits with citations,

  marked ``untrusted``).



Memory (privacy: inspect and erase what the agent remembers):



* ``GET /memory/items?kind=customer|prefs|case`` ; ``GET /memory/customers/{id}`` ;

  ``DELETE /memory/customers/{id}`` (erase everything remembered about a customer) ;

  ``DELETE /memory/items/{id}``.



Prompts (procedural memory): ``GET /prompts`` ; ``POST /prompts/{name}/versions`` ;

``PUT /prompts/{name}/labels/{label}`` (deploy / rollback by moving ``production``).

"""

from __future__ import annotations

import base64
import binascii
import uuid
from typing import Any, Literal

from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel, Field, model_validator
from sqlalchemy import delete

from core.api.routes.runs import services
from core.auth.deps import Principal, current_principal, require_role
from core.memory.knowledge import IngestError, KnowledgeBase, detect_type
from core.memory.models import KnowledgeDoc, MemoryItem
from core.memory.prompts import LocalPromptRegistry, PromptError, PromptRegistry
from core.memory.store import MemoryRepo, MemoryStores, customer_ns, tenant_prefix
from core.services import Services
from core.tenancy.models import Role

router = APIRouter(tags=["knowledge"])


def _kb(svc: Services) -> KnowledgeBase:
    if svc.knowledge is None:  # pragma: no cover - build_services always sets it
        raise HTTPException(503, "knowledge base unavailable")
    return svc.knowledge


def _repo(svc: Services) -> MemoryRepo:
    return (svc.memory or MemoryStores(svc.db)).repo


def _prompts(svc: Services) -> PromptRegistry:
    return svc.prompts or LocalPromptRegistry(svc.db)


def _doc_out(d: KnowledgeDoc) -> dict[str, Any]:
    return {
        "id": str(d.id),
        "title": d.title,
        "source_type": d.source_type,
        "source_uri": d.source_uri,
        "size_bytes": d.size_bytes,
        "page_count": d.page_count,
        "chunk_count": d.chunk_count,
        "status": d.status,
        "flagged_chunks": int((d.meta or {}).get("flagged_chunks", 0)),
        "created_by": d.created_by,
        "created_at": d.created_at,
    }


class DocIn(BaseModel):
    title: str | None = Field(default=None, max_length=300)
    filename: str | None = Field(default=None, max_length=300)
    content_type: str | None = Field(default=None, max_length=200)
    content_base64: str | None = None
    text: str | None = Field(default=None, max_length=2_000_000)
    url: str | None = Field(default=None, max_length=2000)

    @model_validator(mode="after")
    def _one_source(self) -> DocIn:
        given = [x for x in (self.content_base64, self.text, self.url) if x]
        if len(given) != 1:
            raise ValueError("give exactly one of content_base64, text or url")
        return self


@router.get("/knowledge/docs")
async def list_docs(

    p: Principal = Depends(current_principal), svc: Services = Depends(services)

) -> list[dict[str, Any]]:
    async with svc.db.session(tenant_id=p.tenant_id) as s:
        return [_doc_out(d) for d in await _kb(svc).list_docs(s)]


@router.post("/knowledge/docs", status_code=status.HTTP_201_CREATED)
async def upload_doc(

    body: DocIn,

    p: Principal = Depends(require_role(Role.MANAGER)),

    svc: Services = Depends(services),

) -> dict[str, Any]:
    kb = _kb(svc)
    try:
        async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
            if body.url:
                doc = await kb.ingest_url(s, p.tenant_id, body.url, actor=p.actor, title=body.title)
            else:
                if body.content_base64:
                    try:
                        data = base64.b64decode(body.content_base64, validate=True)
                    except (binascii.Error, ValueError) as exc:
                        raise IngestError("content_base64 is not valid base64") from exc
                    kind = detect_type(body.filename, body.content_type)
                else:
                    data = (body.text or "").encode()
                    kind = "markdown" if (body.filename or "").endswith(".md") else "text"
                doc = await kb.ingest(
                    s,
                    p.tenant_id,
                    title=body.title or body.filename or "Untitled",
                    data=data,
                    source_type=kind,
                    actor=p.actor,
                )
            return _doc_out(doc)
    except IngestError as exc:
        raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, str(exc)) from exc


@router.delete("/knowledge/docs/{doc_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_doc(

    doc_id: uuid.UUID,

    p: Principal = Depends(require_role(Role.MANAGER)),

    svc: Services = Depends(services),

) -> None:
    async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
        if not await _kb(svc).delete_doc(s, doc_id):
            raise HTTPException(404, "document not found")


@router.get("/knowledge/docs/{doc_id}/chunks")
async def doc_chunks(

    doc_id: uuid.UUID,

    p: Principal = Depends(current_principal),

    svc: Services = Depends(services),

) -> list[dict[str, Any]]:
    async with svc.db.session(tenant_id=p.tenant_id) as s:
        rows = await _kb(svc).chunks(s, doc_id)
    return [
        {"id": str(c.id), "ordinal": c.ordinal, "page": c.page, "text": c.text,
         "flags": list(c.flags or [])}
        for c in rows
    ]  # fmt: skip


@router.get("/knowledge/search")
async def search_knowledge(

    q: str = Query(min_length=2, max_length=500),

    k: int = Query(default=5, ge=1, le=20),

    p: Principal = Depends(current_principal),

    svc: Services = Depends(services),

) -> dict[str, Any]:
    async with svc.db.session(tenant_id=p.tenant_id) as s:
        hits = await _kb(svc).search(s, q, k)
    return {"untrusted": True, "hits": [h.as_dict() for h in hits]}


# ------------------------------------------------------------------------------ memory


def _item_out(row: MemoryItem, ok: bool) -> dict[str, Any]:
    return {
        "id": str(row.id),
        "namespace": row.namespace.split("."),
        "key": row.key,
        "kind": row.kind,
        "value": row.value if ok else None,
        "integrity_ok": ok,
        "size_bytes": row.size_bytes,
        "written_by": row.written_by,
        "created_at": row.created_at,
        "updated_at": row.updated_at,
        "expires_at": row.expires_at,
    }


KIND_PREFIX = {"customer": ("customer",), "prefs": ("prefs",), "case": ("cases",)}


@router.get("/memory/items")
async def memory_items(

    kind: Literal["customer", "prefs", "case"] | None = None,

    p: Principal = Depends(require_role(Role.MANAGER)),

    svc: Services = Depends(services),

) -> list[dict[str, Any]]:
    prefix = (*tenant_prefix(p.tenant_id), *(KIND_PREFIX[kind] if kind else ()))
    async with svc.db.session(tenant_id=p.tenant_id) as s:
        rows = await _repo(svc).list_items(s, p.tenant_id, prefix)
    return [_item_out(r, ok) for r, ok in rows]


@router.get("/memory/customers/{customer_id}")
async def customer_memory(

    customer_id: str,

    p: Principal = Depends(require_role(Role.MANAGER)),

    svc: Services = Depends(services),

) -> list[dict[str, Any]]:
    async with svc.db.session(tenant_id=p.tenant_id) as s:
        rows = await _repo(svc).list_items(s, p.tenant_id, customer_ns(p.tenant_id, customer_id))
    return [_item_out(r, ok) for r, ok in rows]


@router.delete("/memory/customers/{customer_id}")
async def forget_customer(

    customer_id: str,

    p: Principal = Depends(require_role(Role.MANAGER)),

    svc: Services = Depends(services),

) -> dict[str, int]:
    async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
        n = await _repo(svc).purge(s, p.tenant_id, customer_ns(p.tenant_id, customer_id))
    return {"deleted": n}


@router.delete("/memory/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_item(

    item_id: uuid.UUID,

    p: Principal = Depends(require_role(Role.MANAGER)),

    svc: Services = Depends(services),

) -> None:
    async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
        res = await s.execute(
            delete(MemoryItem).where(MemoryItem.id == item_id).returning(MemoryItem.id)
        )
        if res.first() is None:
            raise HTTPException(404, "memory item not found")


# ----------------------------------------------------------------------------- prompts


class PromptIn(BaseModel):
    body: str = Field(min_length=1, max_length=20_000)
    labels: list[str] = Field(default_factory=list, max_length=10)


class LabelIn(BaseModel):
    version: int = Field(ge=1)


@router.get("/prompts")
async def list_prompts(

    name: str | None = None,

    p: Principal = Depends(current_principal),

    svc: Services = Depends(services),

) -> list[dict[str, Any]]:
    return [r.as_dict() for r in await _prompts(svc).versions(p.tenant_id, name)]


@router.post("/prompts/{name}/versions", status_code=status.HTTP_201_CREATED)
async def create_prompt_version(

    name: str,

    body: PromptIn,

    p: Principal = Depends(require_role(Role.MANAGER)),

    svc: Services = Depends(services),

) -> dict[str, Any]:
    try:
        rec = await _prompts(svc).create(
            p.tenant_id, name, body.body, actor=p.actor, labels=tuple(body.labels)
        )
    except PromptError as exc:
        raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, str(exc)) from exc
    return rec.as_dict()


@router.put("/prompts/{name}/labels/{label}")
async def set_prompt_label(

    name: str,

    label: str,

    body: LabelIn,

    p: Principal = Depends(require_role(Role.MANAGER)),

    svc: Services = Depends(services),

) -> dict[str, Any]:
    try:
        rec = await _prompts(svc).set_label(p.tenant_id, name, body.version, label)
    except PromptError as exc:
        raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, str(exc)) from exc
    return rec.as_dict()


@router.get("/prompts/{name}/resolve")
async def resolve_prompt(

    name: str,

    label: str = "production",

    p: Principal = Depends(current_principal),

    svc: Services = Depends(services),

) -> dict[str, Any]:
    try:
        rec = await _prompts(svc).get(p.tenant_id, name, label)
    except PromptError as exc:
        raise HTTPException(status.HTTP_409_CONFLICT, str(exc)) from exc
    if rec is None:
        raise HTTPException(404, f"no {label} version of {name}")
    return rec.as_dict()