Spaces:
Running

File size: 6,992 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
"""Procedural memory: versioned prompts and SOPs with labels (``production`` for deploy and

rollback), behind a provider-agnostic ``PromptRegistry`` interface.



``LocalPromptRegistry`` keeps versions in ``prompt_versions`` (RLS). A Langfuse-backed

registry (Phase 15) implements the same four methods with Langfuse prompt management:

``get`` -> ``langfuse.get_prompt(name, label=...)``, ``create`` -> ``create_prompt``,

``set_label`` -> ``update_prompt(name, version, new_labels=[...])``.



Versions are immutable; a label points at exactly one version per name (setting it moves it).

Rollback = set ``production`` on an older version.

"""

from __future__ import annotations

import re
import uuid
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Protocol

from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession

from core.db.session import Database
from core.memory.models import PromptVersion
from core.tools.preview import sha256_hex

PRODUCTION = "production"
NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_.-]{0,199}$")
LABEL_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,39}$")
MAX_BODY = 20_000


class PromptError(ValueError):
    pass


@dataclass(frozen=True)
class PromptRecord:
    name: str
    version: int
    body: str
    labels: tuple[str, ...]
    created_by: str
    created_at: datetime | None
    checksum: str

    def as_dict(self) -> dict[str, Any]:
        return {
            "name": self.name,
            "version": self.version,
            "body": self.body,
            "labels": list(self.labels),
            "created_by": self.created_by,
            "created_at": self.created_at,
            "checksum": self.checksum,
        }


class PromptRegistry(Protocol):
    async def get(

        self, tenant_id: uuid.UUID, name: str, label: str = PRODUCTION

    ) -> PromptRecord | None: ...

    async def create(

        self,

        tenant_id: uuid.UUID,

        name: str,

        body: str,

        *,

        actor: str,

        labels: tuple[str, ...] = (),

    ) -> PromptRecord: ...

    async def set_label(

        self, tenant_id: uuid.UUID, name: str, version: int, label: str

    ) -> PromptRecord: ...

    async def versions(

        self, tenant_id: uuid.UUID, name: str | None = None

    ) -> list[PromptRecord]: ...


def _record(row: PromptVersion) -> PromptRecord:
    return PromptRecord(
        name=row.name,
        version=row.version,
        body=row.body,
        labels=tuple(row.labels or ()),
        created_by=row.created_by,
        created_at=row.created_at,
        checksum=row.checksum,
    )


def _check(name: str, labels: tuple[str, ...] = ()) -> None:
    if not NAME_RE.match(name):
        raise PromptError("prompt names are lowercase letters, digits, '.', '_' or '-'")
    for label in labels:
        if not LABEL_RE.match(label) or label == "latest":
            raise PromptError(f"invalid label {label!r}")


# Session-level operations (used by the gateway tool and by LocalPromptRegistry).


async def get_prompt(s: AsyncSession, name: str, label: str = PRODUCTION) -> PromptRecord | None:
    q = select(PromptVersion).where(PromptVersion.name == name)
    if label == "latest":
        q = q.order_by(PromptVersion.version.desc())
    else:
        q = q.where(PromptVersion.labels.contains([label]))
    row = (await s.execute(q.limit(1))).scalar_one_or_none()
    if row is None:
        return None
    if sha256_hex(row.body) != row.checksum:
        raise PromptError(f"prompt {name} v{row.version} failed its checksum")
    return _record(row)


async def create_prompt(

    s: AsyncSession,

    tenant_id: uuid.UUID,

    name: str,

    body: str,

    *,

    actor: str,

    labels: tuple[str, ...] = (),

) -> PromptRecord:
    _check(name, labels)
    if not body.strip() or len(body) > MAX_BODY:
        raise PromptError(f"prompt body must be 1-{MAX_BODY} characters")
    # Serialize version numbering per (tenant, name).
    await s.execute(select(func.pg_advisory_xact_lock(func.hashtext(f"prompt:{tenant_id}:{name}"))))
    latest = (
        await s.execute(select(func.max(PromptVersion.version)).where(PromptVersion.name == name))
    ).scalar_one()
    row = PromptVersion(
        tenant_id=tenant_id,
        name=name,
        version=int(latest or 0) + 1,
        body=body,
        labels=[],
        meta={},
        checksum=sha256_hex(body),
        created_by=actor[:120],
    )
    s.add(row)
    await s.flush()
    for label in labels:
        await set_prompt_label(s, name, row.version, label)
    await s.refresh(row)
    return _record(row)


async def set_prompt_label(s: AsyncSession, name: str, version: int, label: str) -> PromptRecord:
    _check(name, (label,))
    rows = list(
        (await s.execute(select(PromptVersion).where(PromptVersion.name == name))).scalars()
    )
    target = next((r for r in rows if r.version == version), None)
    if target is None:
        raise PromptError(f"prompt {name} has no version {version}")
    for r in rows:
        if r is not target and label in (r.labels or []):
            r.labels = [x for x in r.labels if x != label]
    if label not in (target.labels or []):
        target.labels = [*(target.labels or []), label]
    await s.flush()
    return _record(target)


async def list_prompts(s: AsyncSession, name: str | None = None) -> list[PromptRecord]:
    q = select(PromptVersion).order_by(PromptVersion.name, PromptVersion.version.desc())
    if name is not None:
        q = q.where(PromptVersion.name == name)
    return [_record(r) for r in (await s.execute(q)).scalars()]


class LocalPromptRegistry:
    def __init__(self, db: Database) -> None:
        self.db = db

    async def get(

        self, tenant_id: uuid.UUID, name: str, label: str = PRODUCTION

    ) -> PromptRecord | None:
        async with self.db.session(tenant_id=tenant_id) as s:
            return await get_prompt(s, name, label)

    async def create(

        self,

        tenant_id: uuid.UUID,

        name: str,

        body: str,

        *,

        actor: str,

        labels: tuple[str, ...] = (),

    ) -> PromptRecord:
        async with self.db.session(tenant_id=tenant_id) as s, s.begin():
            return await create_prompt(s, tenant_id, name, body, actor=actor, labels=labels)

    async def set_label(

        self, tenant_id: uuid.UUID, name: str, version: int, label: str

    ) -> PromptRecord:
        async with self.db.session(tenant_id=tenant_id) as s, s.begin():
            return await set_prompt_label(s, name, version, label)

    async def versions(self, tenant_id: uuid.UUID, name: str | None = None) -> list[PromptRecord]:
        async with self.db.session(tenant_id=tenant_id) as s:
            return await list_prompts(s, name)