-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathhttp_server.py
More file actions
81 lines (64 loc) · 2.36 KB
/
Copy pathhttp_server.py
File metadata and controls
81 lines (64 loc) · 2.36 KB
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
# /// script
# requires-python = ">=3.10,<3.15"
# dependencies = [
# "agent-client-protocol[http]",
# "hypercorn>=0.17",
# ]
# ///
"""Serve an ACP agent over Streamable HTTP + WebSocket (experimental).
Run with an HTTP/2-capable ASGI server for spec-compliant Streamable HTTP. This
example uses Hypercorn; Uvicorn works for WebSocket but does not serve HTTP/2.
uv run examples/http_server.py
# then, in another terminal:
uv run examples/http_client.py
uv run examples/ws_client.py
"""
import asyncio
from typing import Any
from uuid import uuid4
from acp import (
Agent,
InitializeResponse,
NewSessionResponse,
PromptResponse,
text_block,
update_agent_message,
)
from acp.http.asgi import create_asgi_app
from acp.interfaces import Client
from acp.schema import ClientCapabilities, Implementation
class EchoAgent(Agent):
_conn: Client
def on_connect(self, conn: Client) -> None:
self._conn = conn
async def initialize(
self,
protocol_version: int,
client_capabilities: ClientCapabilities | None = None,
client_info: Implementation | None = None,
**kwargs: Any,
) -> InitializeResponse:
return InitializeResponse(protocol_version=protocol_version)
async def new_session(self, cwd: str = "", **kwargs: Any) -> NewSessionResponse:
return NewSessionResponse(session_id=uuid4().hex)
async def prompt(self, session_id: str, prompt: list[Any], **kwargs: Any) -> PromptResponse:
for block in prompt:
text = block.get("text", "") if isinstance(block, dict) else getattr(block, "text", "")
await self._conn.session_update(
session_id=session_id,
update=update_agent_message(text_block(f"echo: {text}")),
)
return PromptResponse(stop_reason="end_turn")
# One agent instance per connection.
app = create_asgi_app(lambda conn: EchoAgent())
async def main() -> None:
import hypercorn.asyncio
from hypercorn.config import Config
config = Config()
config.bind = ["localhost:8000"]
# Enable HTTP/2 (Streamable HTTP requires it). Hypercorn negotiates h2c/h2.
config.alpn_protocols = ["h2", "http/1.1"]
print("Serving ACP agent on http://localhost:8000/acp (HTTP + WS)")
await hypercorn.asyncio.serve(app, config)
if __name__ == "__main__":
asyncio.run(main())