Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ notified the moment a prompt changes.
🐍 Your Python app
│
▼
PromptClient (this library) ──gRPC: get / list / diff──▶ 🗄️ Priompt server
│ ▲ │
│ └──────────── "prompt changed" push (NATS) ───────────┘
PromptClient (this library) ──gRPC: get/list/diff/publish──▶ 🗄️ Priompt server
│ ▲ │
│ └────────────── "prompt changed" push (NATS) ─────────────┘
▼
Optional local cache (cache_ttl seconds)
```
Expand Down Expand Up @@ -78,6 +78,7 @@ PromptClient(host=None, token=None, tls=False, ca_cert=None,
client.get(uri, ref="") # fetch a prompt (ref = branch or commit hash to pin a version)
client.list(prefix="") # browse a repo (URI prefix) like a folder
client.diff(uri, new_template) # semantic diff: stored version vs. your draft
client.publish(uri, template, slots=None, message="", branch="") # publish a new prompt version
client.subscribe(uri, on_change, reload=None) # be notified when the prompt changes
client.close()
```
Expand All @@ -97,6 +98,17 @@ Pin a version (ignore future changes until *you* decide to upgrade):
prompt = client.get("priompt://acme/support/agent", ref="1e8284f35650")
```

Publish a new version (slots are derived automatically unless passed explicitly):

```python
resp = client.publish(
"priompt://acme/onboarding/welcome",
"Hi {name}, welcome to {org}!",
message="friendlier greeting",
)
print(resp.version_hash)
```

## Live updates

When someone publishes a new version, the server pushes a notification that
Expand Down
40 changes: 40 additions & 0 deletions priompt_sdk/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import logging
import os
import re
import threading
import time
from urllib.parse import urlparse
Expand All @@ -14,6 +15,16 @@
_TOKEN_SAFE = frozenset(
b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"
)
_SLOT_RE = re.compile(r"\{\{|\}\}|\{([A-Za-z0-9_]+)\}")


def _derive_slots(template):
"""Extract {slot} names in first-seen order, skipping escaped {{ / }}."""
return list(
dict.fromkeys(
m.group(1) for m in _SLOT_RE.finditer(template) if m.group(1) is not None
)
)


def _subject(uri):
Expand Down Expand Up @@ -149,6 +160,35 @@ def diff(self, uri, new_template):
metadata=self._md,
)

def publish(self, uri, template, slots=None, message="", branch=""):
"""Validate and store a new prompt version on the server. Returns the
PublishPromptResponse (with `version_hash`).

When `slots` is None, placeholder names are derived from `template` in
first-seen order (skipping escaped `{{` / `}}`). Pass `branch` to write
to a non-default branch instead of `"main"`.
"""
if slots is None:
slots = _derive_slots(template)
resp = self._stub.PublishPrompt(
prompt_pb2.PublishPromptRequest(
uri=uri,
template=template,
slots=slots,
message=message,
branch=branch,
),
metadata=self._md,
)
# Unpinned get() and list() only serve the "main" HEAD, so non-main
# branch publishes leave the local cache intact.
if self._cache_ttl and branch in ("", "main"):
self._cache.pop(uri, None)
for key in list(self._cache):
if isinstance(key, tuple) and key[0] == "list" and uri.startswith(key[1]):
self._cache.pop(key, None)
return resp

def subscribe(self, uri, on_change, reload=None):
"""Register as a subscriber: call on_change(version_hash, classification)
whenever the prompt at `uri` is republished (push). `classification` is
Expand Down
106 changes: 104 additions & 2 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import pytest

from priompt_sdk import PromptClient
from priompt_sdk.client import _subject
from priompt_sdk.client import _derive_slots, _subject


class FakeStub:
Expand All @@ -23,6 +23,8 @@ def __init__(self):
self.get_calls = 0
self.list_calls = 0
self.diff_calls = 0
self.publish_calls = 0
self.last_publish = None

def GetPrompt(self, req, metadata=None):
self.get_calls += 1
Expand All @@ -37,6 +39,11 @@ def DiffPrompt(self, req, metadata=None):
self.diff_calls += 1
return f"diff:{req.uri}:{self.diff_calls}"

def PublishPrompt(self, req, metadata=None):
self.publish_calls += 1
self.last_publish = (req, metadata)
return type("Resp", (), {"version_hash": f"pub:{req.uri}:{self.publish_calls}"})


@pytest.fixture
def clock(monkeypatch):
Expand Down Expand Up @@ -364,4 +371,99 @@ async def connect_no_port(url, error_cb=None, **kw):
with pytest.raises(ConnectionError) as exc2:
c2.subscribe("priompt://x", lambda *_: None)
assert "127.0.0.1:5222" in str(exc2.value)
assert "secret-token" not in str(exc2.value)
assert "secret-token" not in str(exc2.value)


# --- publish: slot derivation and cache invalidation ----------------------

@pytest.mark.parametrize("template,expected", [
("Hi {name}, welcome to {org}!", ["name", "org"]),
("{b} then {a} then {b} and {c} and {a}", ["b", "a", "c"]),
("No placeholders here.", []),
("Literal {{name}} and {{org}} braces.", []),
("{{{name}}} {org} {{\"k\": \"{val}\"}}", ["name", "org", "val"]),
("{user_id_1} and {Item2}", ["user_id_1", "Item2"]),
])
def test_derive_slots(template, expected):
assert _derive_slots(template) == expected


def test_publish_derives_slots_and_forwards_fields():
c = PromptClient("localhost:1", token="tok123")
c._stub = FakeStub()
resp = c.publish(
"priompt://acme/onboarding/welcome",
"Hi {name}, welcome to {org}! Bye {name}.",
message="friendlier greeting",
branch="draft",
)
assert resp.version_hash == "pub:priompt://acme/onboarding/welcome:1"
req, md = c._stub.last_publish
assert req.uri == "priompt://acme/onboarding/welcome"
assert req.template == "Hi {name}, welcome to {org}! Bye {name}."
assert list(req.slots) == ["name", "org"]
assert req.message == "friendlier greeting"
assert req.branch == "draft"
assert md == [("authorization", "Bearer tok123")]


def test_publish_respects_explicit_slots():
c = make_client()
c.publish("priompt://x", "Hi {name}!", slots=["custom"])
req, _ = c._stub.last_publish
assert list(req.slots) == ["custom"]

# An explicit empty list must not fall back to derivation.
c.publish("priompt://x", "Hi {name}!", slots=[])
req, _ = c._stub.last_publish
assert list(req.slots) == []


def test_publish_invalidates_get_and_matching_list_cache(clock):
c = make_client(cache_ttl=10)
uri = "priompt://acme/onboarding/welcome"
other = "priompt://acme/onboarding/goodbye"

before_get = c.get(uri)
before_other = c.get(other)
before_all = c.list("")
before_acme = c.list("priompt://acme/")
before_unrelated = c.list("priompt://other/")

c.publish(uri, "Hi {name}!")

# Published URI and matching list prefixes are evicted and refetched.
assert c.get(uri) != before_get
assert c.list("") != before_all
assert c.list("priompt://acme/") != before_acme
# Unrelated get() and list() entries remain warm in the cache.
assert c.get(other) == before_other
assert c.list("priompt://other/") == before_unrelated
assert c._stub.get_calls == 3
assert c._stub.list_calls == 5


def test_publish_to_main_invalidates_cache(clock):
c = make_client(cache_ttl=10)
uri = "priompt://acme/onboarding/welcome"
before_get = c.get(uri)
before_list = c.list("priompt://acme/")

c.publish(uri, "Hi {name}!", branch="main")

assert c.get(uri) != before_get
assert c.list("priompt://acme/") != before_list


def test_publish_to_non_main_branch_keeps_cache(clock):
c = make_client(cache_ttl=10)
uri = "priompt://acme/onboarding/welcome"
before_get = c.get(uri)
before_list = c.list("priompt://acme/")

c.publish(uri, "Hi {name}!", branch="experiment")

assert c.get(uri) == before_get
assert c.list("priompt://acme/") == before_list
assert c._stub.get_calls == 1
assert c._stub.list_calls == 1
Loading