-
Notifications
You must be signed in to change notification settings - Fork 4
feat(sdk): generic PersonaAgent NPC — pack-agnostic tools, comms, scoped memory #364
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
westonbrown
wants to merge
12
commits into
main
Choose a base branch
from
feat/persona-npc
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
5442e45
feat(sdk): generic PersonaAgent NPC — pack-agnostic tools, comms, sco…
westonbrown f49753d
refactor(sdk): second-pass review — reliability, believability, CI co…
westonbrown 8ae44d9
fix(sdk): make persona tests CI-robust; deterministic blank-name ids
westonbrown d3e5708
refactor(sdk): trim over-engineered edges (simplicity review)
westonbrown 50c6d47
chore(deps): bump strands-agents 1.38.0 -> 1.45.0 (tools 0.8.2)
westonbrown 153d620
feat(sdk): procedural persona diversity — numeric traits + sample_per…
westonbrown ed9f0af
fix(sdk): persona robustness + scale hardening from real-episode probing
westonbrown 980942c
fix(core): NPC-runtime robustness discovered by persona scale testing
westonbrown 2684bf5
feat(sdk): personas animate on the dashboard + CI-gated feature evals
westonbrown 9a890ea
feat(examples): live believability eval + catch reasoning-leak tells
westonbrown 849b10f
fix: front+back peer-review polish + real SPA-render regression test
westonbrown 11591fb
chore: address review — trim log-style comments, drop test-shaped exa…
westonbrown File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
117 changes: 117 additions & 0 deletions
117
packages/openrange-pack-sdk/src/openrange_pack_sdk/comms.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,117 @@ | ||
| """Environment-mediated communication channels for NPCs. | ||
|
|
||
| Comms flow THROUGH THE WORLD, never through a direct agent-to-agent handle: an | ||
| NPC writes a shared store via a pack-surfaced callable, and other NPCs (and a | ||
| grader) perceive the message only by reading the same store. A pack surfaces | ||
| these closures from ``surface_extras()`` so they land in every NPC's per-tick | ||
| ``interface``, and drains the store in ``collect_extras()`` so a grader can read | ||
| what was said and attribute it by sender. | ||
|
|
||
| Runtime hands the SAME frozen surface mapping to every NPC, so the surface | ||
| closures are IDENTITY-NEUTRAL: ``sender`` is an explicit argument. Identity is | ||
| bound one layer up, NPC-side, where each persona injects its own ``actor_id`` | ||
| (and never exposes ``sender`` to the model) — so cover traffic is attributable | ||
| by construction and a persona cannot forge another's identity. | ||
|
|
||
| Everything here is deterministic (monotonic ids, insertion order, no clock or | ||
| randomness) so a fixed seed replays identically. The stores are NOT thread-safe; | ||
| the harness steps NPCs on a single thread today, so a lock would be dead weight | ||
| (add one if parallel/async stepping ever lands). | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from collections.abc import Callable | ||
| from dataclasses import dataclass, field | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class Message: | ||
| """One delivered message. ``recipient`` is a mailbox name or a chat channel; | ||
| the empty string is a mailbox broadcast.""" | ||
|
|
||
| id: int | ||
| sender: str | ||
| recipient: str | ||
| subject: str | ||
| body: str | ||
|
|
||
| def as_dict(self) -> dict[str, object]: | ||
| return { | ||
| "id": self.id, | ||
| "sender": self.sender, | ||
| "recipient": self.recipient, | ||
| "subject": self.subject, | ||
| "body": self.body, | ||
| } | ||
|
|
||
|
|
||
| @dataclass | ||
| class MailboxStore: | ||
| """Directed mail: ``send(to=...)`` lands in one box; a recipient of ``""`` | ||
| is a broadcast every box also reads. ``read`` takes a ``since`` cursor so a | ||
| reader only sees new mail.""" | ||
|
|
||
| _messages: list[Message] = field(default_factory=list) | ||
| _counter: int = 0 | ||
|
|
||
| def send(self, *, sender: str, to: str, subject: str = "", body: str = "") -> int: | ||
| self._counter += 1 | ||
| self._messages.append(Message(self._counter, sender, to, subject, body)) | ||
| return self._counter | ||
|
|
||
| def read(self, box: str, since: int = 0) -> list[Message]: | ||
| return [m for m in self._messages if m.id > since and m.recipient in (box, "")] | ||
|
|
||
| def all(self) -> list[Message]: | ||
| """Every message, for ``collect_extras()`` / grading.""" | ||
| return list(self._messages) | ||
|
|
||
|
|
||
| @dataclass | ||
| class ChatStore: | ||
| """Channel chat: ``post(channel=...)`` is visible to everyone who reads that | ||
| channel. ``since`` lets a reader poll only new lines.""" | ||
|
|
||
| _messages: list[Message] = field(default_factory=list) | ||
| _counter: int = 0 | ||
|
|
||
| def post(self, *, sender: str, channel: str, text: str) -> int: | ||
| self._counter += 1 | ||
| self._messages.append(Message(self._counter, sender, channel, "", text)) | ||
| return self._counter | ||
|
|
||
| def read(self, channel: str, since: int = 0) -> list[Message]: | ||
| return [m for m in self._messages if m.recipient == channel and m.id > since] | ||
|
|
||
| def all(self) -> list[Message]: | ||
| return list(self._messages) | ||
|
|
||
|
|
||
| def surface_mailbox(store: MailboxStore) -> dict[str, Callable[..., object]]: | ||
| """The identity-neutral ``mail_send`` / ``mail_read`` callables a pack merges | ||
| into ``surface_extras()``. ``sender``/``box`` are explicit because one shared | ||
| surface serves every NPC; the persona binds its own identity NPC-side.""" | ||
|
|
||
| def mail_send(sender: str, to: str, subject: str = "", body: str = "") -> str: | ||
| mid = store.send(sender=sender, to=to, subject=subject, body=body) | ||
| return f"sent#{mid}" | ||
|
|
||
| def mail_read(box: str, since: int = 0) -> list[dict[str, object]]: | ||
| return [m.as_dict() for m in store.read(box, since)] | ||
|
|
||
| return {"mail_send": mail_send, "mail_read": mail_read} | ||
|
|
||
|
|
||
| def surface_chat(store: ChatStore) -> dict[str, Callable[..., object]]: | ||
| """The identity-neutral ``chat_post`` / ``chat_read`` callables a pack merges | ||
| into ``surface_extras()``.""" | ||
|
|
||
| def chat_post(sender: str, channel: str, text: str) -> str: | ||
| mid = store.post(sender=sender, channel=channel, text=text) | ||
| return f"posted#{mid}" | ||
|
|
||
| def chat_read(channel: str, since: int = 0) -> list[dict[str, object]]: | ||
| return [m.as_dict() for m in store.read(channel, since)] | ||
|
|
||
| return {"chat_post": chat_post, "chat_read": chat_read} |
57 changes: 57 additions & 0 deletions
57
packages/openrange-pack-sdk/src/openrange_pack_sdk/memory.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| """Per-persona scoped memory for NPCs. | ||
|
|
||
| Training-free and dependency-free: ``DictMemory`` is a keyword-ranked note store. | ||
| The ``scope`` is a stable ``"{run}:{actor}"`` string INJECTED by the NPC wrapper, | ||
| never chosen by the model, so one persona can never read another persona's (or | ||
| the SUT's) notes. Ranking is deterministic (term overlap, then recency) so a | ||
| fixed seed replays identically. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import re | ||
| from dataclasses import dataclass, field | ||
|
|
||
| _WORD = re.compile(r"[a-z0-9]+") | ||
|
|
||
| # Bound a persona's note store so recall can't grow the prompt without limit. | ||
| _MAX_NOTE_CHARS = 2000 | ||
| _MAX_NOTES = 500 | ||
|
|
||
|
|
||
| def _terms(text: str) -> set[str]: | ||
| # Word tokens, so adjacent punctuation ("finance,") still matches "finance". | ||
| return set(_WORD.findall(text.lower())) | ||
|
|
||
|
|
||
| @dataclass | ||
| class DictMemory: | ||
| """In-process scoped notes with keyword-overlap retrieval. | ||
|
|
||
| Retrieval returns notes sharing at least one query term, most-overlapping | ||
| first; when nothing overlaps it falls back to the most recent notes, so a | ||
| bare ``recall`` still surfaces context. | ||
| """ | ||
|
|
||
| _items: dict[str, list[str]] = field(default_factory=dict) | ||
|
|
||
| def store(self, scope: str, content: str) -> None: | ||
| if content: | ||
| items = self._items.setdefault(scope, []) | ||
| items.append(content[:_MAX_NOTE_CHARS]) | ||
| del items[:-_MAX_NOTES] # keep only the most recent notes per scope | ||
|
|
||
| def retrieve(self, scope: str, query: str, k: int = 5) -> list[str]: | ||
| items = self._items.get(scope, []) | ||
| if not items: | ||
| return [] | ||
| q = _terms(query) | ||
| if q: | ||
| scored = sorted( | ||
| enumerate(items), | ||
| key=lambda pair: (-len(q & _terms(pair[1])), -pair[0]), | ||
| ) | ||
| hits = [c for i, c in scored if q & _terms(c)] | ||
| if hits: | ||
| return hits[:k] | ||
| return list(reversed(items))[:k] |
12 changes: 12 additions & 0 deletions
12
packages/openrange-pack-sdk/src/openrange_pack_sdk/npcs/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| """Reusable NPC implementations shared across packs.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from openrange_pack_sdk.npcs.persona_agent import ( | ||
| PersonaAgent, | ||
| factory, | ||
| render_persona, | ||
| sample_persona, | ||
| ) | ||
|
|
||
| __all__ = ["PersonaAgent", "factory", "render_persona", "sample_persona"] |
46 changes: 46 additions & 0 deletions
46
packages/openrange-pack-sdk/src/openrange_pack_sdk/npcs/metrics.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| """Deterministic, model-free metrics for a persona population: whether a sampled | ||
| population is diverse (role entropy) and whether the persona prompt reads like an | ||
| assistant rather than a character (tell rate).""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import math | ||
| import re | ||
| from collections import Counter | ||
| from collections.abc import Iterable | ||
|
|
||
| # Phrases a helpful assistant, or a model reasoning out loud, emits — an | ||
| # in-character persona should not. | ||
| _ASSISTANT_TELLS = ( | ||
| re.compile(r"\bas an ai\b"), | ||
| re.compile(r"\blanguage model\b"), | ||
| re.compile(r"\bhow (can|may) i (help|assist)\b"), | ||
| re.compile(r"\bi (cannot|can't|am unable to)\b"), | ||
| re.compile(r"\bi'?m (happy|glad) to help\b"), | ||
| re.compile(r"^#{1,6}\s", re.MULTILINE), # markdown headers | ||
| re.compile(r"\b(best regards|sincerely|kind regards)\b"), | ||
| re.compile(r"\bthe user\b"), | ||
| re.compile(r"\bact(ing)? as\b"), | ||
| re.compile(r"\b(stay|staying|stick|in) (in )?character\b"), | ||
| re.compile(r"\bmy (character|persona|role|goal is)\b"), | ||
| ) | ||
|
|
||
|
|
||
| def role_entropy(roles: Iterable[str], universe_size: int) -> float: | ||
| """Shannon entropy of a role distribution, normalized to ``[0, 1]`` against | ||
| ``universe_size`` distinct roles (1.0 == perfectly uniform over the vocab).""" | ||
| counts = Counter(r for r in roles) | ||
| total = sum(counts.values()) | ||
| if total == 0 or universe_size <= 1: | ||
| return 0.0 | ||
| h = -sum((c / total) * math.log(c / total) for c in counts.values()) | ||
| return h / math.log(universe_size) | ||
|
|
||
|
|
||
| def assistant_tell_rate(texts: Iterable[str]) -> float: | ||
| """Fraction of texts that contain at least one assistant-tell phrase.""" | ||
| items = list(texts) | ||
| if not items: | ||
| return 0.0 | ||
| hits = sum(1 for t in items if any(p.search(t.lower()) for p in _ASSISTANT_TELLS)) | ||
| return hits / len(items) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this file is not an implementation log
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pulled the CI-status and "deferred to a follow-up" paragraphs, kept the usage guidance. 11591fb