fetch-hackkit 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.
- fetch_hackkit/__init__.py +33 -0
- fetch_hackkit/agent.py +340 -0
- fetch_hackkit/asi1.py +294 -0
- fetch_hackkit/cards.py +526 -0
- fetch_hackkit/cli.py +90 -0
- fetch_hackkit/doctor.py +209 -0
- fetch_hackkit/mcp.py +93 -0
- fetch_hackkit/payments.py +264 -0
- fetch_hackkit/peers.py +40 -0
- fetch_hackkit/py.typed +0 -0
- fetch_hackkit/register.py +240 -0
- fetch_hackkit-0.1.0.dist-info/METADATA +72 -0
- fetch_hackkit-0.1.0.dist-info/RECORD +16 -0
- fetch_hackkit-0.1.0.dist-info/WHEEL +4 -0
- fetch_hackkit-0.1.0.dist-info/entry_points.txt +2 -0
- fetch_hackkit-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""fetch-hackkit: batteries for Fetch.ai hackathon agents.
|
|
2
|
+
|
|
3
|
+
from fetch_hackkit import HackAgent, cards, ASI1
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from . import cards
|
|
7
|
+
from .agent import HackAgent, Inbound, Reply, text_message
|
|
8
|
+
from .asi1 import ASI1, ASI1Error, Tool, history, remember, tool
|
|
9
|
+
from .cards import Card, CardError, parse_selection
|
|
10
|
+
from .register import connect_mailbox, handle_available, resolve, validate_handle
|
|
11
|
+
|
|
12
|
+
__version__ = "0.1.0"
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"ASI1",
|
|
16
|
+
"ASI1Error",
|
|
17
|
+
"Card",
|
|
18
|
+
"CardError",
|
|
19
|
+
"HackAgent",
|
|
20
|
+
"Inbound",
|
|
21
|
+
"Reply",
|
|
22
|
+
"Tool",
|
|
23
|
+
"cards",
|
|
24
|
+
"connect_mailbox",
|
|
25
|
+
"handle_available",
|
|
26
|
+
"history",
|
|
27
|
+
"parse_selection",
|
|
28
|
+
"remember",
|
|
29
|
+
"resolve",
|
|
30
|
+
"text_message",
|
|
31
|
+
"tool",
|
|
32
|
+
"validate_handle",
|
|
33
|
+
]
|
fetch_hackkit/agent.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
"""``HackAgent``: a uAgent that already speaks the Agent Chat Protocol.
|
|
2
|
+
|
|
3
|
+
What you get over a plain ``uagents.Agent``:
|
|
4
|
+
|
|
5
|
+
* the chat protocol is included and its manifest published (ASI:One needs this);
|
|
6
|
+
* every message is acknowledged, session start/end content is handled;
|
|
7
|
+
* ``@agent.on_text`` receives clean text (leading ``@handle`` mentions removed);
|
|
8
|
+
* ``@agent.on_action("name")`` receives interactive-card taps, already parsed;
|
|
9
|
+
* handlers just *return* a reply: ``str``, :class:`~fetch_hackkit.cards.Card`,
|
|
10
|
+
``ChatMessage``, or a list of those;
|
|
11
|
+
* if a handler raises, the user gets a friendly message instead of silence;
|
|
12
|
+
* ``@agent.paid(...)`` puts any action behind the Payment Protocol;
|
|
13
|
+
* with ``AGENTVERSE_API_KEY`` set, a mailbox agent connects itself to
|
|
14
|
+
Agentverse on startup (no inspector click), with name, ``@handle``,
|
|
15
|
+
description and README.
|
|
16
|
+
|
|
17
|
+
It *is* a ``uagents.Agent``, so ``on_interval``, ``storage``, ``include`` and
|
|
18
|
+
everything else still work.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import asyncio
|
|
24
|
+
import inspect
|
|
25
|
+
import json
|
|
26
|
+
import os
|
|
27
|
+
import warnings
|
|
28
|
+
from collections.abc import Awaitable, Callable, Sequence
|
|
29
|
+
from dataclasses import dataclass, field
|
|
30
|
+
from datetime import UTC, datetime
|
|
31
|
+
from typing import TYPE_CHECKING, Any, TypeAlias
|
|
32
|
+
from uuid import uuid4
|
|
33
|
+
|
|
34
|
+
from dotenv import find_dotenv, load_dotenv
|
|
35
|
+
from uagents import Agent, Context, Protocol
|
|
36
|
+
from uagents_core.contrib.protocols.chat import (
|
|
37
|
+
ChatAcknowledgement,
|
|
38
|
+
ChatMessage,
|
|
39
|
+
EndSessionContent,
|
|
40
|
+
MetadataContent,
|
|
41
|
+
StartSessionContent,
|
|
42
|
+
TextContent,
|
|
43
|
+
chat_protocol_spec,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
from .cards import Card, collect_actions, parse_selection, strip_mention
|
|
47
|
+
from .register import validate_handle
|
|
48
|
+
|
|
49
|
+
if TYPE_CHECKING:
|
|
50
|
+
from .payments import Paywall
|
|
51
|
+
|
|
52
|
+
DEFAULT_ERROR_MESSAGE = (
|
|
53
|
+
"Sorry, something went wrong on my side while handling that. Please try again in a moment."
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
ReplyPart: TypeAlias = str | Card | ChatMessage
|
|
57
|
+
Reply: TypeAlias = ReplyPart | Sequence[ReplyPart] | None
|
|
58
|
+
TextHandler: TypeAlias = Callable[[Context, "Inbound"], Awaitable[Reply]]
|
|
59
|
+
ActionHandler: TypeAlias = Callable[[Context, "Inbound", dict[str, Any]], Awaitable[Reply]]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class Inbound:
|
|
64
|
+
"""One user message, already unpacked."""
|
|
65
|
+
|
|
66
|
+
sender: str
|
|
67
|
+
text: str
|
|
68
|
+
"""Text with leading ``@handle`` mentions stripped."""
|
|
69
|
+
session: str
|
|
70
|
+
"""Conversation id; use it to key per-conversation state in ``ctx.storage``."""
|
|
71
|
+
raw: ChatMessage
|
|
72
|
+
metadata: dict[str, str] = field(default_factory=dict)
|
|
73
|
+
selection: dict[str, Any] = field(default_factory=dict)
|
|
74
|
+
"""Parsed card tap (``{}`` for ordinary text)."""
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def action(self) -> str | None:
|
|
78
|
+
value = self.selection.get("action")
|
|
79
|
+
return str(value) if value else None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def text_message(text: str, *, end_session: bool = False) -> ChatMessage:
|
|
83
|
+
"""A plain chat-protocol text message."""
|
|
84
|
+
content: list[Any] = [TextContent(type="text", text=text)]
|
|
85
|
+
if end_session:
|
|
86
|
+
content.append(EndSessionContent(type="end-session"))
|
|
87
|
+
return ChatMessage(timestamp=datetime.now(UTC), msg_id=uuid4(), content=content)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def to_messages(reply: Reply) -> list[ChatMessage]:
|
|
91
|
+
"""Normalise anything a handler may return into chat messages."""
|
|
92
|
+
if reply is None:
|
|
93
|
+
return []
|
|
94
|
+
parts: Sequence[ReplyPart] = (
|
|
95
|
+
[reply] if isinstance(reply, str | Card | ChatMessage) else reply # type: ignore[list-item]
|
|
96
|
+
)
|
|
97
|
+
out: list[ChatMessage] = []
|
|
98
|
+
for part in parts:
|
|
99
|
+
if isinstance(part, ChatMessage):
|
|
100
|
+
out.append(part)
|
|
101
|
+
elif isinstance(part, Card):
|
|
102
|
+
out.append(part.to_message())
|
|
103
|
+
elif isinstance(part, str):
|
|
104
|
+
if part.strip():
|
|
105
|
+
out.append(text_message(part))
|
|
106
|
+
else:
|
|
107
|
+
raise TypeError(f"handlers must return str, Card or ChatMessage, got {type(part)!r}")
|
|
108
|
+
return out
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _event_loop() -> asyncio.AbstractEventLoop:
|
|
112
|
+
"""The loop uAgents should use. On Python 3.14+ there is no implicit main-thread
|
|
113
|
+
loop, and ``uagents.Agent()`` at module level crashes without this."""
|
|
114
|
+
try:
|
|
115
|
+
return asyncio.get_running_loop()
|
|
116
|
+
except RuntimeError:
|
|
117
|
+
pass
|
|
118
|
+
try:
|
|
119
|
+
with warnings.catch_warnings():
|
|
120
|
+
warnings.simplefilter("ignore", DeprecationWarning)
|
|
121
|
+
return asyncio.get_event_loop_policy().get_event_loop()
|
|
122
|
+
except RuntimeError:
|
|
123
|
+
loop = asyncio.new_event_loop()
|
|
124
|
+
asyncio.set_event_loop(loop)
|
|
125
|
+
return loop
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
async def _maybe_await(value: Any) -> Any:
|
|
129
|
+
return await value if inspect.isawaitable(value) else value
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class HackAgent(Agent):
|
|
133
|
+
"""A chat-protocol-ready ``uagents.Agent``. See the module docstring."""
|
|
134
|
+
|
|
135
|
+
def __init__(
|
|
136
|
+
self,
|
|
137
|
+
name: str,
|
|
138
|
+
*,
|
|
139
|
+
seed: str | None = None,
|
|
140
|
+
port: int | None = None,
|
|
141
|
+
mailbox: bool = True,
|
|
142
|
+
handle: str | None = None,
|
|
143
|
+
description: str | None = None,
|
|
144
|
+
readme_path: str | None = None,
|
|
145
|
+
avatar_url: str | None = None,
|
|
146
|
+
error_message: str = DEFAULT_ERROR_MESSAGE,
|
|
147
|
+
auto_connect: bool = True,
|
|
148
|
+
**agent_kwargs: Any,
|
|
149
|
+
) -> None:
|
|
150
|
+
load_dotenv(find_dotenv(usecwd=True))
|
|
151
|
+
seed = seed or os.getenv("AGENT_SEED_PHRASE")
|
|
152
|
+
if not seed:
|
|
153
|
+
raise ValueError(
|
|
154
|
+
"No seed phrase. Set AGENT_SEED_PHRASE in .env to any long random phrase and keep "
|
|
155
|
+
"it secret: the seed *is* your agent's identity (address + wallet). "
|
|
156
|
+
"Run `hackkit seed` to generate one."
|
|
157
|
+
)
|
|
158
|
+
if handle:
|
|
159
|
+
validate_handle(handle)
|
|
160
|
+
agent_kwargs.setdefault("loop", _event_loop())
|
|
161
|
+
super().__init__(
|
|
162
|
+
name=name,
|
|
163
|
+
seed=seed,
|
|
164
|
+
port=port or int(os.getenv("AGENT_PORT", "8000")),
|
|
165
|
+
mailbox=mailbox,
|
|
166
|
+
handle=handle,
|
|
167
|
+
description=description,
|
|
168
|
+
readme_path=readme_path,
|
|
169
|
+
avatar_url=avatar_url,
|
|
170
|
+
publish_agent_details=True,
|
|
171
|
+
**agent_kwargs,
|
|
172
|
+
)
|
|
173
|
+
self.error_message = error_message
|
|
174
|
+
self._text_handler: TextHandler | None = None
|
|
175
|
+
self._action_handlers: dict[str, ActionHandler] = {}
|
|
176
|
+
self._known_actions: set[str] = set()
|
|
177
|
+
self._paywall: Paywall | None = None
|
|
178
|
+
|
|
179
|
+
self.chat_protocol = Protocol(spec=chat_protocol_spec)
|
|
180
|
+
self.chat_protocol.on_message(ChatMessage)(self._on_chat_message)
|
|
181
|
+
self.chat_protocol.on_message(ChatAcknowledgement)(self._on_chat_ack)
|
|
182
|
+
self.include(self.chat_protocol, publish_manifest=True)
|
|
183
|
+
|
|
184
|
+
if mailbox and auto_connect:
|
|
185
|
+
self.on_event("startup")(self._auto_connect)
|
|
186
|
+
|
|
187
|
+
# ------------------------------------------------------------------ #
|
|
188
|
+
# Decorators
|
|
189
|
+
# ------------------------------------------------------------------ #
|
|
190
|
+
|
|
191
|
+
def on_text(self, func: TextHandler) -> TextHandler:
|
|
192
|
+
"""Handle ordinary text (and card taps with no matching ``on_action``)."""
|
|
193
|
+
self._text_handler = func
|
|
194
|
+
return func
|
|
195
|
+
|
|
196
|
+
def on_action(self, name: str) -> Callable[[ActionHandler], ActionHandler]:
|
|
197
|
+
"""Handle card taps whose selection has ``{"action": name}``."""
|
|
198
|
+
|
|
199
|
+
def decorator(func: ActionHandler) -> ActionHandler:
|
|
200
|
+
self._action_handlers[name] = func
|
|
201
|
+
self._known_actions.add(name)
|
|
202
|
+
return func
|
|
203
|
+
|
|
204
|
+
return decorator
|
|
205
|
+
|
|
206
|
+
def paid(
|
|
207
|
+
self,
|
|
208
|
+
name: str,
|
|
209
|
+
*,
|
|
210
|
+
amount: str,
|
|
211
|
+
currency: str = "FET",
|
|
212
|
+
description: str | None = None,
|
|
213
|
+
) -> Callable[[ActionHandler], ActionHandler]:
|
|
214
|
+
"""Put action ``name`` behind a payment. The handler runs only after payment.
|
|
215
|
+
|
|
216
|
+
Tapping a button with ``action=name`` (or calling :meth:`charge`) sends the
|
|
217
|
+
user a ``RequestPayment``; when the user's ``CommitPayment`` verifies
|
|
218
|
+
on-chain, the handler runs with the original message and selection.
|
|
219
|
+
"""
|
|
220
|
+
from .payments import Paywall, Product
|
|
221
|
+
|
|
222
|
+
if self._paywall is None:
|
|
223
|
+
self._paywall = Paywall(self)
|
|
224
|
+
paywall = self._paywall
|
|
225
|
+
|
|
226
|
+
def decorator(func: ActionHandler) -> ActionHandler:
|
|
227
|
+
paywall.add(
|
|
228
|
+
Product(
|
|
229
|
+
name=name,
|
|
230
|
+
amount=amount,
|
|
231
|
+
currency=currency,
|
|
232
|
+
description=description or name,
|
|
233
|
+
handler=func,
|
|
234
|
+
)
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
async def request(ctx: Context, msg: Inbound, sel: dict[str, Any]) -> Reply:
|
|
238
|
+
return await paywall.request(ctx, msg, name, sel)
|
|
239
|
+
|
|
240
|
+
self._action_handlers[name] = request
|
|
241
|
+
self._known_actions.add(name)
|
|
242
|
+
return func
|
|
243
|
+
|
|
244
|
+
return decorator
|
|
245
|
+
|
|
246
|
+
async def charge(
|
|
247
|
+
self, ctx: Context, msg: Inbound, product: str, sel: dict[str, Any] | None = None
|
|
248
|
+
) -> Reply:
|
|
249
|
+
"""Start the payment flow for a ``@paid`` product from your own code."""
|
|
250
|
+
if self._paywall is None:
|
|
251
|
+
raise ValueError(f"no @agent.paid product named {product!r}")
|
|
252
|
+
return await self._paywall.request(ctx, msg, product, sel or {})
|
|
253
|
+
|
|
254
|
+
# ------------------------------------------------------------------ #
|
|
255
|
+
# Sending
|
|
256
|
+
# ------------------------------------------------------------------ #
|
|
257
|
+
|
|
258
|
+
async def reply(self, ctx: Context, to: str, reply: Reply) -> None:
|
|
259
|
+
"""Send a reply (any handler return value) to ``to``."""
|
|
260
|
+
for message in to_messages(reply):
|
|
261
|
+
for content in message.content:
|
|
262
|
+
if isinstance(content, MetadataContent) and "card_payload" in content.metadata:
|
|
263
|
+
self._known_actions |= collect_actions(
|
|
264
|
+
json.loads(content.metadata["card_payload"])
|
|
265
|
+
)
|
|
266
|
+
await ctx.send(to, message)
|
|
267
|
+
|
|
268
|
+
# ------------------------------------------------------------------ #
|
|
269
|
+
# Protocol plumbing
|
|
270
|
+
# ------------------------------------------------------------------ #
|
|
271
|
+
|
|
272
|
+
async def _on_chat_ack(self, ctx: Context, sender: str, msg: ChatAcknowledgement) -> None:
|
|
273
|
+
ctx.logger.debug(f"ack from {sender} for {msg.acknowledged_msg_id}")
|
|
274
|
+
|
|
275
|
+
async def _on_chat_message(self, ctx: Context, sender: str, msg: ChatMessage) -> None:
|
|
276
|
+
await ctx.send(
|
|
277
|
+
sender,
|
|
278
|
+
ChatAcknowledgement(timestamp=datetime.now(UTC), acknowledged_msg_id=msg.msg_id),
|
|
279
|
+
)
|
|
280
|
+
texts: list[str] = []
|
|
281
|
+
metadata: dict[str, str] = {}
|
|
282
|
+
for content in msg.content:
|
|
283
|
+
if isinstance(content, TextContent):
|
|
284
|
+
texts.append(content.text)
|
|
285
|
+
elif isinstance(content, MetadataContent):
|
|
286
|
+
metadata.update(content.metadata)
|
|
287
|
+
elif isinstance(content, StartSessionContent):
|
|
288
|
+
ctx.logger.info(f"session start from {sender}")
|
|
289
|
+
elif isinstance(content, EndSessionContent):
|
|
290
|
+
ctx.logger.info(f"session end from {sender}")
|
|
291
|
+
raw_text = "\n".join(texts).strip()
|
|
292
|
+
if not raw_text:
|
|
293
|
+
return
|
|
294
|
+
|
|
295
|
+
inbound = Inbound(
|
|
296
|
+
sender=sender,
|
|
297
|
+
text=strip_mention(raw_text),
|
|
298
|
+
session=str(ctx.session),
|
|
299
|
+
raw=msg,
|
|
300
|
+
metadata=metadata,
|
|
301
|
+
selection=parse_selection(raw_text, self._known_actions),
|
|
302
|
+
)
|
|
303
|
+
ctx.logger.info(f"<- {sender[:16]}…: {inbound.text[:200]!r}")
|
|
304
|
+
try:
|
|
305
|
+
reply = await self._dispatch(ctx, inbound)
|
|
306
|
+
except Exception:
|
|
307
|
+
ctx.logger.exception("handler failed")
|
|
308
|
+
reply = self.error_message
|
|
309
|
+
try:
|
|
310
|
+
await self.reply(ctx, sender, reply)
|
|
311
|
+
except Exception:
|
|
312
|
+
ctx.logger.exception("could not send reply")
|
|
313
|
+
await ctx.send(sender, text_message(self.error_message))
|
|
314
|
+
|
|
315
|
+
async def _dispatch(self, ctx: Context, inbound: Inbound) -> Reply:
|
|
316
|
+
action = inbound.action
|
|
317
|
+
if action and action in self._action_handlers:
|
|
318
|
+
return await _maybe_await(
|
|
319
|
+
self._action_handlers[action](ctx, inbound, inbound.selection)
|
|
320
|
+
)
|
|
321
|
+
if self._text_handler is not None:
|
|
322
|
+
return await _maybe_await(self._text_handler(ctx, inbound))
|
|
323
|
+
return "Hi! This agent has no @agent.on_text handler yet."
|
|
324
|
+
|
|
325
|
+
async def _auto_connect(self, ctx: Context) -> None:
|
|
326
|
+
from .register import connect_mailbox
|
|
327
|
+
|
|
328
|
+
if not os.getenv("AGENTVERSE_API_KEY"):
|
|
329
|
+
ctx.logger.warning(
|
|
330
|
+
"AGENTVERSE_API_KEY not set: open the inspector link above and click Connect "
|
|
331
|
+
"(mailbox), or set the key so the agent connects itself."
|
|
332
|
+
)
|
|
333
|
+
return
|
|
334
|
+
result = await connect_mailbox(self)
|
|
335
|
+
if result.ok:
|
|
336
|
+
ctx.logger.info(f"Connected to Agentverse as {result.profile_url}")
|
|
337
|
+
if result.detail:
|
|
338
|
+
ctx.logger.warning(result.detail)
|
|
339
|
+
else:
|
|
340
|
+
ctx.logger.error(f"Agentverse connect failed: {result.detail}")
|
fetch_hackkit/asi1.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
"""ASI:One LLM client: chat, structured output, and a tool-calling loop.
|
|
2
|
+
|
|
3
|
+
ASI:One speaks the OpenAI Chat Completions format, so this wraps the official
|
|
4
|
+
``openai`` SDK pointed at ``https://api.asi1.ai/v1``.
|
|
5
|
+
|
|
6
|
+
llm = ASI1() # reads ASI_ONE_API_KEY
|
|
7
|
+
text = await llm.ask("Explain uAgents in one line")
|
|
8
|
+
answer = await llm.run_tools("Weather in Paris?", tools=[get_weather])
|
|
9
|
+
|
|
10
|
+
Any plain Python function (sync or async) with type hints and a docstring can
|
|
11
|
+
be a tool; its JSON schema is generated for you.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import asyncio
|
|
17
|
+
import inspect
|
|
18
|
+
import json
|
|
19
|
+
import logging
|
|
20
|
+
import os
|
|
21
|
+
import re
|
|
22
|
+
from collections.abc import Awaitable, Callable, Sequence
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from typing import Any, TypeVar, cast, get_type_hints
|
|
25
|
+
|
|
26
|
+
from openai import AsyncOpenAI
|
|
27
|
+
from pydantic import BaseModel, ValidationError, create_model
|
|
28
|
+
|
|
29
|
+
ASI1_BASE_URL = "https://api.asi1.ai/v1"
|
|
30
|
+
DEFAULT_MODEL = "asi1"
|
|
31
|
+
_KEY_ENVS = ("ASI_ONE_API_KEY", "ASI1_API_KEY")
|
|
32
|
+
|
|
33
|
+
log = logging.getLogger("fetch_hackkit.asi1")
|
|
34
|
+
M = TypeVar("M", bound=BaseModel)
|
|
35
|
+
Message = dict[str, Any]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ASI1Error(RuntimeError):
|
|
39
|
+
pass
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# --------------------------------------------------------------------------- #
|
|
43
|
+
# Tools
|
|
44
|
+
# --------------------------------------------------------------------------- #
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class Tool:
|
|
49
|
+
"""A function the model may call."""
|
|
50
|
+
|
|
51
|
+
name: str
|
|
52
|
+
description: str
|
|
53
|
+
parameters: dict[str, Any]
|
|
54
|
+
call: Callable[[dict[str, Any]], Awaitable[Any]]
|
|
55
|
+
|
|
56
|
+
def spec(self) -> dict[str, Any]:
|
|
57
|
+
return {
|
|
58
|
+
"type": "function",
|
|
59
|
+
"function": {
|
|
60
|
+
"name": self.name,
|
|
61
|
+
"description": self.description,
|
|
62
|
+
"parameters": self.parameters,
|
|
63
|
+
},
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _doc_parts(func: Callable[..., Any]) -> tuple[str, dict[str, str]]:
|
|
68
|
+
"""Summary + per-argument descriptions from a Google-style docstring."""
|
|
69
|
+
doc = inspect.getdoc(func) or ""
|
|
70
|
+
summary = doc.split("\n\n", 1)[0].strip().replace("\n", " ")
|
|
71
|
+
args: dict[str, str] = {}
|
|
72
|
+
match = re.search(r"^(?:Args|Arguments|Parameters):\s*\n(.*?)(?:\n\S|\Z)", doc, re.S | re.M)
|
|
73
|
+
if match:
|
|
74
|
+
for line in match.group(1).splitlines():
|
|
75
|
+
m = re.match(r"\s+(\w+)(?:\s*\([^)]*\))?:\s*(.+)", line)
|
|
76
|
+
if m:
|
|
77
|
+
args[m.group(1)] = m.group(2).strip()
|
|
78
|
+
return summary or func.__name__.replace("_", " "), args
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def tool(func: Callable[..., Any], *, name: str | None = None) -> Tool:
|
|
82
|
+
"""Turn a typed Python function (sync or async) into a :class:`Tool`."""
|
|
83
|
+
if isinstance(func, Tool):
|
|
84
|
+
return func
|
|
85
|
+
summary, arg_docs = _doc_parts(func)
|
|
86
|
+
hints = get_type_hints(func)
|
|
87
|
+
fields: dict[str, Any] = {}
|
|
88
|
+
for pname, param in inspect.signature(func).parameters.items():
|
|
89
|
+
if param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD):
|
|
90
|
+
continue
|
|
91
|
+
annotation = hints.get(pname, str)
|
|
92
|
+
default = ... if param.default is inspect.Parameter.empty else param.default
|
|
93
|
+
fields[pname] = (annotation, default)
|
|
94
|
+
model = create_model(f"{func.__name__}_args", **fields)
|
|
95
|
+
schema = model.model_json_schema()
|
|
96
|
+
schema.pop("title", None)
|
|
97
|
+
for pname, prop in schema.get("properties", {}).items():
|
|
98
|
+
prop.pop("title", None)
|
|
99
|
+
if pname in arg_docs:
|
|
100
|
+
prop["description"] = arg_docs[pname]
|
|
101
|
+
|
|
102
|
+
async def call(arguments: dict[str, Any]) -> Any:
|
|
103
|
+
validated = model.model_validate(arguments)
|
|
104
|
+
kwargs = {k: getattr(validated, k) for k in fields}
|
|
105
|
+
if inspect.iscoroutinefunction(func):
|
|
106
|
+
return await func(**kwargs)
|
|
107
|
+
return await asyncio.to_thread(func, **kwargs)
|
|
108
|
+
|
|
109
|
+
return Tool(name=name or func.__name__, description=summary, parameters=schema, call=call)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _to_text(value: Any) -> str:
|
|
113
|
+
if isinstance(value, str):
|
|
114
|
+
return value
|
|
115
|
+
if isinstance(value, BaseModel):
|
|
116
|
+
return value.model_dump_json()
|
|
117
|
+
try:
|
|
118
|
+
return json.dumps(value, default=str, ensure_ascii=False)
|
|
119
|
+
except (TypeError, ValueError):
|
|
120
|
+
return str(value)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _extract_json(text: str) -> str:
|
|
124
|
+
"""Pull a JSON object out of a reply that may wrap it in prose or code fences."""
|
|
125
|
+
fenced = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.S)
|
|
126
|
+
if fenced:
|
|
127
|
+
return fenced.group(1)
|
|
128
|
+
start, end = text.find("{"), text.rfind("}")
|
|
129
|
+
return text[start : end + 1] if start != -1 and end > start else text
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# --------------------------------------------------------------------------- #
|
|
133
|
+
# Client
|
|
134
|
+
# --------------------------------------------------------------------------- #
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class ASI1:
|
|
138
|
+
"""Thin async ASI:One client."""
|
|
139
|
+
|
|
140
|
+
def __init__(
|
|
141
|
+
self,
|
|
142
|
+
api_key: str | None = None,
|
|
143
|
+
*,
|
|
144
|
+
model: str | None = None,
|
|
145
|
+
base_url: str = ASI1_BASE_URL,
|
|
146
|
+
timeout: float = 60.0,
|
|
147
|
+
client: AsyncOpenAI | None = None,
|
|
148
|
+
) -> None:
|
|
149
|
+
self.model = model or os.getenv("ASI_ONE_MODEL") or DEFAULT_MODEL
|
|
150
|
+
if client is not None:
|
|
151
|
+
self.client = client
|
|
152
|
+
return
|
|
153
|
+
key = api_key or next((os.environ[k] for k in _KEY_ENVS if os.getenv(k)), None)
|
|
154
|
+
if not key:
|
|
155
|
+
raise ASI1Error(
|
|
156
|
+
"ASI_ONE_API_KEY is not set. Get a key at https://asi1.ai/developer "
|
|
157
|
+
"and put it in your .env."
|
|
158
|
+
)
|
|
159
|
+
self.client = AsyncOpenAI(api_key=key, base_url=base_url, timeout=timeout)
|
|
160
|
+
|
|
161
|
+
async def chat(
|
|
162
|
+
self, messages: Sequence[Message], *, model: str | None = None, **kwargs: Any
|
|
163
|
+
) -> str:
|
|
164
|
+
"""One completion. Returns the assistant text."""
|
|
165
|
+
resp = await self.client.chat.completions.create(
|
|
166
|
+
model=model or self.model,
|
|
167
|
+
messages=cast(Any, list(messages)),
|
|
168
|
+
**kwargs,
|
|
169
|
+
)
|
|
170
|
+
return resp.choices[0].message.content or ""
|
|
171
|
+
|
|
172
|
+
async def ask(
|
|
173
|
+
self, prompt: str, *, system: str | None = None, history: Sequence[Message] = ()
|
|
174
|
+
) -> str:
|
|
175
|
+
"""Ask a single question (optionally with a system prompt and prior turns)."""
|
|
176
|
+
return await self.chat(_messages(prompt, system, history))
|
|
177
|
+
|
|
178
|
+
async def structured(
|
|
179
|
+
self, prompt: str, schema: type[M], *, system: str | None = None, retries: int = 1
|
|
180
|
+
) -> M:
|
|
181
|
+
"""Ask for JSON matching a Pydantic model; validated, with one repair retry."""
|
|
182
|
+
instructions = (
|
|
183
|
+
"Reply with only a JSON object matching this JSON schema, no prose:\n"
|
|
184
|
+
+ json.dumps(schema.model_json_schema())
|
|
185
|
+
)
|
|
186
|
+
messages = _messages(prompt, f"{system}\n\n{instructions}" if system else instructions)
|
|
187
|
+
for attempt in range(retries + 1):
|
|
188
|
+
text = await self.chat(messages)
|
|
189
|
+
try:
|
|
190
|
+
return schema.model_validate_json(_extract_json(text))
|
|
191
|
+
except ValidationError as exc:
|
|
192
|
+
if attempt == retries:
|
|
193
|
+
raise ASI1Error(f"model did not return valid {schema.__name__}: {exc}") from exc
|
|
194
|
+
messages = [
|
|
195
|
+
*messages,
|
|
196
|
+
{"role": "assistant", "content": text},
|
|
197
|
+
{"role": "user", "content": f"That was invalid: {exc}. Try again."},
|
|
198
|
+
]
|
|
199
|
+
raise AssertionError("unreachable")
|
|
200
|
+
|
|
201
|
+
async def run_tools(
|
|
202
|
+
self,
|
|
203
|
+
prompt: str | Sequence[Message],
|
|
204
|
+
tools: Sequence[Callable[..., Any] | Tool],
|
|
205
|
+
*,
|
|
206
|
+
system: str | None = None,
|
|
207
|
+
max_steps: int = 6,
|
|
208
|
+
on_call: Callable[[str, dict[str, Any], Any], None] | None = None,
|
|
209
|
+
) -> str:
|
|
210
|
+
"""Let the model call ``tools`` until it can answer; returns the final text.
|
|
211
|
+
|
|
212
|
+
Tool exceptions are sent back to the model as ``{"error": ...}`` so it
|
|
213
|
+
can retry or explain, instead of crashing your agent.
|
|
214
|
+
"""
|
|
215
|
+
registry = {t.name: t for t in (f if isinstance(f, Tool) else tool(f) for f in tools)}
|
|
216
|
+
specs = [t.spec() for t in registry.values()]
|
|
217
|
+
messages: list[Message] = (
|
|
218
|
+
_messages(prompt, system)
|
|
219
|
+
if isinstance(prompt, str)
|
|
220
|
+
else [*([{"role": "system", "content": system}] if system else []), *prompt]
|
|
221
|
+
)
|
|
222
|
+
for _ in range(max_steps):
|
|
223
|
+
resp = await self.client.chat.completions.create(
|
|
224
|
+
model=self.model,
|
|
225
|
+
messages=cast(Any, messages),
|
|
226
|
+
tools=cast(Any, specs),
|
|
227
|
+
)
|
|
228
|
+
message = resp.choices[0].message
|
|
229
|
+
calls: list[Any] = list(message.tool_calls or [])
|
|
230
|
+
if not calls:
|
|
231
|
+
return message.content or ""
|
|
232
|
+
messages.append(
|
|
233
|
+
{
|
|
234
|
+
"role": "assistant",
|
|
235
|
+
"content": message.content or "",
|
|
236
|
+
"tool_calls": [
|
|
237
|
+
{
|
|
238
|
+
"id": c.id,
|
|
239
|
+
"type": "function",
|
|
240
|
+
"function": {
|
|
241
|
+
"name": c.function.name,
|
|
242
|
+
"arguments": c.function.arguments,
|
|
243
|
+
},
|
|
244
|
+
}
|
|
245
|
+
for c in calls
|
|
246
|
+
if getattr(c, "function", None) is not None
|
|
247
|
+
],
|
|
248
|
+
}
|
|
249
|
+
)
|
|
250
|
+
for call in calls:
|
|
251
|
+
fn = getattr(call, "function", None)
|
|
252
|
+
name = getattr(fn, "name", "")
|
|
253
|
+
args: dict[str, Any] = {}
|
|
254
|
+
try:
|
|
255
|
+
args = json.loads(getattr(fn, "arguments", None) or "{}")
|
|
256
|
+
if name not in registry:
|
|
257
|
+
raise ASI1Error(f"unknown tool {name!r}")
|
|
258
|
+
result: Any = await registry[name].call(args)
|
|
259
|
+
except Exception as exc: # report to the model, keep going
|
|
260
|
+
result = {"error": f"{type(exc).__name__}: {exc}"}
|
|
261
|
+
log.warning("tool %s failed: %s", name, exc)
|
|
262
|
+
if on_call:
|
|
263
|
+
on_call(name, args, result)
|
|
264
|
+
messages.append(
|
|
265
|
+
{"role": "tool", "tool_call_id": call.id, "content": _to_text(result)[:20_000]}
|
|
266
|
+
)
|
|
267
|
+
messages.append(
|
|
268
|
+
{"role": "user", "content": "Stop calling tools and answer with what you have."}
|
|
269
|
+
)
|
|
270
|
+
return await self.chat(messages)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _messages(
|
|
274
|
+
prompt: str, system: str | None = None, history: Sequence[Message] = ()
|
|
275
|
+
) -> list[Message]:
|
|
276
|
+
out: list[Message] = [{"role": "system", "content": system}] if system else []
|
|
277
|
+
return [*out, *history, {"role": "user", "content": prompt}]
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
# --------------------------------------------------------------------------- #
|
|
281
|
+
# Per-conversation memory (ASI:One sends your agent one message at a time)
|
|
282
|
+
# --------------------------------------------------------------------------- #
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def history(ctx: Any, session: str) -> list[Message]:
|
|
286
|
+
"""Prior turns for this conversation, stored in ``ctx.storage``."""
|
|
287
|
+
stored = ctx.storage.get(f"hackkit:history:{session}")
|
|
288
|
+
return list(stored) if isinstance(stored, list) else []
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def remember(ctx: Any, session: str, role: str, content: str, *, keep: int = 20) -> None:
|
|
292
|
+
"""Append a turn to this conversation's history (keeps the last ``keep``)."""
|
|
293
|
+
turns = [*history(ctx, session), {"role": role, "content": content}][-keep:]
|
|
294
|
+
ctx.storage.set(f"hackkit:history:{session}", turns)
|