agent0-runtime 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.
@@ -0,0 +1,285 @@
1
+ """Proxy-aware downloads with trafilatura for HTML extraction only."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from email.message import Message
7
+ from functools import lru_cache
8
+ from html.parser import HTMLParser
9
+ from pathlib import Path
10
+ from typing import Any
11
+ from urllib.parse import urlsplit, urlunsplit
12
+ from urllib.request import getproxies, proxy_bypass
13
+
14
+ DEFAULT_FETCH_CHARS = 12_000
15
+ MAX_FETCH_CHARS = 50_000
16
+ MAX_DOWNLOAD_BYTES = 20_000_000
17
+ CONNECT_TIMEOUT = 8
18
+ READ_TIMEOUT = 20
19
+
20
+ _USER_AGENT = "Mozilla/5.0 (compatible; agent0-runtime)"
21
+ _RETRY_STATUS = (429, 500, 502, 503, 504)
22
+ _TEXT_TYPES = frozenset(
23
+ {
24
+ "application/javascript",
25
+ "application/json",
26
+ "application/toml",
27
+ "application/x-yaml",
28
+ "application/xml",
29
+ "application/yaml",
30
+ }
31
+ )
32
+
33
+
34
+ class _FetchError(Exception):
35
+ """A download failure with a model-readable message."""
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class _Downloaded:
40
+ data: bytes
41
+ media_type: str
42
+ charset: str | None = None
43
+
44
+
45
+ def _normalized_url(url: str) -> str:
46
+ if not isinstance(url, str) or not url.strip():
47
+ raise ValueError("url must be a non-empty string")
48
+ parsed = urlsplit(url.strip())
49
+ if parsed.scheme.lower() not in ("http", "https") or not parsed.netloc:
50
+ raise ValueError("url must start with http:// or https://")
51
+ return urlunsplit(parsed._replace(fragment=""))
52
+
53
+
54
+ def _limit(max_chars: int | None) -> int:
55
+ if max_chars is None:
56
+ return DEFAULT_FETCH_CHARS
57
+ limit = int(max_chars)
58
+ if limit < 1:
59
+ raise ValueError("max_chars must be at least 1")
60
+ return min(limit, MAX_FETCH_CHARS)
61
+
62
+
63
+ def _truncate(text: str, limit: int) -> str:
64
+ if len(text) <= limit:
65
+ return text
66
+ return text[:limit] + f"\n... [truncated {len(text) - limit} chars]"
67
+
68
+
69
+ def _proxy_for(url: str) -> str | None:
70
+ """Resolve lowercase/uppercase environment proxies and no_proxy rules."""
71
+ parsed = urlsplit(url)
72
+ if parsed.hostname and proxy_bypass(parsed.hostname):
73
+ return None
74
+ proxies = getproxies()
75
+ return proxies.get(parsed.scheme.lower()) or proxies.get("all")
76
+
77
+
78
+ def _http_stack() -> Any:
79
+ """Load optional HTTP dependencies only when the fetch tool is used."""
80
+
81
+ try:
82
+ import certifi
83
+ import urllib3
84
+ except ImportError as e:
85
+ raise RuntimeError("the fetch tool requires the web extra (urllib3 + certifi)") from e
86
+ return urllib3, certifi
87
+
88
+
89
+ @lru_cache(maxsize=8)
90
+ def _pool(proxy_url: str | None) -> Any:
91
+ # Reuse connections within a host without keeping proxy credentials elsewhere.
92
+ urllib3, certifi = _http_stack()
93
+ options = {"ca_certs": certifi.where(), "cert_reqs": "CERT_REQUIRED", "num_pools": 4}
94
+ if proxy_url:
95
+ return urllib3.ProxyManager(proxy_url, **options)
96
+ return urllib3.PoolManager(**options)
97
+
98
+
99
+ def _download(url: str) -> _Downloaded:
100
+ urllib3, _certifi = _http_stack()
101
+ retries = urllib3.Retry(
102
+ total=None,
103
+ connect=1,
104
+ read=1,
105
+ status=1,
106
+ redirect=2,
107
+ backoff_factor=0.5,
108
+ status_forcelist=_RETRY_STATUS,
109
+ allowed_methods=frozenset({"GET"}),
110
+ respect_retry_after_header=False,
111
+ raise_on_status=False,
112
+ )
113
+ response = None
114
+ try:
115
+ manager = _pool(_proxy_for(url))
116
+ response = manager.request(
117
+ "GET",
118
+ url,
119
+ headers={"User-Agent": _USER_AGENT},
120
+ timeout=urllib3.Timeout(connect=CONNECT_TIMEOUT, read=READ_TIMEOUT),
121
+ preload_content=False,
122
+ retries=retries,
123
+ )
124
+ if not 200 <= response.status < 300:
125
+ raise _FetchError(f"HTTP {response.status}")
126
+
127
+ body = bytearray()
128
+ for chunk in response.stream(2**16):
129
+ body.extend(chunk)
130
+ if len(body) > MAX_DOWNLOAD_BYTES:
131
+ raise _FetchError(f"response exceeds {MAX_DOWNLOAD_BYTES} bytes")
132
+
133
+ content_type = response.headers.get("Content-Type", "")
134
+ header = Message()
135
+ header["content-type"] = content_type
136
+ media_type = header.get_content_type().lower() if content_type else ""
137
+ return _Downloaded(bytes(body), media_type, header.get_content_charset())
138
+ except _FetchError:
139
+ raise
140
+ except (OSError, ValueError, urllib3.exceptions.HTTPError) as e:
141
+ raise _FetchError("could not fetch URL") from e
142
+ finally:
143
+ if response is not None:
144
+ response.release_conn()
145
+
146
+
147
+ def _decode(downloaded: _Downloaded) -> str:
148
+ if downloaded.charset:
149
+ try:
150
+ return downloaded.data.decode(downloaded.charset)
151
+ except (LookupError, UnicodeDecodeError):
152
+ pass
153
+ try:
154
+ return downloaded.data.decode("utf-8")
155
+ except UnicodeDecodeError:
156
+ # Reuse trafilatura's encoding detection for legacy/non-UTF-8 pages.
157
+ from trafilatura.utils import decode_file
158
+
159
+ return decode_file(downloaded.data)
160
+
161
+
162
+ def _is_html(downloaded: _Downloaded) -> bool:
163
+ if downloaded.media_type in ("text/html", "application/xhtml+xml"):
164
+ return True
165
+ if downloaded.media_type:
166
+ return False
167
+ beginning = downloaded.data[:4096].lstrip().lower()
168
+ return beginning.startswith((b"<!doctype html", b"<html", b"<head", b"<body"))
169
+
170
+
171
+ def _is_text(downloaded: _Downloaded) -> bool:
172
+ media_type = downloaded.media_type
173
+ if not media_type:
174
+ return b"\0" not in downloaded.data[:4096]
175
+ return (
176
+ media_type.startswith("text/")
177
+ or media_type in _TEXT_TYPES
178
+ or media_type.endswith(("+json", "+xml"))
179
+ )
180
+
181
+
182
+ class _PlainTextParser(HTMLParser):
183
+ """Last-resort HTML text extraction without script/style contents."""
184
+
185
+ _HIDDEN = frozenset({"script", "style", "noscript", "svg"})
186
+ _BREAKS = frozenset(
187
+ {
188
+ "article",
189
+ "br",
190
+ "div",
191
+ "h1",
192
+ "h2",
193
+ "h3",
194
+ "h4",
195
+ "h5",
196
+ "h6",
197
+ "li",
198
+ "p",
199
+ "pre",
200
+ "section",
201
+ "table",
202
+ "tr",
203
+ }
204
+ )
205
+
206
+ def __init__(self) -> None:
207
+ super().__init__(convert_charrefs=True)
208
+ self.parts: list[str] = []
209
+ self.hidden = 0
210
+
211
+ def handle_starttag(self, tag: str, _attrs: list[tuple[str, str | None]]) -> None:
212
+ if tag in self._HIDDEN:
213
+ self.hidden += 1
214
+ elif not self.hidden and tag in self._BREAKS:
215
+ self.parts.append("\n")
216
+
217
+ def handle_endtag(self, tag: str) -> None:
218
+ if tag in self._HIDDEN and self.hidden:
219
+ self.hidden -= 1
220
+ elif not self.hidden and tag in self._BREAKS:
221
+ self.parts.append("\n")
222
+
223
+ def handle_data(self, data: str) -> None:
224
+ if not self.hidden:
225
+ self.parts.append(data)
226
+
227
+
228
+ def _plain_text(downloaded: _Downloaded) -> str:
229
+ parser = _PlainTextParser()
230
+ parser.feed(_decode(downloaded))
231
+ parser.close()
232
+ lines = (" ".join(line.split()) for line in "".join(parser.parts).splitlines())
233
+ return "\n".join(line for line in lines if line)
234
+
235
+
236
+ def _extract_html(downloaded: _Downloaded, url: str) -> str | None:
237
+ from trafilatura import extract
238
+
239
+ options = {
240
+ "url": url,
241
+ "output_format": "markdown",
242
+ "with_metadata": True,
243
+ "include_comments": False,
244
+ "include_tables": True,
245
+ "include_links": True,
246
+ "include_images": False,
247
+ "deduplicate": True,
248
+ }
249
+ text = extract(downloaded.data, **options)
250
+ if not text:
251
+ # Relax precision before falling back to bounded, cleaned plain text.
252
+ text = extract(downloaded.data, **options, favor_recall=True)
253
+ return text
254
+
255
+
256
+ def fetch(url: str, max_chars: int | None = None) -> str:
257
+ """Download a page and return bounded Markdown or readable plain text."""
258
+ try:
259
+ url = _normalized_url(url)
260
+ limit = _limit(max_chars)
261
+ downloaded = _download(url)
262
+ except (TypeError, ValueError, _FetchError) as e:
263
+ return f"error: {e}"
264
+
265
+ if _is_html(downloaded):
266
+ try:
267
+ text = _extract_html(downloaded, url)
268
+ except ImportError:
269
+ return "error: trafilatura is not installed"
270
+ if not text:
271
+ text = _plain_text(downloaded)
272
+ elif _is_text(downloaded):
273
+ # Raw Markdown, source files, and JSON need no HTML extraction pass.
274
+ text = _decode(downloaded)
275
+ else:
276
+ return f"error: unsupported content type: {downloaded.media_type or 'unknown'}"
277
+
278
+ if not text or not text.strip():
279
+ return "error: no readable text extracted"
280
+ return _truncate(text, limit)
281
+
282
+
283
+ def tool_fetch(_cwd: Path | None, url: str, max_chars: int | None = None) -> str:
284
+ """fetch tool handler: cwd is unused because fetching has no workspace path."""
285
+ return fetch(url, max_chars)
@@ -0,0 +1,295 @@
1
+ """Web search through DeepSeek's Search API.
2
+
3
+ `fetch` answers "what does this page say"; `search` answers "which pages say
4
+ anything about this". The API returns ranked results with a long `summary`
5
+ (600-800 chars) that the model can read directly, so `need_content` stays off:
6
+ opening a page is what `fetch` is for.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import time
13
+ import urllib.error
14
+ import urllib.request
15
+ from collections.abc import Callable
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from .providers import Credential, get_provider
20
+ from .search import SearchProvider
21
+
22
+ DEFAULT_COUNT = 8
23
+ MIN_COUNT, MAX_COUNT = 1, 50
24
+ MAX_QUERY_CHARS = 128 # the API rejects longer queries outright
25
+ MAX_SUMMARY_CHARS = 2_000 # the API promises 600-800, but serves whole pages sometimes
26
+ MAX_CONTENT_CHARS = 4_000
27
+ MAX_RESULTS_CHARS = 12_000
28
+ GOOD_SCORE = 1.5 # rerank_score >= 1.5 means "relevant" per the API docs
29
+ FALLBACK_RESULTS = 3 # never hide everything when no result clears GOOD_SCORE
30
+ DEFAULT_TIMEOUT = 30.0
31
+ RETRY_SLEEPS = (0.5, 1.5)
32
+ RETRY_STATUS = frozenset({408, 429, 500, 502, 503, 504})
33
+ SEARCH_PATH = "/v1/tools/search"
34
+ DEFAULT_BASE_URL = "https://api.deepseek.com"
35
+ CredentialResolver = Callable[[], Credential | None]
36
+
37
+
38
+ class _HttpError(Exception):
39
+ """One failed Search request: `status` 0 means the request never landed."""
40
+
41
+ def __init__(self, status: int, detail: str = "") -> None:
42
+ self.status = status
43
+ self.detail = detail
44
+ super().__init__(detail or f"HTTP {status}")
45
+
46
+
47
+ def skill_path() -> Path:
48
+ """The packaged, on-demand syntax and triage runbook for this tool."""
49
+ return Path(__file__).resolve().parent / "skills" / "websearch" / "SKILL.md"
50
+
51
+
52
+ def _clean(value: Any) -> str:
53
+ return value.strip() if isinstance(value, str) else ""
54
+
55
+
56
+ def _normalized_query(query: Any) -> str:
57
+ text = _clean(query)
58
+ if not text:
59
+ raise ValueError("query must be a non-empty string")
60
+ if len(text) > MAX_QUERY_CHARS:
61
+ raise ValueError(
62
+ f"query is {len(text)} chars; the API accepts at most {MAX_QUERY_CHARS} — shorten it"
63
+ )
64
+ return text
65
+
66
+
67
+ def _limited_count(count: Any) -> int:
68
+ if count is None:
69
+ return DEFAULT_COUNT
70
+ try:
71
+ limit = int(count)
72
+ except (TypeError, ValueError) as e:
73
+ raise ValueError(f"count must be an integer, got {count!r}") from e
74
+ if not MIN_COUNT <= limit <= MAX_COUNT:
75
+ raise ValueError(f"count must be between {MIN_COUNT} and {MAX_COUNT}, got {limit}")
76
+ return limit
77
+
78
+
79
+ def _truncated_question(question: Any) -> str | None:
80
+ """`ori_question` sharpens intent; the API caps it at 128 chars like `query`."""
81
+ text = _clean(question)
82
+ return text[:MAX_QUERY_CHARS] or None
83
+
84
+
85
+ def _endpoint(base_url: str) -> str:
86
+ base = base_url.strip().rstrip("/")
87
+ if base.endswith("/v1"): # providers may already point at the versioned root
88
+ base = base[:-3]
89
+ return base + SEARCH_PATH
90
+
91
+
92
+ def _credentials(
93
+ api_key: str | None,
94
+ base_url: str | None,
95
+ *,
96
+ credential_resolver: CredentialResolver | None = None,
97
+ ) -> tuple[str, str]:
98
+ if api_key or base_url:
99
+ if not api_key:
100
+ raise ValueError("api_key is required when base_url is set")
101
+ return api_key, base_url or DEFAULT_BASE_URL
102
+ if credential_resolver is not None:
103
+ credential = credential_resolver()
104
+ else:
105
+ provider = get_provider("deepseek")
106
+ resolve = getattr(provider, "resolve", None) or getattr(provider, "resolve_env", None)
107
+ credential = resolve() if resolve else None
108
+ if credential is None:
109
+ raise ValueError(
110
+ "no DeepSeek API key for web search — export DEEPSEEK_API_KEY "
111
+ "or configure a credential resolver"
112
+ )
113
+ return credential.api_key, credential.base_url
114
+
115
+
116
+ def _post(url: str, payload: dict[str, Any], api_key: str, timeout: float) -> dict[str, Any]:
117
+ """One JSON POST. Raises _HttpError for anything that is not a 200 with JSON."""
118
+ request = urllib.request.Request(
119
+ url,
120
+ data=json.dumps(payload).encode("utf-8"),
121
+ method="POST",
122
+ headers={
123
+ "Authorization": f"Bearer {api_key}",
124
+ "Content-Type": "application/json",
125
+ },
126
+ )
127
+ try:
128
+ with urllib.request.urlopen(request, timeout=timeout) as response:
129
+ body = response.read().decode("utf-8", "replace")
130
+ except urllib.error.HTTPError as e:
131
+ detail = ""
132
+ try:
133
+ error = json.loads(e.read().decode("utf-8", "replace")).get("error") or {}
134
+ detail = _clean(error.get("message"))
135
+ except (ValueError, OSError, AttributeError):
136
+ pass
137
+ raise _HttpError(e.code, detail) from e
138
+ except (urllib.error.URLError, TimeoutError, OSError) as e:
139
+ raise _HttpError(0, str(e)) from e
140
+ try:
141
+ return json.loads(body or "{}")
142
+ except ValueError as e:
143
+ raise _HttpError(0, f"unreadable response: {body[:200]}") from e
144
+
145
+
146
+ def _retryable(error: _HttpError) -> bool:
147
+ # A dead connection is worth one more try; 402 and other 4xx are not.
148
+ return error.status == 0 or error.status in RETRY_STATUS
149
+
150
+
151
+ def _failed(error: _HttpError) -> str:
152
+ detail = f": {error.detail}" if error.detail else ""
153
+ if error.status == 0:
154
+ return f"error: search request failed{detail}"
155
+ if error.status == 401:
156
+ return "error: DeepSeek API key rejected for web search (401); check the configured key"
157
+ if error.status == 402:
158
+ return "error: DeepSeek balance is empty (402); top up before searching again"
159
+ if error.status == 429:
160
+ return "error: search rate limited (429); wait a moment before searching again"
161
+ if error.status >= 500:
162
+ return f"error: search service unavailable ({error.status}){detail} — try again later"
163
+ return f"error: search rejected ({error.status}){detail}"
164
+
165
+
166
+ def _score(result: dict[str, Any]) -> float:
167
+ value = result.get("rerank_score")
168
+ return float(value) if isinstance(value, (int, float)) else 0.0
169
+
170
+
171
+ def _indent(text: str) -> str:
172
+ return "\n".join(f" {line}" for line in text.splitlines())
173
+
174
+
175
+ def _format_result(index: int, result: dict[str, Any], *, with_content: bool) -> str:
176
+ meta = [f"score {_score(result):.1f}"]
177
+ authority = result.get("authority")
178
+ if isinstance(authority, int) and authority >= 0:
179
+ meta.append(f"authority {authority}")
180
+ if date := _clean(result.get("date"))[:10]:
181
+ meta.append(date)
182
+ if site := _clean(result.get("site_name")):
183
+ meta.append(site)
184
+ title = _clean(result.get("title")) or "(untitled)"
185
+ head = f"{index}. {title} · " + " · ".join(meta)
186
+ lines = [head, f" {_clean(result.get('url'))}"]
187
+ if body := _clean(result.get("summary")) or _clean(result.get("snippet")):
188
+ if len(body) > MAX_SUMMARY_CHARS:
189
+ cut = len(body) - MAX_SUMMARY_CHARS
190
+ body = (
191
+ body[:MAX_SUMMARY_CHARS]
192
+ + f"\n...[summary truncated {cut} chars; fetch the URL for the rest]"
193
+ )
194
+ lines.append(_indent(body))
195
+ if with_content and (content := _clean(result.get("content"))):
196
+ if len(content) > MAX_CONTENT_CHARS:
197
+ cut = len(content) - MAX_CONTENT_CHARS
198
+ content = content[:MAX_CONTENT_CHARS] + f"\n...[content truncated {cut} chars]"
199
+ lines += [" ---", _indent(content)]
200
+ return "\n".join(lines)
201
+
202
+
203
+ def _format(query: str, results: list[Any], *, with_content: bool) -> str:
204
+ usable = [r for r in results if isinstance(r, dict)]
205
+ if not usable:
206
+ return f"no results for {query!r}"
207
+ kept = [r for r in usable if _score(r) >= GOOD_SCORE]
208
+ notes: list[str] = []
209
+ if not kept:
210
+ kept = usable[:FALLBACK_RESULTS]
211
+ notes.append(f"(no result scored >= {GOOD_SCORE}; showing the top {len(kept)})")
212
+ elif len(kept) < len(usable):
213
+ notes.append(f"({len(usable) - len(kept)} lower-scoring results hidden)")
214
+ blocks = [_format_result(i, r, with_content=with_content) for i, r in enumerate(kept, 1)]
215
+ text = "\n\n".join(blocks)
216
+ if len(text) > MAX_RESULTS_CHARS:
217
+ text = text[:MAX_RESULTS_CHARS] + f"\n...[truncated {len(text) - MAX_RESULTS_CHARS} chars]"
218
+ return text + ("\n" + "\n".join(notes) if notes else "")
219
+
220
+
221
+ def search(
222
+ query: str,
223
+ count: int | None = None,
224
+ need_content: bool = False,
225
+ *,
226
+ ori_question: str | None = None,
227
+ api_key: str | None = None,
228
+ base_url: str | None = None,
229
+ timeout: float = DEFAULT_TIMEOUT,
230
+ credential_resolver: CredentialResolver | None = None,
231
+ ) -> str:
232
+ """Search the web and return ranked, model-readable results as text."""
233
+ try:
234
+ text = _normalized_query(query)
235
+ limit = _limited_count(count)
236
+ key, base = _credentials(api_key, base_url, credential_resolver=credential_resolver)
237
+ except (TypeError, ValueError) as e:
238
+ return f"error: {e}"
239
+
240
+ payload: dict[str, Any] = {"query": text, "count": limit}
241
+ if need_content:
242
+ payload["need_content"] = True
243
+ if question := _truncated_question(ori_question):
244
+ payload["ori_question"] = question
245
+
246
+ url = _endpoint(base)
247
+ for attempt in range(len(RETRY_SLEEPS) + 1):
248
+ try:
249
+ body = _post(url, payload, key, timeout)
250
+ break
251
+ except _HttpError as e:
252
+ if attempt < len(RETRY_SLEEPS) and _retryable(e):
253
+ time.sleep(RETRY_SLEEPS[attempt])
254
+ continue
255
+ return _failed(e)
256
+
257
+ results = body.get("results") if isinstance(body, dict) else None
258
+ if not isinstance(results, list) or not results:
259
+ return (
260
+ f"no results for {text!r} — the search found nothing; "
261
+ "broaden the query or drop restrictive operators"
262
+ )
263
+ return _format(text, results, with_content=need_content)
264
+
265
+
266
+ def tool_search(
267
+ _cwd: Path,
268
+ query: str,
269
+ count: int | None = None,
270
+ *,
271
+ user_question: str | None = None,
272
+ ) -> str:
273
+ """search tool handler: cwd is unused because searching has no workspace path."""
274
+ return search(query, count, ori_question=user_question)
275
+
276
+
277
+ class DeepSeekSearchProvider(SearchProvider):
278
+ """DeepSeek Search API with optional host-provided credential resolution."""
279
+
280
+ def __init__(self, credential_resolver: CredentialResolver | None = None) -> None:
281
+ self.credential_resolver = credential_resolver
282
+
283
+ def search(
284
+ self,
285
+ query: str,
286
+ count: int | None = None,
287
+ *,
288
+ user_question: str | None = None,
289
+ ) -> str:
290
+ return search(
291
+ query,
292
+ count,
293
+ ori_question=user_question,
294
+ credential_resolver=self.credential_resolver,
295
+ )
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.3
2
+ Name: agent0-runtime
3
+ Version: 0.1.0
4
+ Summary: A small embeddable agent runtime with tools, sessions, events, and plugins
5
+ Project-URL: Homepage, https://github.com/r1cardohj/agent0-runtime
6
+ Project-URL: Repository, https://github.com/r1cardohj/agent0-runtime
7
+ Project-URL: Issues, https://github.com/r1cardohj/agent0-runtime/issues
8
+ Project-URL: Changelog, https://github.com/r1cardohj/agent0-runtime/blob/main/CHANGELOG.md
9
+ Author-email: r1cardohj <2413302357@qq.com>
10
+ License: MIT
11
+ Keywords: agent,agent-runtime,llm,openai-compatible
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: certifi>=2024
23
+ Requires-Dist: openai>=1.40.0
24
+ Requires-Dist: pillow>=12.3.0
25
+ Requires-Dist: trafilatura<3,>=2.3
26
+ Requires-Dist: urllib3>=2
27
+ Description-Content-Type: text/markdown
28
+
29
+ # agent0-runtime
30
+
31
+ A small, headless, embeddable agent runtime for Python. It provides the model/tool
32
+ loop, OpenAI-compatible Responses backends, tools, sessions, structured events,
33
+ cancellation, lifecycle hooks, and plugins. Terminal UI, persistence formats, and
34
+ application policy belong to consumers.
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ python -m pip install agent0-runtime
40
+ ```
41
+
42
+ Python 3.10 through 3.13 are supported. The package is typed and ships `py.typed`.
43
+
44
+ ## Minimal agent
45
+
46
+ Set `DEEPSEEK_API_KEY` or `KIMI_API_KEY`, then run:
47
+
48
+ ```python
49
+ import asyncio
50
+ from agent0_runtime import Agent, tool
51
+
52
+ @tool("add")
53
+ def add(a: float, b: float) -> str:
54
+ """Add two numbers."""
55
+ return str(a + b)
56
+
57
+ async def main():
58
+ async with Agent.from_env(tools=["add"]) as agent:
59
+ result = await agent.run("Use add to calculate 20 + 22.")
60
+ print(result.text)
61
+
62
+ asyncio.run(main())
63
+ ```
64
+
65
+ `Agent.from_env()` creates and owns the provider client, backend, and matching history
66
+ policy. Exiting the async context closes plugins and network resources. Pass an explicit
67
+ `provider/model` when more than one provider is configured.
68
+
69
+ Hosts with an existing OpenAI-compatible client can share the same backend/history
70
+ assembly without transferring ownership:
71
+
72
+ ```python
73
+ from agent0_runtime import Agent
74
+
75
+ agent = Agent.from_openai(client, model, provider_id=provider_id, tools=registry)
76
+ ```
77
+
78
+ The runtime also includes provider-neutral built-in tools for filesystem, shell, fetch,
79
+ and search. Optional behavior is injected through `BuiltinToolsConfig`; hosts provide
80
+ workspace policy, credentials, persistence, and UI.
81
+
82
+ ## Documentation
83
+
84
+ - [Embedding guide](docs/runtime.md)
85
+ - [Minimal example](examples/minimal_agent.py)
86
+ - [Changelog](CHANGELOG.md)
87
+
88
+ ## Development
89
+
90
+ ```bash
91
+ python -m pip install -e .
92
+ python -m unittest discover -s tests -v
93
+ python -m pip install ruff==0.12.12 build twine
94
+ ruff check .
95
+ ruff format --check .
96
+ python -m build
97
+ python -m twine check --strict dist/*
98
+ ```
99
+
100
+ ## License
101
+
102
+ [MIT](LICENSE)