fast-chat-server 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fast_chat_server/__init__.py +26 -0
- fast_chat_server/agents/__init__.py +23 -0
- fast_chat_server/agents/agent.py +145 -0
- fast_chat_server/agents/api.py +31 -0
- fast_chat_server/agents/context.py +105 -0
- fast_chat_server/agents/history.py +53 -0
- fast_chat_server/agents/runtime.py +734 -0
- fast_chat_server/agents/triggers.py +120 -0
- fast_chat_server/api/__init__.py +0 -0
- fast_chat_server/api/admin.py +152 -0
- fast_chat_server/api/client/__init__.py +0 -0
- fast_chat_server/api/client/auth.py +157 -0
- fast_chat_server/api/client/misc.py +231 -0
- fast_chat_server/api/client/rooms.py +457 -0
- fast_chat_server/api/client/spaces.py +31 -0
- fast_chat_server/api/client/sync.py +75 -0
- fast_chat_server/api/client/versions.py +14 -0
- fast_chat_server/api/deps.py +83 -0
- fast_chat_server/api/fcs.py +33 -0
- fast_chat_server/api/federation/__init__.py +0 -0
- fast_chat_server/api/federation/server.py +392 -0
- fast_chat_server/api/federation/version.py +14 -0
- fast_chat_server/api/keys.py +16 -0
- fast_chat_server/api/media.py +106 -0
- fast_chat_server/api/metrics.py +41 -0
- fast_chat_server/api/well_known.py +21 -0
- fast_chat_server/app.py +464 -0
- fast_chat_server/bus/__init__.py +13 -0
- fast_chat_server/bus/base.py +43 -0
- fast_chat_server/bus/factory.py +30 -0
- fast_chat_server/bus/memory.py +74 -0
- fast_chat_server/bus/redis.py +73 -0
- fast_chat_server/cli.py +142 -0
- fast_chat_server/core/__init__.py +1 -0
- fast_chat_server/core/auth_rules.py +374 -0
- fast_chat_server/core/canonical_json.py +58 -0
- fast_chat_server/core/encoding.py +25 -0
- fast_chat_server/core/hashing.py +80 -0
- fast_chat_server/core/ids.py +147 -0
- fast_chat_server/core/redaction.py +102 -0
- fast_chat_server/core/redirects.py +70 -0
- fast_chat_server/core/room_versions.py +98 -0
- fast_chat_server/core/signing.py +149 -0
- fast_chat_server/core/state_res.py +217 -0
- fast_chat_server/errors.py +102 -0
- fast_chat_server/federation/__init__.py +1 -0
- fast_chat_server/federation/auth.py +82 -0
- fast_chat_server/federation/backfill.py +318 -0
- fast_chat_server/federation/client.py +173 -0
- fast_chat_server/federation/inbound.py +477 -0
- fast_chat_server/federation/keyring.py +205 -0
- fast_chat_server/federation/membership.py +450 -0
- fast_chat_server/federation/outbound.py +329 -0
- fast_chat_server/federation/service.py +37 -0
- fast_chat_server/observability.py +398 -0
- fast_chat_server/py.typed +0 -0
- fast_chat_server/services/__init__.py +1 -0
- fast_chat_server/services/admin.py +559 -0
- fast_chat_server/services/auth.py +405 -0
- fast_chat_server/services/ephemeral.py +168 -0
- fast_chat_server/services/events.py +570 -0
- fast_chat_server/services/media.py +128 -0
- fast_chat_server/services/notifier.py +90 -0
- fast_chat_server/services/rooms.py +551 -0
- fast_chat_server/services/serialize.py +111 -0
- fast_chat_server/services/spaces.py +208 -0
- fast_chat_server/services/sso.py +212 -0
- fast_chat_server/services/state.py +168 -0
- fast_chat_server/services/sync.py +596 -0
- fast_chat_server/services/util.py +38 -0
- fast_chat_server/settings.py +204 -0
- fast_chat_server/storage/__init__.py +3 -0
- fast_chat_server/storage/database.py +94 -0
- fast_chat_server/storage/migrate.py +52 -0
- fast_chat_server/storage/migrations/__init__.py +0 -0
- fast_chat_server/storage/migrations/env.py +48 -0
- fast_chat_server/storage/migrations/script.py.mako +25 -0
- fast_chat_server/storage/migrations/versions/0001_initial_schema.py +269 -0
- fast_chat_server/storage/migrations/versions/0002_phase_1_tables.py +132 -0
- fast_chat_server/storage/migrations/versions/0003_agent_runs.py +78 -0
- fast_chat_server/storage/migrations/versions/0004_federation_and_state_groups.py +84 -0
- fast_chat_server/storage/migrations/versions/0005_admin_api.py +59 -0
- fast_chat_server/storage/migrations/versions/0006_agent_run_active_time.py +28 -0
- fast_chat_server/storage/migrations/versions/0007_forgotten_rooms.py +31 -0
- fast_chat_server/storage/models.py +443 -0
- fast_chat_server/storage/streams.py +44 -0
- fast_chat_server/testing/__init__.py +1 -0
- fast_chat_server/testing/harness.py +303 -0
- fast_chat_server/testing/mock_oidc.py +159 -0
- fast_chat_server-0.1.0.dist-info/METADATA +400 -0
- fast_chat_server-0.1.0.dist-info/RECORD +94 -0
- fast_chat_server-0.1.0.dist-info/WHEEL +4 -0
- fast_chat_server-0.1.0.dist-info/entry_points.txt +2 -0
- fast_chat_server-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""fast-chat-server: a Matrix homeserver as a mountable FastAPI sub-application."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Any
|
|
6
|
+
|
|
7
|
+
__version__ = "0.1.0"
|
|
8
|
+
|
|
9
|
+
__all__ = ["MatrixServer", "Settings", "__version__"]
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from fast_chat_server.app import MatrixServer
|
|
13
|
+
from fast_chat_server.settings import Settings
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def __getattr__(name: str) -> Any:
|
|
17
|
+
# Lazy so that `fast_chat_server.core` can be imported without FastAPI/SQLAlchemy.
|
|
18
|
+
if name == "MatrixServer":
|
|
19
|
+
from fast_chat_server.app import MatrixServer
|
|
20
|
+
|
|
21
|
+
return MatrixServer
|
|
22
|
+
if name == "Settings":
|
|
23
|
+
from fast_chat_server.settings import Settings
|
|
24
|
+
|
|
25
|
+
return Settings
|
|
26
|
+
raise AttributeError(name)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""LLM agents as Matrix users, built on Pydantic AI (``pip install 'fast-chat-server[agents]'``).
|
|
2
|
+
|
|
3
|
+
from fast_chat_server.agents import MatrixAgent, AgentContext, on
|
|
4
|
+
|
|
5
|
+
helpdesk = MatrixAgent(
|
|
6
|
+
localpart="helpdesk",
|
|
7
|
+
model="anthropic:claude-sonnet-5-5",
|
|
8
|
+
instructions="You are the IT helpdesk.",
|
|
9
|
+
triggers=[on.mention(), on.direct_message(), on.command("!ticket")],
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
@helpdesk.tool
|
|
13
|
+
async def lookup_ticket(ctx: RunContext[AgentContext[None]], ticket_id: int) -> str:
|
|
14
|
+
...
|
|
15
|
+
|
|
16
|
+
matrix.agents.register(helpdesk)
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from fast_chat_server.agents.agent import MatrixAgent
|
|
20
|
+
from fast_chat_server.agents.context import AgentContext, RoomHandle
|
|
21
|
+
from fast_chat_server.agents.triggers import Trigger, TriggerInput, on
|
|
22
|
+
|
|
23
|
+
__all__ = ["AgentContext", "MatrixAgent", "RoomHandle", "Trigger", "TriggerInput", "on"]
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""``MatrixAgent``: a Matrix user backed by a Pydantic AI agent."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
from collections.abc import Awaitable, Callable, Sequence
|
|
7
|
+
from typing import Any, Generic, Literal
|
|
8
|
+
|
|
9
|
+
from pydantic_ai import Agent
|
|
10
|
+
from pydantic_ai.usage import UsageLimits
|
|
11
|
+
|
|
12
|
+
from fast_chat_server.agents.context import AgentContext, AppDepsT
|
|
13
|
+
from fast_chat_server.agents.triggers import Trigger, on
|
|
14
|
+
from fast_chat_server.core.ids import UserID
|
|
15
|
+
|
|
16
|
+
ReplyMode = Literal["auto", "thread", "reply", "message"]
|
|
17
|
+
DepsFactory = Callable[[AgentContext[Any]], "AppDepsT | Awaitable[AppDepsT]"]
|
|
18
|
+
RoomFilter = Sequence[str] | Callable[[str], bool] | None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class MatrixAgent(Generic[AppDepsT]):
|
|
22
|
+
"""An LLM agent that lives in Matrix rooms as ``@<localpart>:<server_name>``.
|
|
23
|
+
|
|
24
|
+
It wraps (and exposes as ``.agent``) a ``pydantic_ai.Agent`` whose deps are an
|
|
25
|
+
:class:`AgentContext`. Define tools with ``@my_agent.tool``; pass
|
|
26
|
+
``requires_approval=True`` for tools a human must approve in the room first.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
localpart: the agent's user ID local part (``helpdesk`` → ``@helpdesk:server``).
|
|
30
|
+
model: any Pydantic AI model name (e.g. ``"anthropic:claude-sonnet-5-5"``) or Model.
|
|
31
|
+
instructions: system instructions for the model.
|
|
32
|
+
triggers: when to respond (default: mentions and direct messages).
|
|
33
|
+
deps_factory: builds your app dependencies for each run; available as
|
|
34
|
+
``ctx.deps.app`` in tools. May be async.
|
|
35
|
+
history_limit: how many earlier messages to give the model as context.
|
|
36
|
+
reply_mode: ``"thread"``, ``"reply"``, ``"message"`` or ``"auto"`` (threads
|
|
37
|
+
in group rooms, plain messages in direct messages).
|
|
38
|
+
allowed_rooms: room IDs (or a predicate) the agent may respond in.
|
|
39
|
+
trust_remote_users: respond to users from other (federated) servers (and
|
|
40
|
+
accept their invites and approvals).
|
|
41
|
+
auto_join: join rooms the agent is invited to (when the room is allowed and
|
|
42
|
+
the inviter trusted).
|
|
43
|
+
approval_power_level: power level needed to approve tool calls.
|
|
44
|
+
max_runs_per_minute: per room; extra triggers are ignored.
|
|
45
|
+
usage_limits: Pydantic AI usage limits for each run (tokens, requests).
|
|
46
|
+
agent: adopt an existing ``pydantic_ai.Agent`` instead of creating one.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
*,
|
|
52
|
+
localpart: str,
|
|
53
|
+
model: Any = None,
|
|
54
|
+
instructions: str | None = None,
|
|
55
|
+
display_name: str | None = None,
|
|
56
|
+
description: str = "",
|
|
57
|
+
avatar_url: str | None = None,
|
|
58
|
+
triggers: Sequence[Trigger] | None = None,
|
|
59
|
+
deps_factory: DepsFactory[AppDepsT] | None = None,
|
|
60
|
+
history_limit: int = 30,
|
|
61
|
+
reply_mode: ReplyMode = "auto",
|
|
62
|
+
allowed_rooms: RoomFilter = None,
|
|
63
|
+
trust_remote_users: bool = False,
|
|
64
|
+
approval_power_level: int = 50,
|
|
65
|
+
auto_join: bool = True,
|
|
66
|
+
max_runs_per_minute: int = 20,
|
|
67
|
+
usage_limits: UsageLimits | None = None,
|
|
68
|
+
agent: Agent[AgentContext[AppDepsT], str] | None = None,
|
|
69
|
+
**agent_kwargs: Any,
|
|
70
|
+
) -> None:
|
|
71
|
+
UserID.parse(f"@{localpart}:example.org", strict=True)
|
|
72
|
+
self.localpart = localpart
|
|
73
|
+
self.display_name = display_name or localpart
|
|
74
|
+
self.description = description
|
|
75
|
+
self.avatar_url = avatar_url
|
|
76
|
+
self.triggers: list[Trigger] = list(triggers or [on.mention(), on.direct_message()])
|
|
77
|
+
self.deps_factory = deps_factory
|
|
78
|
+
self.history_limit = history_limit
|
|
79
|
+
self.reply_mode: ReplyMode = reply_mode
|
|
80
|
+
self.allowed_rooms = allowed_rooms
|
|
81
|
+
self.trust_remote_users = trust_remote_users
|
|
82
|
+
self.approval_power_level = approval_power_level
|
|
83
|
+
self.auto_join = auto_join
|
|
84
|
+
self.max_runs_per_minute = max_runs_per_minute
|
|
85
|
+
self.usage_limits = usage_limits
|
|
86
|
+
self.user_id: str | None = None # set when registered with a server
|
|
87
|
+
if agent is None:
|
|
88
|
+
agent = Agent(
|
|
89
|
+
model,
|
|
90
|
+
instructions=instructions,
|
|
91
|
+
deps_type=AgentContext,
|
|
92
|
+
name=localpart,
|
|
93
|
+
defer_model_check=True,
|
|
94
|
+
**agent_kwargs,
|
|
95
|
+
)
|
|
96
|
+
self.agent: Agent[AgentContext[AppDepsT], str] = agent
|
|
97
|
+
|
|
98
|
+
@classmethod
|
|
99
|
+
def from_agent(
|
|
100
|
+
cls, agent: Agent[Any, Any], *, localpart: str, **kwargs: Any
|
|
101
|
+
) -> MatrixAgent[Any]:
|
|
102
|
+
"""Put an existing Pydantic AI agent (with its tools) into Matrix."""
|
|
103
|
+
return cls(localpart=localpart, agent=agent, **kwargs)
|
|
104
|
+
|
|
105
|
+
# Tool decorators delegate to the wrapped agent, so the full Pydantic AI API applies.
|
|
106
|
+
def tool(self, func: Any = None, /, **kwargs: Any) -> Any:
|
|
107
|
+
return self.agent.tool(func, **kwargs) if func is not None else self.agent.tool(**kwargs)
|
|
108
|
+
|
|
109
|
+
def tool_plain(self, func: Any = None, /, **kwargs: Any) -> Any:
|
|
110
|
+
if func is not None:
|
|
111
|
+
return self.agent.tool_plain(func, **kwargs)
|
|
112
|
+
return self.agent.tool_plain(**kwargs)
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def model_name(self) -> str | None:
|
|
116
|
+
model = self.agent.model
|
|
117
|
+
if model is None:
|
|
118
|
+
return None
|
|
119
|
+
return str(getattr(model, "model_name", model))
|
|
120
|
+
|
|
121
|
+
def room_allowed(self, room_id: str) -> bool:
|
|
122
|
+
if self.allowed_rooms is None:
|
|
123
|
+
return True
|
|
124
|
+
if callable(self.allowed_rooms):
|
|
125
|
+
return bool(self.allowed_rooms(room_id))
|
|
126
|
+
return room_id in self.allowed_rooms
|
|
127
|
+
|
|
128
|
+
async def build_app_deps(self, ctx: AgentContext[Any]) -> Any:
|
|
129
|
+
if self.deps_factory is None:
|
|
130
|
+
return None
|
|
131
|
+
value = self.deps_factory(ctx)
|
|
132
|
+
return await value if inspect.isawaitable(value) else value
|
|
133
|
+
|
|
134
|
+
def tools_summary(self) -> list[dict[str, Any]]:
|
|
135
|
+
tools = []
|
|
136
|
+
for toolset in self.agent.toolsets:
|
|
137
|
+
for name, tool in getattr(toolset, "tools", {}).items():
|
|
138
|
+
tools.append(
|
|
139
|
+
{
|
|
140
|
+
"name": name,
|
|
141
|
+
"description": getattr(tool, "description", None),
|
|
142
|
+
"requires_approval": bool(getattr(tool, "requires_approval", False)),
|
|
143
|
+
}
|
|
144
|
+
)
|
|
145
|
+
return tools
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""``GET /_fcs/v1/agents``: the agent catalogue for frontends."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from fastapi import APIRouter
|
|
8
|
+
|
|
9
|
+
from fast_chat_server.api.deps import Auth, Server
|
|
10
|
+
|
|
11
|
+
router = APIRouter()
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@router.get("/agents")
|
|
15
|
+
async def list_agents(server: Server, requester: Auth) -> dict[str, Any]:
|
|
16
|
+
agents = []
|
|
17
|
+
for user_id, agent in server.agents.agents.items():
|
|
18
|
+
agents.append(
|
|
19
|
+
{
|
|
20
|
+
"user_id": user_id,
|
|
21
|
+
"display_name": agent.display_name,
|
|
22
|
+
"description": agent.description,
|
|
23
|
+
"avatar_url": agent.avatar_url,
|
|
24
|
+
"model": agent.model_name,
|
|
25
|
+
"triggers": [t.description for t in agent.triggers],
|
|
26
|
+
"commands": [t.prefix for t in agent.triggers if hasattr(t, "prefix")],
|
|
27
|
+
"tools": agent.tools_summary(),
|
|
28
|
+
"reply_mode": agent.reply_mode,
|
|
29
|
+
}
|
|
30
|
+
)
|
|
31
|
+
return {"agents": agents}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""What agent tools see: ``ctx.deps`` is an :class:`AgentContext`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import TYPE_CHECKING, Any, Generic, TypeVar
|
|
7
|
+
|
|
8
|
+
from sqlalchemy import select
|
|
9
|
+
|
|
10
|
+
from fast_chat_server.services.serialize import EventSerializer
|
|
11
|
+
from fast_chat_server.storage.models import Event
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from fast_chat_server.agents.agent import MatrixAgent
|
|
15
|
+
from fast_chat_server.app import MatrixServer
|
|
16
|
+
|
|
17
|
+
AppDepsT = TypeVar("AppDepsT")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class RoomHandle:
|
|
21
|
+
"""A narrow API for acting in one room as the agent's user."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, server: MatrixServer, room_id: str, user_id: str) -> None:
|
|
24
|
+
self.server = server
|
|
25
|
+
self.room_id = room_id
|
|
26
|
+
self.user_id = user_id
|
|
27
|
+
|
|
28
|
+
async def send_event(
|
|
29
|
+
self, event_type: str, content: dict[str, Any], state_key: str | None = None
|
|
30
|
+
) -> str:
|
|
31
|
+
async with self.server.transaction() as session:
|
|
32
|
+
event = await self.server.events.create_event(
|
|
33
|
+
session,
|
|
34
|
+
room_id=self.room_id,
|
|
35
|
+
sender=self.user_id,
|
|
36
|
+
event_type=event_type,
|
|
37
|
+
content=content,
|
|
38
|
+
state_key=state_key,
|
|
39
|
+
)
|
|
40
|
+
return str(event["event_id"])
|
|
41
|
+
|
|
42
|
+
async def send_text(self, body: str, **extra: Any) -> str:
|
|
43
|
+
return await self.send_event("m.room.message", {"msgtype": "m.text", "body": body, **extra})
|
|
44
|
+
|
|
45
|
+
async def send_notice(self, body: str, **extra: Any) -> str:
|
|
46
|
+
return await self.send_event(
|
|
47
|
+
"m.room.message", {"msgtype": "m.notice", "body": body, **extra}
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
async def react(self, event_id: str, key: str) -> str:
|
|
51
|
+
return await self.send_event(
|
|
52
|
+
"m.reaction",
|
|
53
|
+
{"m.relates_to": {"rel_type": "m.annotation", "event_id": event_id, "key": key}},
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
async def state(self, event_type: str, state_key: str = "") -> dict[str, Any] | None:
|
|
57
|
+
async with self.server.db.read() as session:
|
|
58
|
+
state = await self.server.events.current_state(session, self.room_id)
|
|
59
|
+
event = state.get((event_type, state_key))
|
|
60
|
+
return dict(event["content"]) if event else None
|
|
61
|
+
|
|
62
|
+
async def members(self) -> list[str]:
|
|
63
|
+
async with self.server.db.read() as session:
|
|
64
|
+
state = await self.server.events.current_state(session, self.room_id)
|
|
65
|
+
return sorted(
|
|
66
|
+
k
|
|
67
|
+
for (t, k), e in state.items()
|
|
68
|
+
if t == "m.room.member" and e["content"].get("membership") == "join"
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
async def history(self, limit: int = 20) -> list[dict[str, Any]]:
|
|
72
|
+
"""Recent events (client format), oldest first."""
|
|
73
|
+
async with self.server.db.read() as session:
|
|
74
|
+
rows = list(
|
|
75
|
+
(
|
|
76
|
+
await session.execute(
|
|
77
|
+
select(Event)
|
|
78
|
+
.where(Event.room_id == self.room_id)
|
|
79
|
+
.order_by(Event.stream_ordering.desc())
|
|
80
|
+
.limit(limit)
|
|
81
|
+
)
|
|
82
|
+
).scalars()
|
|
83
|
+
)
|
|
84
|
+
events = await EventSerializer().serialize(session, list(reversed(rows)))
|
|
85
|
+
return events
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass
|
|
89
|
+
class AgentContext(Generic[AppDepsT]):
|
|
90
|
+
"""Passed to tools as ``ctx.deps``.
|
|
91
|
+
|
|
92
|
+
``app`` holds whatever your ``deps_factory`` returned (DB sessions, API clients, ...).
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
server: MatrixServer
|
|
96
|
+
agent: MatrixAgent[Any]
|
|
97
|
+
room: RoomHandle
|
|
98
|
+
event: dict[str, Any]
|
|
99
|
+
sender: str
|
|
100
|
+
run_id: str
|
|
101
|
+
app: AppDepsT = field(default=None) # type: ignore[assignment]
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def server_name(self) -> str:
|
|
105
|
+
return self.server.settings.server_name
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Matrix room messages → Pydantic AI message history."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping, Sequence
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from pydantic_ai.messages import ModelMessage, ModelRequest, ModelResponse, TextPart, UserPromptPart
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def message_text(event: Mapping[str, Any]) -> str | None:
|
|
12
|
+
if event.get("type") != "m.room.message":
|
|
13
|
+
return None
|
|
14
|
+
body = event.get("content", {}).get("body")
|
|
15
|
+
return body if isinstance(body, str) and body else None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def thread_root(event: Mapping[str, Any]) -> str | None:
|
|
19
|
+
relates = event.get("content", {}).get("m.relates_to")
|
|
20
|
+
if isinstance(relates, dict) and relates.get("rel_type") == "m.thread":
|
|
21
|
+
root = relates.get("event_id")
|
|
22
|
+
return root if isinstance(root, str) else None
|
|
23
|
+
return None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def to_model_messages(
|
|
27
|
+
events: Sequence[Mapping[str, Any]], agent_user_id: str, names: Mapping[str, str]
|
|
28
|
+
) -> list[ModelMessage]:
|
|
29
|
+
"""Other people's messages become user prompts ("Name: text"); the agent's own
|
|
30
|
+
messages become model responses. Consecutive messages from the same side are
|
|
31
|
+
merged, so requests and responses alternate (some providers require that)."""
|
|
32
|
+
history: list[ModelMessage] = []
|
|
33
|
+
for event in events:
|
|
34
|
+
text = message_text(event)
|
|
35
|
+
if text is None:
|
|
36
|
+
continue
|
|
37
|
+
sender = str(event.get("sender"))
|
|
38
|
+
if sender == agent_user_id:
|
|
39
|
+
part: Any = TextPart(content=text)
|
|
40
|
+
if history and isinstance(history[-1], ModelResponse):
|
|
41
|
+
history[-1] = ModelResponse(parts=[*history[-1].parts, part])
|
|
42
|
+
else:
|
|
43
|
+
history.append(ModelResponse(parts=[part]))
|
|
44
|
+
else:
|
|
45
|
+
prompt = UserPromptPart(content=f"{names.get(sender, sender)}: {text}")
|
|
46
|
+
if history and isinstance(history[-1], ModelRequest):
|
|
47
|
+
history[-1] = ModelRequest(parts=[*history[-1].parts, prompt])
|
|
48
|
+
else:
|
|
49
|
+
history.append(ModelRequest(parts=[prompt]))
|
|
50
|
+
# A conversation must start with a request.
|
|
51
|
+
while history and isinstance(history[0], ModelResponse):
|
|
52
|
+
history.pop(0)
|
|
53
|
+
return history
|