acp-sdk 0.1.0rc8__tar.gz → 0.2.0__tar.gz
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.
- acp_sdk-0.2.0/PKG-INFO +113 -0
- acp_sdk-0.2.0/README.md +91 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/examples/clients/advanced.py +3 -3
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/examples/clients/session.py +4 -4
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/examples/clients/simple.py +4 -2
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/examples/clients/stream.py +4 -2
- acp_sdk-0.2.0/examples/servers/awaiting.py +25 -0
- acp_sdk-0.2.0/examples/servers/standalone.py +25 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/pyproject.toml +4 -2
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/src/acp_sdk/client/client.py +7 -7
- acp_sdk-0.2.0/src/acp_sdk/models/models.py +170 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/src/acp_sdk/server/__init__.py +1 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/src/acp_sdk/server/agent.py +78 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/src/acp_sdk/server/bundle.py +42 -28
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/src/acp_sdk/server/server.py +4 -103
- acp_sdk-0.2.0/src/acp_sdk/server/types.py +6 -0
- acp_sdk-0.2.0/tests/e2e/fixtures/server.py +83 -0
- acp_sdk-0.2.0/tests/e2e/test_suites/test_runs.py +191 -0
- acp_sdk-0.1.0rc8/PKG-INFO +0 -74
- acp_sdk-0.1.0rc8/README.md +0 -55
- acp_sdk-0.1.0rc8/examples/servers/awaiting.py +0 -23
- acp_sdk-0.1.0rc8/src/acp_sdk/models/models.py +0 -191
- acp_sdk-0.1.0rc8/src/acp_sdk/server/types.py +0 -6
- acp_sdk-0.1.0rc8/tests/e2e/fixtures/server.py +0 -38
- acp_sdk-0.1.0rc8/tests/e2e/test_suites/test_runs.py +0 -89
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/.gitignore +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/.python-version +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/examples/servers/echo.py +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/pytest.ini +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/src/acp_sdk/__init__.py +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/src/acp_sdk/client/__init__.py +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/src/acp_sdk/models/__init__.py +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/src/acp_sdk/models/errors.py +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/src/acp_sdk/models/schemas.py +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/src/acp_sdk/py.typed +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/src/acp_sdk/server/app.py +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/src/acp_sdk/server/context.py +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/src/acp_sdk/server/errors.py +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/src/acp_sdk/server/logging.py +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/src/acp_sdk/server/session.py +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/src/acp_sdk/server/telemetry.py +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/src/acp_sdk/server/utils.py +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/src/acp_sdk/version.py +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/tests/conftest.py +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/tests/e2e/__init__.py +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/tests/e2e/config.py +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/tests/e2e/fixtures/__init__.py +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/tests/e2e/fixtures/client.py +0 -0
- {acp_sdk-0.1.0rc8 → acp_sdk-0.2.0}/tests/e2e/test_suites/__init__.py +0 -0
acp_sdk-0.2.0/PKG-INFO
ADDED
@@ -0,0 +1,113 @@
|
|
1
|
+
Metadata-Version: 2.4
|
2
|
+
Name: acp-sdk
|
3
|
+
Version: 0.2.0
|
4
|
+
Summary: Agent Communication Protocol SDK
|
5
|
+
Author: IBM Corp.
|
6
|
+
Maintainer-email: Tomas Pilar <thomas7pilar@gmail.com>
|
7
|
+
License-Expression: Apache-2.0
|
8
|
+
Requires-Python: <4.0,>=3.11
|
9
|
+
Requires-Dist: opentelemetry-api>=1.31.1
|
10
|
+
Requires-Dist: pydantic>=2.11.1
|
11
|
+
Provides-Extra: client
|
12
|
+
Requires-Dist: httpx-sse>=0.4.0; extra == 'client'
|
13
|
+
Requires-Dist: httpx>=0.28.1; extra == 'client'
|
14
|
+
Requires-Dist: opentelemetry-instrumentation-httpx>=0.52b1; extra == 'client'
|
15
|
+
Provides-Extra: server
|
16
|
+
Requires-Dist: fastapi[standard]>=0.115.8; extra == 'server'
|
17
|
+
Requires-Dist: janus>=2.0.0; extra == 'server'
|
18
|
+
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.31.1; extra == 'server'
|
19
|
+
Requires-Dist: opentelemetry-instrumentation-fastapi>=0.52b1; extra == 'server'
|
20
|
+
Requires-Dist: opentelemetry-sdk>=1.31.1; extra == 'server'
|
21
|
+
Description-Content-Type: text/markdown
|
22
|
+
|
23
|
+
# Agent Communication Protocol SDK for Python
|
24
|
+
|
25
|
+
Agent Communication Protocol SDK for Python provides allows developers to serve and consume agents over the Agent Communication Protocol.
|
26
|
+
|
27
|
+
## Prerequisites
|
28
|
+
|
29
|
+
✅ Python >= 3.11
|
30
|
+
|
31
|
+
## Installation
|
32
|
+
|
33
|
+
Install to use client:
|
34
|
+
|
35
|
+
```shell
|
36
|
+
pip install acp-sdk[client]
|
37
|
+
```
|
38
|
+
|
39
|
+
Install to use server:
|
40
|
+
|
41
|
+
```shell
|
42
|
+
pip install acp-sdk[server]
|
43
|
+
```
|
44
|
+
|
45
|
+
Install to use models only:
|
46
|
+
|
47
|
+
```shell
|
48
|
+
pip install acp-sdk
|
49
|
+
```
|
50
|
+
|
51
|
+
## Overview
|
52
|
+
|
53
|
+
### Core
|
54
|
+
|
55
|
+
The core of the SDK exposes [pydantic](https://docs.pydantic.dev/) data models corresponding to REST API requests, responses, resources, events and errors.
|
56
|
+
|
57
|
+
|
58
|
+
### Client
|
59
|
+
|
60
|
+
The `client` submodule exposes [httpx](https://www.python-httpx.org/) based client with simple methods for communication over ACP.
|
61
|
+
|
62
|
+
```python
|
63
|
+
async with Client(base_url="http://localhost:8000") as client:
|
64
|
+
run = await client.run_sync(agent="echo", inputs=[Message(parts=[MessagePart(content="Howdy!")])])
|
65
|
+
print(run)
|
66
|
+
|
67
|
+
```
|
68
|
+
|
69
|
+
### Server
|
70
|
+
|
71
|
+
The `server` submodule exposes `Agent` class and `agent` decorator together with [fastapi](https://fastapi.tiangolo.com/) application factory, making it easy to expose agents over ACP. Additionaly, it exposes [uvicorn](https://www.uvicorn.org/) based server to serve agents with set up logging, [opentelemetry](https://opentelemetry.io/) and more.
|
72
|
+
|
73
|
+
```python
|
74
|
+
server = Server()
|
75
|
+
|
76
|
+
@server.agent()
|
77
|
+
async def echo(inputs: list[Message], context: Context) -> AsyncGenerator[RunYield, RunYieldResume]:
|
78
|
+
"""Echoes everything"""
|
79
|
+
for message in inputs:
|
80
|
+
yield {"thought": "I should echo everyting"}
|
81
|
+
await asyncio.sleep(0.5)
|
82
|
+
yield message
|
83
|
+
|
84
|
+
|
85
|
+
server.run()
|
86
|
+
```
|
87
|
+
|
88
|
+
➡️ Explore more in our [examples library](/python/examples).
|
89
|
+
|
90
|
+
## Architecture
|
91
|
+
|
92
|
+
The architecture of the SDK is outlined in the following segment. It focuses on central parts of the SDK without going into much detail.
|
93
|
+
|
94
|
+
### Models
|
95
|
+
|
96
|
+
The core of the SDK contains pydantic models for requests, responses, resources, events and errors. Users of the SDK are meant to use these models directly or indirectly.
|
97
|
+
|
98
|
+
### Server
|
99
|
+
|
100
|
+
The server module consists of 3 parts:
|
101
|
+
|
102
|
+
1. Agent interface
|
103
|
+
2. FastAPI application factory
|
104
|
+
3. Uvicorn based server
|
105
|
+
|
106
|
+
Each part builds on top of the previous one. Not all parts need to be used, e.g. users are advised to bring their own ASGI server for production deployments.
|
107
|
+
|
108
|
+
### Client
|
109
|
+
|
110
|
+
The client module consists of httpx based client with session support. The client is meant to be thin and mimic the REST API. Exception is session management which has been abstracted into a context manager.
|
111
|
+
|
112
|
+
|
113
|
+
|
acp_sdk-0.2.0/README.md
ADDED
@@ -0,0 +1,91 @@
|
|
1
|
+
# Agent Communication Protocol SDK for Python
|
2
|
+
|
3
|
+
Agent Communication Protocol SDK for Python provides allows developers to serve and consume agents over the Agent Communication Protocol.
|
4
|
+
|
5
|
+
## Prerequisites
|
6
|
+
|
7
|
+
✅ Python >= 3.11
|
8
|
+
|
9
|
+
## Installation
|
10
|
+
|
11
|
+
Install to use client:
|
12
|
+
|
13
|
+
```shell
|
14
|
+
pip install acp-sdk[client]
|
15
|
+
```
|
16
|
+
|
17
|
+
Install to use server:
|
18
|
+
|
19
|
+
```shell
|
20
|
+
pip install acp-sdk[server]
|
21
|
+
```
|
22
|
+
|
23
|
+
Install to use models only:
|
24
|
+
|
25
|
+
```shell
|
26
|
+
pip install acp-sdk
|
27
|
+
```
|
28
|
+
|
29
|
+
## Overview
|
30
|
+
|
31
|
+
### Core
|
32
|
+
|
33
|
+
The core of the SDK exposes [pydantic](https://docs.pydantic.dev/) data models corresponding to REST API requests, responses, resources, events and errors.
|
34
|
+
|
35
|
+
|
36
|
+
### Client
|
37
|
+
|
38
|
+
The `client` submodule exposes [httpx](https://www.python-httpx.org/) based client with simple methods for communication over ACP.
|
39
|
+
|
40
|
+
```python
|
41
|
+
async with Client(base_url="http://localhost:8000") as client:
|
42
|
+
run = await client.run_sync(agent="echo", inputs=[Message(parts=[MessagePart(content="Howdy!")])])
|
43
|
+
print(run)
|
44
|
+
|
45
|
+
```
|
46
|
+
|
47
|
+
### Server
|
48
|
+
|
49
|
+
The `server` submodule exposes `Agent` class and `agent` decorator together with [fastapi](https://fastapi.tiangolo.com/) application factory, making it easy to expose agents over ACP. Additionaly, it exposes [uvicorn](https://www.uvicorn.org/) based server to serve agents with set up logging, [opentelemetry](https://opentelemetry.io/) and more.
|
50
|
+
|
51
|
+
```python
|
52
|
+
server = Server()
|
53
|
+
|
54
|
+
@server.agent()
|
55
|
+
async def echo(inputs: list[Message], context: Context) -> AsyncGenerator[RunYield, RunYieldResume]:
|
56
|
+
"""Echoes everything"""
|
57
|
+
for message in inputs:
|
58
|
+
yield {"thought": "I should echo everyting"}
|
59
|
+
await asyncio.sleep(0.5)
|
60
|
+
yield message
|
61
|
+
|
62
|
+
|
63
|
+
server.run()
|
64
|
+
```
|
65
|
+
|
66
|
+
➡️ Explore more in our [examples library](/python/examples).
|
67
|
+
|
68
|
+
## Architecture
|
69
|
+
|
70
|
+
The architecture of the SDK is outlined in the following segment. It focuses on central parts of the SDK without going into much detail.
|
71
|
+
|
72
|
+
### Models
|
73
|
+
|
74
|
+
The core of the SDK contains pydantic models for requests, responses, resources, events and errors. Users of the SDK are meant to use these models directly or indirectly.
|
75
|
+
|
76
|
+
### Server
|
77
|
+
|
78
|
+
The server module consists of 3 parts:
|
79
|
+
|
80
|
+
1. Agent interface
|
81
|
+
2. FastAPI application factory
|
82
|
+
3. Uvicorn based server
|
83
|
+
|
84
|
+
Each part builds on top of the previous one. Not all parts need to be used, e.g. users are advised to bring their own ASGI server for production deployments.
|
85
|
+
|
86
|
+
### Client
|
87
|
+
|
88
|
+
The client module consists of httpx based client with session support. The client is meant to be thin and mimic the REST API. Exception is session management which has been abstracted into a context manager.
|
89
|
+
|
90
|
+
|
91
|
+
|
@@ -2,7 +2,7 @@ import asyncio
|
|
2
2
|
|
3
3
|
import httpx
|
4
4
|
from acp_sdk.client.client import Client
|
5
|
-
from acp_sdk.models import Message,
|
5
|
+
from acp_sdk.models import Message, MessagePart
|
6
6
|
|
7
7
|
|
8
8
|
async def example() -> None:
|
@@ -13,8 +13,8 @@ async def example() -> None:
|
|
13
13
|
# Additional client configuration
|
14
14
|
)
|
15
15
|
) as client:
|
16
|
-
run = await client.run_sync(agent="echo", inputs=[Message(
|
17
|
-
print(run
|
16
|
+
run = await client.run_sync(agent="echo", inputs=[Message(parts=[MessagePart(content="Howdy!")])])
|
17
|
+
print(run)
|
18
18
|
|
19
19
|
|
20
20
|
if __name__ == "__main__":
|
@@ -3,15 +3,15 @@ import asyncio
|
|
3
3
|
from acp_sdk.client import Client
|
4
4
|
from acp_sdk.models import (
|
5
5
|
Message,
|
6
|
-
|
6
|
+
MessagePart,
|
7
7
|
)
|
8
8
|
|
9
9
|
|
10
10
|
async def example() -> None:
|
11
11
|
async with Client(base_url="http://localhost:8000") as client, client.session() as session:
|
12
|
-
run = await session.run_sync(agent="
|
13
|
-
run = await session.run_sync(agent="
|
14
|
-
print(run
|
12
|
+
run = await session.run_sync(agent="echo", inputs=[Message(parts=[MessagePart(content="Howdy!")])])
|
13
|
+
run = await session.run_sync(agent="echo", inputs=[Message(parts=[MessagePart(content="Howdy again!")])])
|
14
|
+
print(run)
|
15
15
|
|
16
16
|
|
17
17
|
if __name__ == "__main__":
|
@@ -3,13 +3,15 @@ import asyncio
|
|
3
3
|
from acp_sdk.client import Client
|
4
4
|
from acp_sdk.models import (
|
5
5
|
Message,
|
6
|
-
|
6
|
+
MessagePart,
|
7
7
|
)
|
8
8
|
|
9
9
|
|
10
10
|
async def example() -> None:
|
11
11
|
async with Client(base_url="http://localhost:8000") as client:
|
12
|
-
run = await client.run_sync(
|
12
|
+
run = await client.run_sync(
|
13
|
+
agent="echo", inputs=[Message(parts=[MessagePart(content="Howdy!", content_type="text/plain")])]
|
14
|
+
)
|
13
15
|
print(run.outputs)
|
14
16
|
|
15
17
|
|
@@ -1,12 +1,14 @@
|
|
1
1
|
import asyncio
|
2
2
|
|
3
3
|
from acp_sdk.client import Client
|
4
|
-
from acp_sdk.models import Message,
|
4
|
+
from acp_sdk.models import Message, MessagePart
|
5
5
|
|
6
6
|
|
7
7
|
async def example() -> None:
|
8
8
|
async with Client(base_url="http://localhost:8000") as client:
|
9
|
-
async for event in client.run_stream(
|
9
|
+
async for event in client.run_stream(
|
10
|
+
agent="echo", inputs=[Message(parts=[MessagePart(content="Howdy!", content_type="text/plain")])]
|
11
|
+
):
|
10
12
|
print(event)
|
11
13
|
|
12
14
|
|
@@ -0,0 +1,25 @@
|
|
1
|
+
from collections.abc import AsyncGenerator
|
2
|
+
from typing import Any
|
3
|
+
|
4
|
+
from acp_sdk.models import (
|
5
|
+
AwaitRequest,
|
6
|
+
AwaitResume,
|
7
|
+
Message,
|
8
|
+
MessagePart,
|
9
|
+
)
|
10
|
+
from acp_sdk.server import Context, Server
|
11
|
+
|
12
|
+
server = Server()
|
13
|
+
|
14
|
+
|
15
|
+
@server.agent()
|
16
|
+
async def awaiting(
|
17
|
+
inputs: list[Message], context: Context
|
18
|
+
) -> AsyncGenerator[Message | AwaitRequest | Any, AwaitResume]:
|
19
|
+
"""Greets and awaits for more data"""
|
20
|
+
yield MessagePart(content="Hello!", content_type="text/plain")
|
21
|
+
data = yield AwaitRequest()
|
22
|
+
yield MessagePart(content=f"Thanks for {data}", content_type="text/plain")
|
23
|
+
|
24
|
+
|
25
|
+
server.run()
|
@@ -0,0 +1,25 @@
|
|
1
|
+
from collections.abc import AsyncGenerator
|
2
|
+
|
3
|
+
from acp_sdk.models import (
|
4
|
+
Message,
|
5
|
+
)
|
6
|
+
from acp_sdk.server import RunYield, RunYieldResume, agent, create_app
|
7
|
+
|
8
|
+
# This example demonstrates how to serve agents with you own server
|
9
|
+
|
10
|
+
|
11
|
+
@agent()
|
12
|
+
async def echo(inputs: list[Message]) -> AsyncGenerator[RunYield, RunYieldResume]:
|
13
|
+
"""Echoes everything"""
|
14
|
+
for message in inputs:
|
15
|
+
yield message
|
16
|
+
|
17
|
+
|
18
|
+
app = create_app(echo)
|
19
|
+
|
20
|
+
# The app can now be used with any ASGI server
|
21
|
+
|
22
|
+
# Run with
|
23
|
+
# 1. fastapi run examples/servers/standalone.py
|
24
|
+
# 2. uvicorn examples.servers.standalone:app
|
25
|
+
# ...
|
@@ -1,9 +1,11 @@
|
|
1
1
|
[project]
|
2
2
|
name = "acp-sdk"
|
3
|
-
version = "0.
|
3
|
+
version = "0.2.0"
|
4
4
|
description = "Agent Communication Protocol SDK"
|
5
|
+
license = "Apache-2.0"
|
5
6
|
readme = "README.md"
|
6
|
-
authors = []
|
7
|
+
authors = [{ name = "IBM Corp." }]
|
8
|
+
maintainers = [{ name = "Tomas Pilar", email = "thomas7pilar@gmail.com" }]
|
7
9
|
requires-python = ">=3.11, <4.0"
|
8
10
|
dependencies = ["opentelemetry-api>=1.31.1", "pydantic>=2.11.1"]
|
9
11
|
|
@@ -16,14 +16,14 @@ from acp_sdk.models import (
|
|
16
16
|
AgentReadResponse,
|
17
17
|
AgentsListResponse,
|
18
18
|
AwaitResume,
|
19
|
-
CreatedEvent,
|
20
19
|
Error,
|
20
|
+
Event,
|
21
21
|
Message,
|
22
22
|
Run,
|
23
23
|
RunCancelResponse,
|
24
|
+
RunCreatedEvent,
|
24
25
|
RunCreateRequest,
|
25
26
|
RunCreateResponse,
|
26
|
-
RunEvent,
|
27
27
|
RunId,
|
28
28
|
RunMode,
|
29
29
|
RunResumeRequest,
|
@@ -107,7 +107,7 @@ class Client:
|
|
107
107
|
self._set_session(response)
|
108
108
|
return response
|
109
109
|
|
110
|
-
async def run_stream(self, *, agent: AgentName, inputs: list[Message]) -> AsyncIterator[
|
110
|
+
async def run_stream(self, *, agent: AgentName, inputs: list[Message]) -> AsyncIterator[Event]:
|
111
111
|
async with aconnect_sse(
|
112
112
|
self._client,
|
113
113
|
"POST",
|
@@ -120,7 +120,7 @@ class Client:
|
|
120
120
|
).model_dump_json(),
|
121
121
|
) as event_source:
|
122
122
|
async for event in self._validate_stream(event_source):
|
123
|
-
if isinstance(event,
|
123
|
+
if isinstance(event, RunCreatedEvent):
|
124
124
|
self._set_session(event.run)
|
125
125
|
yield event
|
126
126
|
|
@@ -150,7 +150,7 @@ class Client:
|
|
150
150
|
self._raise_error(response)
|
151
151
|
return RunResumeResponse.model_validate(response.json())
|
152
152
|
|
153
|
-
async def run_resume_stream(self, *, run_id: RunId, await_: AwaitResume) -> AsyncIterator[
|
153
|
+
async def run_resume_stream(self, *, run_id: RunId, await_: AwaitResume) -> AsyncIterator[Event]:
|
154
154
|
async with aconnect_sse(
|
155
155
|
self._client,
|
156
156
|
"POST",
|
@@ -163,9 +163,9 @@ class Client:
|
|
163
163
|
async def _validate_stream(
|
164
164
|
self,
|
165
165
|
event_source: EventSource,
|
166
|
-
) -> AsyncIterator[
|
166
|
+
) -> AsyncIterator[Event]:
|
167
167
|
async for event in event_source.aiter_sse():
|
168
|
-
event = TypeAdapter(
|
168
|
+
event = TypeAdapter(Event).validate_json(event.data)
|
169
169
|
yield event
|
170
170
|
|
171
171
|
def _raise_error(self, response: httpx.Response) -> None:
|
@@ -0,0 +1,170 @@
|
|
1
|
+
import uuid
|
2
|
+
from enum import Enum
|
3
|
+
from typing import Any, Literal, Optional, Union
|
4
|
+
|
5
|
+
from pydantic import AnyUrl, BaseModel, ConfigDict, Field
|
6
|
+
|
7
|
+
from acp_sdk.models.errors import Error
|
8
|
+
|
9
|
+
|
10
|
+
class Metadata(BaseModel):
|
11
|
+
model_config = ConfigDict(extra="allow")
|
12
|
+
|
13
|
+
|
14
|
+
class AnyModel(BaseModel):
|
15
|
+
model_config = ConfigDict(extra="allow")
|
16
|
+
|
17
|
+
|
18
|
+
class MessagePart(BaseModel):
|
19
|
+
name: Optional[str] = None
|
20
|
+
content_type: str
|
21
|
+
content: Optional[str] = None
|
22
|
+
content_encoding: Optional[Literal["plain", "base64"]] = "plain"
|
23
|
+
content_url: Optional[AnyUrl] = None
|
24
|
+
|
25
|
+
model_config = ConfigDict(extra="forbid")
|
26
|
+
|
27
|
+
def model_post_init(self, __context: Any) -> None:
|
28
|
+
if self.content is None and self.content_url is None:
|
29
|
+
raise ValueError("Either content or content_url must be provided")
|
30
|
+
if self.content is not None and self.content_url is not None:
|
31
|
+
raise ValueError("Only one of content or content_url can be provided")
|
32
|
+
|
33
|
+
|
34
|
+
class Artifact(MessagePart):
|
35
|
+
name: str
|
36
|
+
|
37
|
+
|
38
|
+
class Message(BaseModel):
|
39
|
+
parts: list[MessagePart]
|
40
|
+
|
41
|
+
def __add__(self, other: "Message") -> "Message":
|
42
|
+
if not isinstance(other, Message):
|
43
|
+
raise TypeError(f"Cannot concatenate Message with {type(other).__name__}")
|
44
|
+
return Message(*(self.parts + other.parts))
|
45
|
+
|
46
|
+
def __str__(self) -> str:
|
47
|
+
return "".join(
|
48
|
+
part.content for part in self.parts if part.content is not None and part.content_type == "text/plain"
|
49
|
+
)
|
50
|
+
|
51
|
+
|
52
|
+
AgentName = str
|
53
|
+
SessionId = uuid.UUID
|
54
|
+
RunId = uuid.UUID
|
55
|
+
|
56
|
+
|
57
|
+
class RunMode(str, Enum):
|
58
|
+
SYNC = "sync"
|
59
|
+
ASYNC = "async"
|
60
|
+
STREAM = "stream"
|
61
|
+
|
62
|
+
|
63
|
+
class RunStatus(str, Enum):
|
64
|
+
CREATED = "created"
|
65
|
+
IN_PROGRESS = "in-progress"
|
66
|
+
AWAITING = "awaiting"
|
67
|
+
CANCELLING = "cancelling"
|
68
|
+
CANCELLED = "cancelled"
|
69
|
+
COMPLETED = "completed"
|
70
|
+
FAILED = "failed"
|
71
|
+
|
72
|
+
@property
|
73
|
+
def is_terminal(self) -> bool:
|
74
|
+
terminal_states = {RunStatus.COMPLETED, RunStatus.FAILED, RunStatus.CANCELLED}
|
75
|
+
return self in terminal_states
|
76
|
+
|
77
|
+
|
78
|
+
class AwaitRequest(BaseModel):
|
79
|
+
type: Literal["placeholder"] = "placeholder"
|
80
|
+
|
81
|
+
|
82
|
+
class AwaitResume(BaseModel):
|
83
|
+
pass
|
84
|
+
|
85
|
+
|
86
|
+
class Run(BaseModel):
|
87
|
+
run_id: RunId = Field(default_factory=uuid.uuid4)
|
88
|
+
agent_name: AgentName
|
89
|
+
session_id: SessionId | None = None
|
90
|
+
status: RunStatus = RunStatus.CREATED
|
91
|
+
await_request: AwaitRequest | None = None
|
92
|
+
outputs: list[Message] = []
|
93
|
+
error: Error | None = None
|
94
|
+
|
95
|
+
|
96
|
+
class MessageCreatedEvent(BaseModel):
|
97
|
+
type: Literal["message.created"] = "message.created"
|
98
|
+
message: Message
|
99
|
+
|
100
|
+
|
101
|
+
class MessagePartEvent(BaseModel):
|
102
|
+
type: Literal["message.part"] = "message.part"
|
103
|
+
part: MessagePart
|
104
|
+
|
105
|
+
|
106
|
+
class ArtifactEvent(BaseModel):
|
107
|
+
type: Literal["message.part"] = "message.part"
|
108
|
+
part: Artifact
|
109
|
+
|
110
|
+
|
111
|
+
class MessageCompletedEvent(BaseModel):
|
112
|
+
type: Literal["message.completed"] = "message.completed"
|
113
|
+
message: Message
|
114
|
+
|
115
|
+
|
116
|
+
class AwaitEvent(BaseModel):
|
117
|
+
type: Literal["await"] = "await"
|
118
|
+
await_request: AwaitRequest | None = None
|
119
|
+
|
120
|
+
|
121
|
+
class GenericEvent(BaseModel):
|
122
|
+
type: Literal["generic"] = "generic"
|
123
|
+
generic: AnyModel
|
124
|
+
|
125
|
+
|
126
|
+
class RunCreatedEvent(BaseModel):
|
127
|
+
type: Literal["run.created"] = "run.created"
|
128
|
+
run: Run
|
129
|
+
|
130
|
+
|
131
|
+
class RunInProgressEvent(BaseModel):
|
132
|
+
type: Literal["run.in-progress"] = "run.in-progress"
|
133
|
+
run: Run
|
134
|
+
|
135
|
+
|
136
|
+
class RunFailedEvent(BaseModel):
|
137
|
+
type: Literal["run.failed"] = "run.failed"
|
138
|
+
run: Run
|
139
|
+
|
140
|
+
|
141
|
+
class RunCancelledEvent(BaseModel):
|
142
|
+
type: Literal["run.cancelled"] = "run.cancelled"
|
143
|
+
run: Run
|
144
|
+
|
145
|
+
|
146
|
+
class RunCompletedEvent(BaseModel):
|
147
|
+
type: Literal["run.completed"] = "run.completed"
|
148
|
+
run: Run
|
149
|
+
|
150
|
+
|
151
|
+
Event = Union[
|
152
|
+
RunCreatedEvent,
|
153
|
+
RunInProgressEvent,
|
154
|
+
MessageCreatedEvent,
|
155
|
+
ArtifactEvent,
|
156
|
+
MessagePartEvent,
|
157
|
+
MessageCompletedEvent,
|
158
|
+
AwaitEvent,
|
159
|
+
GenericEvent,
|
160
|
+
RunCancelledEvent,
|
161
|
+
RunFailedEvent,
|
162
|
+
RunCompletedEvent,
|
163
|
+
MessagePartEvent,
|
164
|
+
]
|
165
|
+
|
166
|
+
|
167
|
+
class Agent(BaseModel):
|
168
|
+
name: str
|
169
|
+
description: str | None = None
|
170
|
+
metadata: Metadata = Metadata()
|
@@ -3,6 +3,7 @@ import asyncio
|
|
3
3
|
import inspect
|
4
4
|
from collections.abc import AsyncGenerator, Coroutine, Generator
|
5
5
|
from concurrent.futures import ThreadPoolExecutor
|
6
|
+
from typing import Callable
|
6
7
|
|
7
8
|
import janus
|
8
9
|
|
@@ -98,3 +99,80 @@ class Agent(abc.ABC):
|
|
98
99
|
context.yield_sync(self.run(input, context))
|
99
100
|
finally:
|
100
101
|
context.shutdown()
|
102
|
+
|
103
|
+
|
104
|
+
def agent(
|
105
|
+
name: str | None = None,
|
106
|
+
description: str | None = None,
|
107
|
+
*,
|
108
|
+
metadata: Metadata | None = None,
|
109
|
+
) -> Callable[[Callable], Agent]:
|
110
|
+
"""Decorator to create an agent."""
|
111
|
+
|
112
|
+
def decorator(fn: Callable) -> Agent:
|
113
|
+
signature = inspect.signature(fn)
|
114
|
+
parameters = list(signature.parameters.values())
|
115
|
+
|
116
|
+
if len(parameters) == 0:
|
117
|
+
raise TypeError("The agent function must have at least 'input' argument")
|
118
|
+
if len(parameters) > 2:
|
119
|
+
raise TypeError("The agent function must have only 'input' and 'context' arguments")
|
120
|
+
if len(parameters) == 2 and parameters[1].name != "context":
|
121
|
+
raise TypeError("The second argument of the agent function must be 'context'")
|
122
|
+
|
123
|
+
has_context_param = len(parameters) == 2
|
124
|
+
|
125
|
+
class DecoratorAgentBase(Agent):
|
126
|
+
@property
|
127
|
+
def name(self) -> str:
|
128
|
+
return name or fn.__name__
|
129
|
+
|
130
|
+
@property
|
131
|
+
def description(self) -> str:
|
132
|
+
return description or fn.__doc__ or ""
|
133
|
+
|
134
|
+
@property
|
135
|
+
def metadata(self) -> Metadata:
|
136
|
+
return metadata or Metadata()
|
137
|
+
|
138
|
+
agent: Agent
|
139
|
+
if inspect.isasyncgenfunction(fn):
|
140
|
+
|
141
|
+
class AsyncGenDecoratorAgent(DecoratorAgentBase):
|
142
|
+
async def run(self, input: Message, context: Context) -> AsyncGenerator[RunYield, RunYieldResume]:
|
143
|
+
try:
|
144
|
+
gen: AsyncGenerator[RunYield, RunYieldResume] = (
|
145
|
+
fn(input, context) if has_context_param else fn(input)
|
146
|
+
)
|
147
|
+
value = None
|
148
|
+
while True:
|
149
|
+
value = yield await gen.asend(value)
|
150
|
+
except StopAsyncIteration:
|
151
|
+
pass
|
152
|
+
|
153
|
+
agent = AsyncGenDecoratorAgent()
|
154
|
+
elif inspect.iscoroutinefunction(fn):
|
155
|
+
|
156
|
+
class CoroDecoratorAgent(DecoratorAgentBase):
|
157
|
+
async def run(self, input: Message, context: Context) -> Coroutine[RunYield]:
|
158
|
+
return await (fn(input, context) if has_context_param else fn(input))
|
159
|
+
|
160
|
+
agent = CoroDecoratorAgent()
|
161
|
+
elif inspect.isgeneratorfunction(fn):
|
162
|
+
|
163
|
+
class GenDecoratorAgent(DecoratorAgentBase):
|
164
|
+
def run(self, input: Message, context: Context) -> Generator[RunYield, RunYieldResume]:
|
165
|
+
yield from (fn(input, context) if has_context_param else fn(input))
|
166
|
+
|
167
|
+
agent = GenDecoratorAgent()
|
168
|
+
else:
|
169
|
+
|
170
|
+
class FuncDecoratorAgent(DecoratorAgentBase):
|
171
|
+
def run(self, input: Message, context: Context) -> RunYield:
|
172
|
+
return fn(input, context) if has_context_param else fn(input)
|
173
|
+
|
174
|
+
agent = FuncDecoratorAgent()
|
175
|
+
|
176
|
+
return agent
|
177
|
+
|
178
|
+
return decorator
|