Spaces:
Runtime error
Runtime error
Commit ·
b0fbfe1
1
Parent(s): 69f2236
Simplify ChatKit backend (#104)
Browse files- chatkit/backend/app/assistant.py +0 -31
- chatkit/backend/app/memory_store.py +76 -157
- chatkit/backend/app/server.py +16 -3
chatkit/backend/app/assistant.py
DELETED
|
@@ -1,31 +0,0 @@
|
|
| 1 |
-
"""Simple streaming assistant wired to ChatKit."""
|
| 2 |
-
|
| 3 |
-
from __future__ import annotations
|
| 4 |
-
|
| 5 |
-
from typing import Any, Annotated
|
| 6 |
-
|
| 7 |
-
from agents import Agent
|
| 8 |
-
from chatkit.agents import AgentContext
|
| 9 |
-
from pydantic import ConfigDict, Field
|
| 10 |
-
from .memory_store import MemoryStore
|
| 11 |
-
|
| 12 |
-
MODEL = "gpt-4.1-mini"
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
class StarterAgentContext(AgentContext):
|
| 16 |
-
"""Minimal context passed into the ChatKit agent runner."""
|
| 17 |
-
|
| 18 |
-
model_config = ConfigDict(arbitrary_types_allowed=True)
|
| 19 |
-
request_context: dict[str, Any]
|
| 20 |
-
# The store is excluded so it isn't serialized into prompts.
|
| 21 |
-
store: Annotated[MemoryStore, Field(exclude=True)]
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
assistant_agent = Agent[StarterAgentContext](
|
| 25 |
-
model=MODEL,
|
| 26 |
-
name="Starter Assistant",
|
| 27 |
-
instructions=(
|
| 28 |
-
"You are a concise, helpful assistant. "
|
| 29 |
-
"Keep replies short and focus on directly answering the user's request."
|
| 30 |
-
),
|
| 31 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
chatkit/backend/app/memory_store.py
CHANGED
|
@@ -1,196 +1,115 @@
|
|
| 1 |
"""
|
| 2 |
Simple in-memory store compatible with the ChatKit Store interface.
|
|
|
|
| 3 |
"""
|
| 4 |
|
| 5 |
from __future__ import annotations
|
| 6 |
|
| 7 |
-
from
|
| 8 |
-
from datetime import datetime
|
| 9 |
-
from typing import Any, Dict, List
|
| 10 |
|
| 11 |
from chatkit.store import NotFoundError, Store
|
| 12 |
-
from chatkit.types import Attachment, Page,
|
| 13 |
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
"""Simple in-memory store compatible with the ChatKit Store interface."""
|
| 23 |
-
|
| 24 |
-
def __init__(self) -> None:
|
| 25 |
-
self._threads: Dict[str, _ThreadState] = {}
|
| 26 |
-
# Attachments intentionally unsupported; use a real store that enforces auth.
|
| 27 |
-
|
| 28 |
-
@staticmethod
|
| 29 |
-
def _coerce_thread_metadata(thread: ThreadMetadata | Thread) -> ThreadMetadata:
|
| 30 |
-
"""Return thread metadata without any embedded items."""
|
| 31 |
-
has_items = isinstance(thread, Thread) or "items" in getattr(
|
| 32 |
-
thread, "model_fields_set", set()
|
| 33 |
-
)
|
| 34 |
-
if not has_items:
|
| 35 |
-
return thread.model_copy(deep=True)
|
| 36 |
-
|
| 37 |
-
data = thread.model_dump()
|
| 38 |
-
data.pop("items", None)
|
| 39 |
-
return ThreadMetadata(**data).model_copy(deep=True)
|
| 40 |
-
|
| 41 |
-
# -- Thread metadata -------------------------------------------------
|
| 42 |
-
async def load_thread(
|
| 43 |
-
self, thread_id: str, context: dict[str, Any]
|
| 44 |
-
) -> ThreadMetadata:
|
| 45 |
-
state = self._threads.get(thread_id)
|
| 46 |
-
if not state:
|
| 47 |
raise NotFoundError(f"Thread {thread_id} not found")
|
| 48 |
-
return self.
|
| 49 |
|
| 50 |
-
async def save_thread(
|
| 51 |
-
self
|
| 52 |
-
) -> None:
|
| 53 |
-
metadata = self._coerce_thread_metadata(thread)
|
| 54 |
-
state = self._threads.get(thread.id)
|
| 55 |
-
if state:
|
| 56 |
-
state.thread = metadata
|
| 57 |
-
else:
|
| 58 |
-
self._threads[thread.id] = _ThreadState(
|
| 59 |
-
thread=metadata,
|
| 60 |
-
items=[],
|
| 61 |
-
)
|
| 62 |
|
| 63 |
async def load_threads(
|
| 64 |
-
self,
|
| 65 |
-
limit: int,
|
| 66 |
-
after: str | None,
|
| 67 |
-
order: str,
|
| 68 |
-
context: dict[str, Any],
|
| 69 |
) -> Page[ThreadMetadata]:
|
| 70 |
-
threads =
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
|
|
|
| 77 |
)
|
| 78 |
|
| 79 |
-
if after:
|
| 80 |
-
index_map = {thread.id: idx for idx, thread in enumerate(threads)}
|
| 81 |
-
start = index_map.get(after, -1) + 1
|
| 82 |
-
else:
|
| 83 |
-
start = 0
|
| 84 |
-
|
| 85 |
-
slice_threads = threads[start : start + limit + 1]
|
| 86 |
-
has_more = len(slice_threads) > limit
|
| 87 |
-
slice_threads = slice_threads[:limit]
|
| 88 |
-
next_after = slice_threads[-1].id if has_more and slice_threads else None
|
| 89 |
-
return Page(
|
| 90 |
-
data=slice_threads,
|
| 91 |
-
has_more=has_more,
|
| 92 |
-
after=next_after,
|
| 93 |
-
)
|
| 94 |
-
|
| 95 |
-
async def delete_thread(self, thread_id: str, context: dict[str, Any]) -> None:
|
| 96 |
-
self._threads.pop(thread_id, None)
|
| 97 |
-
|
| 98 |
-
# -- Thread items ----------------------------------------------------
|
| 99 |
-
def _thread_state(self, thread_id: str) -> _ThreadState:
|
| 100 |
-
state = self._threads.get(thread_id)
|
| 101 |
-
if state is None:
|
| 102 |
-
state = _ThreadState(
|
| 103 |
-
thread=ThreadMetadata(id=thread_id, created_at=datetime.utcnow()),
|
| 104 |
-
items=[],
|
| 105 |
-
)
|
| 106 |
-
self._threads[thread_id] = state
|
| 107 |
-
return state
|
| 108 |
-
|
| 109 |
-
def _items(self, thread_id: str) -> List[ThreadItem]:
|
| 110 |
-
state = self._thread_state(thread_id)
|
| 111 |
-
return state.items
|
| 112 |
-
|
| 113 |
async def load_thread_items(
|
| 114 |
-
self,
|
| 115 |
-
thread_id: str,
|
| 116 |
-
after: str | None,
|
| 117 |
-
limit: int,
|
| 118 |
-
order: str,
|
| 119 |
-
context: dict[str, Any],
|
| 120 |
) -> Page[ThreadItem]:
|
| 121 |
-
items =
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
)
|
| 126 |
|
| 127 |
-
if after:
|
| 128 |
-
index_map = {item.id: idx for idx, item in enumerate(items)}
|
| 129 |
-
start = index_map.get(after, -1) + 1
|
| 130 |
-
else:
|
| 131 |
-
start = 0
|
| 132 |
-
|
| 133 |
-
slice_items = items[start : start + limit + 1]
|
| 134 |
-
has_more = len(slice_items) > limit
|
| 135 |
-
slice_items = slice_items[:limit]
|
| 136 |
-
next_after = slice_items[-1].id if has_more and slice_items else None
|
| 137 |
-
return Page(data=slice_items, has_more=has_more, after=next_after)
|
| 138 |
-
|
| 139 |
async def add_thread_item(
|
| 140 |
-
self, thread_id: str, item: ThreadItem, context: dict
|
| 141 |
) -> None:
|
| 142 |
-
self.
|
| 143 |
|
| 144 |
-
async def save_item(
|
| 145 |
-
|
| 146 |
-
) -> None:
|
| 147 |
-
items = self._items(thread_id)
|
| 148 |
for idx, existing in enumerate(items):
|
| 149 |
if existing.id == item.id:
|
| 150 |
-
items[idx] = item
|
| 151 |
return
|
| 152 |
-
items.append(item
|
| 153 |
|
| 154 |
async def load_item(
|
| 155 |
-
self, thread_id: str, item_id: str, context: dict
|
| 156 |
) -> ThreadItem:
|
| 157 |
-
for item in self.
|
| 158 |
if item.id == item_id:
|
| 159 |
-
return item
|
| 160 |
-
raise NotFoundError(f"Item {item_id} not found")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
async def delete_thread_item(
|
| 163 |
-
self, thread_id: str, item_id: str, context: dict
|
| 164 |
) -> None:
|
| 165 |
-
items =
|
| 166 |
-
|
|
|
|
| 167 |
|
| 168 |
-
|
| 169 |
-
# These methods are not currently used but required to be compatible with the Store interface.
|
| 170 |
-
|
| 171 |
-
async def save_attachment(
|
| 172 |
self,
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
-
|
| 182 |
-
self,
|
| 183 |
-
attachment_id: str,
|
| 184 |
-
context: dict[str, Any],
|
| 185 |
-
) -> Attachment:
|
| 186 |
-
raise NotImplementedError(
|
| 187 |
-
"MemoryStore does not load attachments. Provide a Store implementation "
|
| 188 |
-
"that enforces authentication and authorization before enabling uploads."
|
| 189 |
-
)
|
| 190 |
|
| 191 |
-
async def
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
|
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
Simple in-memory store compatible with the ChatKit Store interface.
|
| 3 |
+
A production app would implement this using a persistant database.
|
| 4 |
"""
|
| 5 |
|
| 6 |
from __future__ import annotations
|
| 7 |
|
| 8 |
+
from collections import defaultdict
|
|
|
|
|
|
|
| 9 |
|
| 10 |
from chatkit.store import NotFoundError, Store
|
| 11 |
+
from chatkit.types import Attachment, Page, ThreadItem, ThreadMetadata
|
| 12 |
|
| 13 |
|
| 14 |
+
class MemoryStore(Store[dict]):
|
| 15 |
+
def __init__(self):
|
| 16 |
+
self.threads: dict[str, ThreadMetadata] = {}
|
| 17 |
+
self.items: dict[str, list[ThreadItem]] = defaultdict(list)
|
| 18 |
|
| 19 |
+
async def load_thread(self, thread_id: str, context: dict) -> ThreadMetadata:
|
| 20 |
+
if thread_id not in self.threads:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
raise NotFoundError(f"Thread {thread_id} not found")
|
| 22 |
+
return self.threads[thread_id]
|
| 23 |
|
| 24 |
+
async def save_thread(self, thread: ThreadMetadata, context: dict) -> None:
|
| 25 |
+
self.threads[thread.id] = thread
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
async def load_threads(
|
| 28 |
+
self, limit: int, after: str | None, order: str, context: dict
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
) -> Page[ThreadMetadata]:
|
| 30 |
+
threads = list(self.threads.values())
|
| 31 |
+
return self._paginate(
|
| 32 |
+
threads,
|
| 33 |
+
after,
|
| 34 |
+
limit,
|
| 35 |
+
order,
|
| 36 |
+
sort_key=lambda t: t.created_at,
|
| 37 |
+
cursor_key=lambda t: t.id,
|
| 38 |
)
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
async def load_thread_items(
|
| 41 |
+
self, thread_id: str, after: str | None, limit: int, order: str, context: dict
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
) -> Page[ThreadItem]:
|
| 43 |
+
items = self.items.get(thread_id, [])
|
| 44 |
+
return self._paginate(
|
| 45 |
+
items,
|
| 46 |
+
after,
|
| 47 |
+
limit,
|
| 48 |
+
order,
|
| 49 |
+
sort_key=lambda i: i.created_at,
|
| 50 |
+
cursor_key=lambda i: i.id,
|
| 51 |
)
|
| 52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
async def add_thread_item(
|
| 54 |
+
self, thread_id: str, item: ThreadItem, context: dict
|
| 55 |
) -> None:
|
| 56 |
+
self.items[thread_id].append(item)
|
| 57 |
|
| 58 |
+
async def save_item(self, thread_id: str, item: ThreadItem, context: dict) -> None:
|
| 59 |
+
items = self.items[thread_id]
|
|
|
|
|
|
|
| 60 |
for idx, existing in enumerate(items):
|
| 61 |
if existing.id == item.id:
|
| 62 |
+
items[idx] = item
|
| 63 |
return
|
| 64 |
+
items.append(item)
|
| 65 |
|
| 66 |
async def load_item(
|
| 67 |
+
self, thread_id: str, item_id: str, context: dict
|
| 68 |
) -> ThreadItem:
|
| 69 |
+
for item in self.items.get(thread_id, []):
|
| 70 |
if item.id == item_id:
|
| 71 |
+
return item
|
| 72 |
+
raise NotFoundError(f"Item {item_id} not found in thread {thread_id}")
|
| 73 |
+
|
| 74 |
+
async def delete_thread(self, thread_id: str, context: dict) -> None:
|
| 75 |
+
self.threads.pop(thread_id, None)
|
| 76 |
+
self.items.pop(thread_id, None)
|
| 77 |
|
| 78 |
async def delete_thread_item(
|
| 79 |
+
self, thread_id: str, item_id: str, context: dict
|
| 80 |
) -> None:
|
| 81 |
+
self.items[thread_id] = [
|
| 82 |
+
item for item in self.items.get(thread_id, []) if item.id != item_id
|
| 83 |
+
]
|
| 84 |
|
| 85 |
+
def _paginate(
|
|
|
|
|
|
|
|
|
|
| 86 |
self,
|
| 87 |
+
rows: list,
|
| 88 |
+
after: str | None,
|
| 89 |
+
limit: int,
|
| 90 |
+
order: str,
|
| 91 |
+
sort_key,
|
| 92 |
+
cursor_key,
|
| 93 |
+
):
|
| 94 |
+
sorted_rows = sorted(rows, key=sort_key, reverse=order == "desc")
|
| 95 |
+
start = 0
|
| 96 |
+
if after:
|
| 97 |
+
for idx, row in enumerate(sorted_rows):
|
| 98 |
+
if cursor_key(row) == after:
|
| 99 |
+
start = idx + 1
|
| 100 |
+
break
|
| 101 |
+
data = sorted_rows[start : start + limit]
|
| 102 |
+
has_more = start + limit < len(sorted_rows)
|
| 103 |
+
next_after = cursor_key(data[-1]) if has_more and data else None
|
| 104 |
+
return Page(data=data, has_more=has_more, after=next_after)
|
| 105 |
|
| 106 |
+
# Attachments are not implemented in the quickstart store
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
+
async def save_attachment(self, attachment: Attachment, context: dict) -> None:
|
| 109 |
+
raise NotImplementedError()
|
| 110 |
+
|
| 111 |
+
async def load_attachment(self, attachment_id: str, context: dict) -> Attachment:
|
| 112 |
+
raise NotImplementedError()
|
| 113 |
+
|
| 114 |
+
async def delete_attachment(self, attachment_id: str, context: dict) -> None:
|
| 115 |
+
raise NotImplementedError()
|
chatkit/backend/app/server.py
CHANGED
|
@@ -5,14 +5,27 @@ from __future__ import annotations
|
|
| 5 |
from typing import Any, AsyncIterator
|
| 6 |
|
| 7 |
from agents import Runner
|
| 8 |
-
from chatkit.agents import simple_to_agent_input, stream_agent_response
|
| 9 |
from chatkit.server import ChatKitServer
|
| 10 |
from chatkit.types import ThreadMetadata, ThreadStreamEvent, UserMessageItem
|
| 11 |
|
| 12 |
-
from .assistant import StarterAgentContext, assistant_agent
|
| 13 |
from .memory_store import MemoryStore
|
|
|
|
|
|
|
| 14 |
|
| 15 |
MAX_RECENT_ITEMS = 30
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
|
| 18 |
class StarterChatServer(ChatKitServer[dict[str, Any]]):
|
|
@@ -38,7 +51,7 @@ class StarterChatServer(ChatKitServer[dict[str, Any]]):
|
|
| 38 |
items = list(reversed(items_page.data))
|
| 39 |
agent_input = await simple_to_agent_input(items)
|
| 40 |
|
| 41 |
-
agent_context =
|
| 42 |
thread=thread,
|
| 43 |
store=self.store,
|
| 44 |
request_context=context,
|
|
|
|
| 5 |
from typing import Any, AsyncIterator
|
| 6 |
|
| 7 |
from agents import Runner
|
| 8 |
+
from chatkit.agents import AgentContext, simple_to_agent_input, stream_agent_response
|
| 9 |
from chatkit.server import ChatKitServer
|
| 10 |
from chatkit.types import ThreadMetadata, ThreadStreamEvent, UserMessageItem
|
| 11 |
|
|
|
|
| 12 |
from .memory_store import MemoryStore
|
| 13 |
+
from agents import Agent
|
| 14 |
+
|
| 15 |
|
| 16 |
MAX_RECENT_ITEMS = 30
|
| 17 |
+
MODEL = "gpt-4.1-mini"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
assistant_agent = Agent[AgentContext[dict[str, Any]]](
|
| 21 |
+
model=MODEL,
|
| 22 |
+
name="Starter Assistant",
|
| 23 |
+
instructions=(
|
| 24 |
+
"You are a concise, helpful assistant. "
|
| 25 |
+
"Keep replies short and focus on directly answering "
|
| 26 |
+
"the user's request."
|
| 27 |
+
),
|
| 28 |
+
)
|
| 29 |
|
| 30 |
|
| 31 |
class StarterChatServer(ChatKitServer[dict[str, Any]]):
|
|
|
|
| 51 |
items = list(reversed(items_page.data))
|
| 52 |
agent_input = await simple_to_agent_input(items)
|
| 53 |
|
| 54 |
+
agent_context = AgentContext(
|
| 55 |
thread=thread,
|
| 56 |
store=self.store,
|
| 57 |
request_context=context,
|