ainative-agent 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.
- ainative_agent/__init__.py +27 -0
- ainative_agent/_http.py +126 -0
- ainative_agent/agents.py +121 -0
- ainative_agent/billing.py +77 -0
- ainative_agent/chat.py +65 -0
- ainative_agent/classify.py +44 -0
- ainative_agent/client.py +146 -0
- ainative_agent/errors.py +56 -0
- ainative_agent/events.py +91 -0
- ainative_agent/files.py +75 -0
- ainative_agent/graph.py +186 -0
- ainative_agent/memory.py +108 -0
- ainative_agent/registry.py +53 -0
- ainative_agent/tables.py +92 -0
- ainative_agent/tasks.py +87 -0
- ainative_agent/threads.py +91 -0
- ainative_agent/types.py +267 -0
- ainative_agent/vectors.py +64 -0
- ainative_agent-0.1.0.dist-info/METADATA +132 -0
- ainative_agent-0.1.0.dist-info/RECORD +22 -0
- ainative_agent-0.1.0.dist-info/WHEEL +4 -0
- ainative_agent-0.1.0.dist-info/licenses/LICENSE +189 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""ainative-agent -- Python SDK for AINative Agent APIs.
|
|
2
|
+
|
|
3
|
+
Refs #2372
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from ainative_agent.classify import classify_task
|
|
7
|
+
from ainative_agent.client import AINativeClient
|
|
8
|
+
from ainative_agent.errors import (
|
|
9
|
+
AINativeError,
|
|
10
|
+
APIError,
|
|
11
|
+
AuthenticationError,
|
|
12
|
+
NetworkError,
|
|
13
|
+
NotFoundError,
|
|
14
|
+
RateLimitError,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"AINativeClient",
|
|
19
|
+
"classify_task",
|
|
20
|
+
"AINativeError",
|
|
21
|
+
"APIError",
|
|
22
|
+
"AuthenticationError",
|
|
23
|
+
"NetworkError",
|
|
24
|
+
"NotFoundError",
|
|
25
|
+
"RateLimitError",
|
|
26
|
+
]
|
|
27
|
+
__version__ = "0.1.0"
|
ainative_agent/_http.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Base HTTP client with retry logic and auth injection.
|
|
2
|
+
|
|
3
|
+
Refs #2372
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
from typing import Any, Dict, Optional, Type, TypeVar
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from ainative_agent.errors import (
|
|
14
|
+
APIError,
|
|
15
|
+
AuthenticationError,
|
|
16
|
+
NetworkError,
|
|
17
|
+
NotFoundError,
|
|
18
|
+
RateLimitError,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
T = TypeVar("T")
|
|
22
|
+
|
|
23
|
+
_RETRYABLE_STATUS_CODES = {429, 500, 502, 503, 504}
|
|
24
|
+
_MAX_RETRIES = 3
|
|
25
|
+
_BASE_BACKOFF = 1.0 # seconds
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class HTTPClient:
|
|
29
|
+
"""Async HTTP client wrapping httpx.AsyncClient with auth and retry."""
|
|
30
|
+
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
base_url: str = "https://api.ainative.studio",
|
|
34
|
+
api_key: Optional[str] = None,
|
|
35
|
+
token: Optional[str] = None,
|
|
36
|
+
timeout: float = 30.0,
|
|
37
|
+
) -> None:
|
|
38
|
+
self._base_url = base_url.rstrip("/")
|
|
39
|
+
self._api_key = api_key
|
|
40
|
+
self._token = token
|
|
41
|
+
self._client = httpx.AsyncClient(timeout=timeout)
|
|
42
|
+
|
|
43
|
+
def _build_headers(self) -> Dict[str, str]:
|
|
44
|
+
headers: Dict[str, str] = {"Content-Type": "application/json"}
|
|
45
|
+
if self._api_key:
|
|
46
|
+
headers["X-API-Key"] = self._api_key
|
|
47
|
+
elif self._token:
|
|
48
|
+
headers["Authorization"] = f"Bearer {self._token}"
|
|
49
|
+
return headers
|
|
50
|
+
|
|
51
|
+
async def request(
|
|
52
|
+
self,
|
|
53
|
+
method: str,
|
|
54
|
+
path: str,
|
|
55
|
+
json: Optional[Dict[str, Any]] = None,
|
|
56
|
+
params: Optional[Dict[str, str]] = None,
|
|
57
|
+
) -> Any:
|
|
58
|
+
"""Send an HTTP request with automatic retry on transient errors.
|
|
59
|
+
|
|
60
|
+
Retries up to 3 times with exponential backoff on 429 and 5xx responses.
|
|
61
|
+
"""
|
|
62
|
+
url = f"{self._base_url}/api/v1{path}"
|
|
63
|
+
headers = self._build_headers()
|
|
64
|
+
last_error: Optional[Exception] = None
|
|
65
|
+
|
|
66
|
+
for attempt in range(_MAX_RETRIES):
|
|
67
|
+
try:
|
|
68
|
+
response = await self._client.request(
|
|
69
|
+
method,
|
|
70
|
+
url,
|
|
71
|
+
json=json,
|
|
72
|
+
params=params,
|
|
73
|
+
headers=headers,
|
|
74
|
+
)
|
|
75
|
+
except httpx.ConnectError as exc:
|
|
76
|
+
last_error = NetworkError("Connection failed", exc)
|
|
77
|
+
if attempt < _MAX_RETRIES - 1:
|
|
78
|
+
await asyncio.sleep(_BASE_BACKOFF * (2 ** attempt))
|
|
79
|
+
continue
|
|
80
|
+
raise last_error from exc
|
|
81
|
+
except httpx.TimeoutException as exc:
|
|
82
|
+
last_error = NetworkError("Request timed out", exc)
|
|
83
|
+
if attempt < _MAX_RETRIES - 1:
|
|
84
|
+
await asyncio.sleep(_BASE_BACKOFF * (2 ** attempt))
|
|
85
|
+
continue
|
|
86
|
+
raise last_error from exc
|
|
87
|
+
|
|
88
|
+
if response.status_code < 400:
|
|
89
|
+
if response.status_code == 204:
|
|
90
|
+
return None
|
|
91
|
+
return response.json()
|
|
92
|
+
|
|
93
|
+
# Retry on transient errors
|
|
94
|
+
if response.status_code in _RETRYABLE_STATUS_CODES and attempt < _MAX_RETRIES - 1:
|
|
95
|
+
retry_after = response.headers.get("Retry-After")
|
|
96
|
+
delay = float(retry_after) if retry_after else _BASE_BACKOFF * (2 ** attempt)
|
|
97
|
+
await asyncio.sleep(delay)
|
|
98
|
+
continue
|
|
99
|
+
|
|
100
|
+
# Non-retryable or final attempt -- raise
|
|
101
|
+
self._raise_for_status(response)
|
|
102
|
+
|
|
103
|
+
# Should not reach here, but satisfy type checker
|
|
104
|
+
if last_error:
|
|
105
|
+
raise last_error
|
|
106
|
+
raise APIError("Request failed after retries", 500) # pragma: no cover
|
|
107
|
+
|
|
108
|
+
@staticmethod
|
|
109
|
+
def _raise_for_status(response: httpx.Response) -> None:
|
|
110
|
+
"""Map HTTP status codes to typed exceptions."""
|
|
111
|
+
status = response.status_code
|
|
112
|
+
body = response.text
|
|
113
|
+
|
|
114
|
+
if status == 401:
|
|
115
|
+
raise AuthenticationError()
|
|
116
|
+
if status == 404:
|
|
117
|
+
raise NotFoundError(body or "Resource not found")
|
|
118
|
+
if status == 429:
|
|
119
|
+
retry_after_raw = response.headers.get("Retry-After")
|
|
120
|
+
retry_after = int(retry_after_raw) if retry_after_raw else None
|
|
121
|
+
raise RateLimitError(retry_after=retry_after)
|
|
122
|
+
raise APIError(f"API error: {status}", status, body)
|
|
123
|
+
|
|
124
|
+
async def close(self) -> None:
|
|
125
|
+
"""Close the underlying httpx client."""
|
|
126
|
+
await self._client.aclose()
|
ainative_agent/agents.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Agents module (AAP - Agent-Authenticated Party).
|
|
2
|
+
|
|
3
|
+
Refs #2372
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from typing import Any, Dict, List, Optional
|
|
9
|
+
|
|
10
|
+
from ainative_agent._http import HTTPClient
|
|
11
|
+
from ainative_agent.types import AgentKey, AgentRegistration, AuditLog
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class AgentClient:
|
|
15
|
+
"""CRUD and lifecycle operations for registered agents."""
|
|
16
|
+
|
|
17
|
+
def __init__(self, http: HTTPClient) -> None:
|
|
18
|
+
self._http = http
|
|
19
|
+
|
|
20
|
+
async def register(
|
|
21
|
+
self,
|
|
22
|
+
name: str,
|
|
23
|
+
agent_type: str,
|
|
24
|
+
capabilities: List[str],
|
|
25
|
+
*,
|
|
26
|
+
model: Optional[str] = None,
|
|
27
|
+
oversight_level: str = "LOGGING",
|
|
28
|
+
) -> AgentRegistration:
|
|
29
|
+
"""Register a new agent."""
|
|
30
|
+
payload: Dict[str, Any] = {
|
|
31
|
+
"name": name,
|
|
32
|
+
"agent_type": agent_type,
|
|
33
|
+
"capabilities": capabilities,
|
|
34
|
+
"oversight_level": oversight_level,
|
|
35
|
+
}
|
|
36
|
+
if model is not None:
|
|
37
|
+
payload["model"] = model
|
|
38
|
+
data = await self._http.request("POST", "/auth/agents/register", json=payload)
|
|
39
|
+
return AgentRegistration.model_validate(data)
|
|
40
|
+
|
|
41
|
+
async def list(self) -> List[AgentRegistration]:
|
|
42
|
+
"""List all registered agents."""
|
|
43
|
+
data = await self._http.request("GET", "/auth/agents")
|
|
44
|
+
return [AgentRegistration.model_validate(item) for item in data]
|
|
45
|
+
|
|
46
|
+
async def get(self, agent_id: str) -> AgentRegistration:
|
|
47
|
+
"""Get a single agent by ID."""
|
|
48
|
+
data = await self._http.request("GET", f"/auth/agents/{agent_id}")
|
|
49
|
+
return AgentRegistration.model_validate(data)
|
|
50
|
+
|
|
51
|
+
async def update(
|
|
52
|
+
self,
|
|
53
|
+
agent_id: str,
|
|
54
|
+
*,
|
|
55
|
+
name: Optional[str] = None,
|
|
56
|
+
capabilities: Optional[List[str]] = None,
|
|
57
|
+
oversight_level: Optional[str] = None,
|
|
58
|
+
) -> AgentRegistration:
|
|
59
|
+
"""Update an agent's configuration."""
|
|
60
|
+
payload: Dict[str, Any] = {}
|
|
61
|
+
if name is not None:
|
|
62
|
+
payload["name"] = name
|
|
63
|
+
if capabilities is not None:
|
|
64
|
+
payload["capabilities"] = capabilities
|
|
65
|
+
if oversight_level is not None:
|
|
66
|
+
payload["oversight_level"] = oversight_level
|
|
67
|
+
data = await self._http.request("PUT", f"/auth/agents/{agent_id}", json=payload)
|
|
68
|
+
return AgentRegistration.model_validate(data)
|
|
69
|
+
|
|
70
|
+
async def delete(self, agent_id: str) -> None:
|
|
71
|
+
"""Delete an agent."""
|
|
72
|
+
await self._http.request("DELETE", f"/auth/agents/{agent_id}")
|
|
73
|
+
|
|
74
|
+
async def create_token(
|
|
75
|
+
self,
|
|
76
|
+
agent_id: str,
|
|
77
|
+
*,
|
|
78
|
+
capabilities: Optional[List[str]] = None,
|
|
79
|
+
task: Optional[str] = None,
|
|
80
|
+
ttl_minutes: int = 60,
|
|
81
|
+
) -> Dict[str, str]:
|
|
82
|
+
"""Create a scoped JWT token for an agent."""
|
|
83
|
+
payload: Dict[str, Any] = {"ttl_minutes": ttl_minutes}
|
|
84
|
+
if capabilities is not None:
|
|
85
|
+
payload["capabilities"] = capabilities
|
|
86
|
+
if task is not None:
|
|
87
|
+
payload["task"] = task
|
|
88
|
+
data = await self._http.request("POST", f"/auth/agents/{agent_id}/token", json=payload)
|
|
89
|
+
return data
|
|
90
|
+
|
|
91
|
+
async def create_key(
|
|
92
|
+
self,
|
|
93
|
+
agent_id: str,
|
|
94
|
+
name: str,
|
|
95
|
+
scoped_capabilities: List[str],
|
|
96
|
+
) -> Dict[str, str]:
|
|
97
|
+
"""Create a persistent API key for an agent."""
|
|
98
|
+
data = await self._http.request(
|
|
99
|
+
"POST",
|
|
100
|
+
f"/auth/agents/{agent_id}/keys",
|
|
101
|
+
json={"name": name, "scoped_capabilities": scoped_capabilities},
|
|
102
|
+
)
|
|
103
|
+
return data
|
|
104
|
+
|
|
105
|
+
async def list_keys(self, agent_id: str) -> List[AgentKey]:
|
|
106
|
+
"""List all API keys for an agent."""
|
|
107
|
+
data = await self._http.request("GET", f"/auth/agents/{agent_id}/keys")
|
|
108
|
+
return [AgentKey.model_validate(item) for item in data]
|
|
109
|
+
|
|
110
|
+
async def revoke_key(self, agent_id: str, key_id: str) -> None:
|
|
111
|
+
"""Revoke an agent API key."""
|
|
112
|
+
await self._http.request("DELETE", f"/auth/agents/{agent_id}/keys/{key_id}")
|
|
113
|
+
|
|
114
|
+
async def audit(self, agent_id: str) -> List[AuditLog]:
|
|
115
|
+
"""Get audit log for an agent."""
|
|
116
|
+
data = await self._http.request("GET", f"/auth/agents/{agent_id}/audit")
|
|
117
|
+
return [AuditLog.model_validate(item) for item in data]
|
|
118
|
+
|
|
119
|
+
async def capabilities(self) -> List[str]:
|
|
120
|
+
"""List all available agent capabilities."""
|
|
121
|
+
return await self._http.request("GET", "/auth/agents/capabilities")
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Billing module - usage tracking, budgets, alerts, and credits."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
from typing import Any, Callable
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class BillingModule:
|
|
8
|
+
"""Client for billing and usage management APIs."""
|
|
9
|
+
|
|
10
|
+
def __init__(self, request: Callable[..., Any]):
|
|
11
|
+
self._request = request
|
|
12
|
+
|
|
13
|
+
def get_usage(
|
|
14
|
+
self,
|
|
15
|
+
period: str | None = None,
|
|
16
|
+
agent_id: str | None = None,
|
|
17
|
+
agent_type: str | None = None,
|
|
18
|
+
) -> dict[str, Any]:
|
|
19
|
+
"""Get usage breakdown for the current billing period."""
|
|
20
|
+
params: dict[str, str] = {}
|
|
21
|
+
if period:
|
|
22
|
+
params["period"] = period
|
|
23
|
+
if agent_id:
|
|
24
|
+
params["agent_id"] = agent_id
|
|
25
|
+
if agent_type:
|
|
26
|
+
params["agent_type"] = agent_type
|
|
27
|
+
return self._request("GET", "/billing/usage", params=params)
|
|
28
|
+
|
|
29
|
+
def set_budget(
|
|
30
|
+
self,
|
|
31
|
+
agent_id: str,
|
|
32
|
+
limit_usd: float,
|
|
33
|
+
period: str = "monthly",
|
|
34
|
+
) -> dict[str, Any]:
|
|
35
|
+
"""Set a spending budget for an agent."""
|
|
36
|
+
return self._request("POST", "/billing/budgets", json={
|
|
37
|
+
"agent_id": agent_id,
|
|
38
|
+
"limit_usd": limit_usd,
|
|
39
|
+
"period": period,
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
def get_budgets(self) -> list[dict[str, Any]]:
|
|
43
|
+
"""List all active budgets."""
|
|
44
|
+
return self._request("GET", "/billing/budgets")
|
|
45
|
+
|
|
46
|
+
def delete_budget(self, budget_id: str) -> None:
|
|
47
|
+
"""Delete a budget."""
|
|
48
|
+
self._request("DELETE", f"/billing/budgets/{budget_id}")
|
|
49
|
+
|
|
50
|
+
def set_alert(
|
|
51
|
+
self,
|
|
52
|
+
agent_id: str,
|
|
53
|
+
threshold_percent: int,
|
|
54
|
+
email: str,
|
|
55
|
+
) -> dict[str, Any]:
|
|
56
|
+
"""Set a spending alert for an agent."""
|
|
57
|
+
return self._request("POST", "/billing/alerts", json={
|
|
58
|
+
"agent_id": agent_id,
|
|
59
|
+
"threshold_percent": threshold_percent,
|
|
60
|
+
"email": email,
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
def get_alerts(self) -> list[dict[str, Any]]:
|
|
64
|
+
"""List all active alerts."""
|
|
65
|
+
return self._request("GET", "/billing/alerts")
|
|
66
|
+
|
|
67
|
+
def delete_alert(self, alert_id: str) -> None:
|
|
68
|
+
"""Delete an alert."""
|
|
69
|
+
self._request("DELETE", f"/billing/alerts/{alert_id}")
|
|
70
|
+
|
|
71
|
+
def get_dashboard(self) -> dict[str, Any]:
|
|
72
|
+
"""Get the billing dashboard summary."""
|
|
73
|
+
return self._request("GET", "/billing/dashboard")
|
|
74
|
+
|
|
75
|
+
def get_credit_balance(self) -> dict[str, Any]:
|
|
76
|
+
"""Get current credit balance."""
|
|
77
|
+
return self._request("GET", "/billing/credits")
|
ainative_agent/chat.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Chat module with streaming support.
|
|
2
|
+
|
|
3
|
+
Refs #2372
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from typing import Any, AsyncIterator, Dict, List, Optional
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from ainative_agent._http import HTTPClient
|
|
13
|
+
from ainative_agent.errors import APIError, AuthenticationError, NetworkError, RateLimitError
|
|
14
|
+
from ainative_agent.types import ChatChunk, ChatRequest, ChatResponse
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ChatClient:
|
|
18
|
+
"""Chat completions with sync and streaming modes."""
|
|
19
|
+
|
|
20
|
+
def __init__(self, http: HTTPClient) -> None:
|
|
21
|
+
self._http = http
|
|
22
|
+
|
|
23
|
+
async def complete(self, request: ChatRequest) -> ChatResponse:
|
|
24
|
+
"""Non-streaming chat completion."""
|
|
25
|
+
payload = request.model_dump(exclude_none=True)
|
|
26
|
+
payload["stream"] = False
|
|
27
|
+
data = await self._http.request("POST", "/chat/completions", json=payload)
|
|
28
|
+
return ChatResponse.model_validate(data)
|
|
29
|
+
|
|
30
|
+
async def stream(self, request: ChatRequest) -> AsyncIterator[ChatChunk]:
|
|
31
|
+
"""Streaming chat completion via SSE.
|
|
32
|
+
|
|
33
|
+
Yields ChatChunk objects as they arrive from the server.
|
|
34
|
+
"""
|
|
35
|
+
payload = request.model_dump(exclude_none=True)
|
|
36
|
+
payload["stream"] = True
|
|
37
|
+
|
|
38
|
+
url = f"{self._http._base_url}/api/v1/chat/completions"
|
|
39
|
+
headers = self._http._build_headers()
|
|
40
|
+
|
|
41
|
+
try:
|
|
42
|
+
async with httpx.AsyncClient() as client:
|
|
43
|
+
async with client.stream(
|
|
44
|
+
"POST", url, json=payload, headers=headers, timeout=120.0
|
|
45
|
+
) as response:
|
|
46
|
+
if response.status_code == 401:
|
|
47
|
+
raise AuthenticationError()
|
|
48
|
+
if response.status_code == 429:
|
|
49
|
+
raise RateLimitError()
|
|
50
|
+
if response.status_code >= 400:
|
|
51
|
+
body = await response.aread()
|
|
52
|
+
raise APIError(f"API error: {response.status_code}", response.status_code, body.decode())
|
|
53
|
+
|
|
54
|
+
buffer = ""
|
|
55
|
+
async for chunk in response.aiter_text():
|
|
56
|
+
buffer += chunk
|
|
57
|
+
lines = buffer.split("\n")
|
|
58
|
+
buffer = lines.pop()
|
|
59
|
+
|
|
60
|
+
for line in lines:
|
|
61
|
+
line = line.strip()
|
|
62
|
+
if line.startswith("data: ") and line != "data: [DONE]":
|
|
63
|
+
yield ChatChunk.model_validate_json(line[6:])
|
|
64
|
+
except httpx.ConnectError as exc:
|
|
65
|
+
raise NetworkError("Stream connection failed", exc) from exc
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Task classification helper for swarm routing. Ported from agent-sdk-python."""
|
|
2
|
+
|
|
3
|
+
PATTERNS: dict[str, list[str]] = {
|
|
4
|
+
"backend": ["api", "endpoint", "database", "backend", "rest", "graphql", "server", "crud", "migration"],
|
|
5
|
+
"frontend": ["ui", "frontend", "react", "vue", "svelte", "css", "component", "page", "layout"],
|
|
6
|
+
"qa": ["test", "coverage", "qa", "bug", "regression", "e2e", "unit test", "integration test"],
|
|
7
|
+
"devops": ["deploy", "ci/cd", "docker", "kubernetes", "infra", "pipeline", "monitoring"],
|
|
8
|
+
"security": ["auth", "security", "oauth", "vulnerability", "compliance", "encryption", "sso"],
|
|
9
|
+
"architect": ["architecture", "design", "system", "scale", "microservice", "pattern", "refactor"],
|
|
10
|
+
"docs": ["docs", "documentation", "readme", "guide", "tutorial", "api reference"],
|
|
11
|
+
"data": ["data", "analytics", "pipeline", "etl", "warehouse", "dashboard", "metrics"],
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def classify_task(description: str) -> dict[str, object]:
|
|
16
|
+
"""Classify a task description into agent types with confidence score.
|
|
17
|
+
|
|
18
|
+
Returns a dict with ``agent_types`` (list of up to 3 best-fit agent roles)
|
|
19
|
+
and ``confidence`` (0.0–0.95 float).
|
|
20
|
+
"""
|
|
21
|
+
lower = description.lower()
|
|
22
|
+
scores: dict[str, int] = {}
|
|
23
|
+
|
|
24
|
+
for agent_type, keywords in PATTERNS.items():
|
|
25
|
+
scores[agent_type] = sum(1 for k in keywords if k in lower)
|
|
26
|
+
|
|
27
|
+
sorted_scores = sorted(
|
|
28
|
+
[(t, s) for t, s in scores.items() if s > 0],
|
|
29
|
+
key=lambda x: x[1],
|
|
30
|
+
reverse=True,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
if not sorted_scores:
|
|
34
|
+
return {"agent_types": ["architect", "backend", "qa"], "confidence": 0.3}
|
|
35
|
+
|
|
36
|
+
max_score = sorted_scores[0][1]
|
|
37
|
+
threshold = max(1, max_score * 0.5)
|
|
38
|
+
selected = [t for t, s in sorted_scores if s >= threshold][:3]
|
|
39
|
+
|
|
40
|
+
total_keywords = sum(len(v) for v in PATTERNS.values())
|
|
41
|
+
matched = sum(scores.values())
|
|
42
|
+
confidence = min(0.95, round(matched / (total_keywords * 0.1), 2))
|
|
43
|
+
|
|
44
|
+
return {"agent_types": selected, "confidence": confidence}
|
ainative_agent/client.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""AINativeClient -- main entry point for the Python SDK.
|
|
2
|
+
|
|
3
|
+
Refs #2372
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from typing import Any, Optional
|
|
9
|
+
|
|
10
|
+
from ainative_agent._http import HTTPClient
|
|
11
|
+
from ainative_agent.agents import AgentClient
|
|
12
|
+
from ainative_agent.chat import ChatClient
|
|
13
|
+
from ainative_agent.events import EventClient
|
|
14
|
+
from ainative_agent.files import FileClient
|
|
15
|
+
from ainative_agent.graph import GraphClient
|
|
16
|
+
from ainative_agent.memory import MemoryClient
|
|
17
|
+
from ainative_agent.tables import TableClient
|
|
18
|
+
from ainative_agent.tasks import TaskClient
|
|
19
|
+
from ainative_agent.threads import ThreadClient
|
|
20
|
+
from ainative_agent.vectors import VectorClient
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class AINativeClient:
|
|
24
|
+
"""Async client for all AINative Agent APIs.
|
|
25
|
+
|
|
26
|
+
Usage::
|
|
27
|
+
|
|
28
|
+
async with AINativeClient(api_key="sk-...") as client:
|
|
29
|
+
agents = await client.agents.list()
|
|
30
|
+
memories = await client.memory.recall(query="project status")
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
api_key: Optional[str] = None,
|
|
36
|
+
*,
|
|
37
|
+
token: Optional[str] = None,
|
|
38
|
+
base_url: str = "https://api.ainative.studio",
|
|
39
|
+
timeout: float = 30.0,
|
|
40
|
+
) -> None:
|
|
41
|
+
self._http = HTTPClient(
|
|
42
|
+
base_url=base_url,
|
|
43
|
+
api_key=api_key,
|
|
44
|
+
token=token,
|
|
45
|
+
timeout=timeout,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
self._agents: Optional[AgentClient] = None
|
|
49
|
+
self._tasks: Optional[TaskClient] = None
|
|
50
|
+
self._memory: Optional[MemoryClient] = None
|
|
51
|
+
self._graph: Optional[GraphClient] = None
|
|
52
|
+
self._vectors: Optional[VectorClient] = None
|
|
53
|
+
self._files: Optional[FileClient] = None
|
|
54
|
+
self._tables: Optional[TableClient] = None
|
|
55
|
+
self._chat: Optional[ChatClient] = None
|
|
56
|
+
self._threads: Optional[ThreadClient] = None
|
|
57
|
+
self._events: Optional[EventClient] = None
|
|
58
|
+
|
|
59
|
+
# Store config for EventClient
|
|
60
|
+
self._base_url = base_url
|
|
61
|
+
self._api_key = api_key
|
|
62
|
+
self._token = token
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def agents(self) -> AgentClient:
|
|
66
|
+
"""Agent registration, keys, and audit."""
|
|
67
|
+
if self._agents is None:
|
|
68
|
+
self._agents = AgentClient(self._http)
|
|
69
|
+
return self._agents
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def tasks(self) -> TaskClient:
|
|
73
|
+
"""Swarm task submission and polling."""
|
|
74
|
+
if self._tasks is None:
|
|
75
|
+
self._tasks = TaskClient(self._http)
|
|
76
|
+
return self._tasks
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def memory(self) -> MemoryClient:
|
|
80
|
+
"""ZeroMemory: remember, recall, forget, reflect."""
|
|
81
|
+
if self._memory is None:
|
|
82
|
+
self._memory = MemoryClient(self._http)
|
|
83
|
+
return self._memory
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def graph(self) -> GraphClient:
|
|
87
|
+
"""Context graph: entities, edges, GraphRAG, ontology."""
|
|
88
|
+
if self._graph is None:
|
|
89
|
+
self._graph = GraphClient(self._http)
|
|
90
|
+
return self._graph
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def vectors(self) -> VectorClient:
|
|
94
|
+
"""Vector embeddings: upsert, search, delete."""
|
|
95
|
+
if self._vectors is None:
|
|
96
|
+
self._vectors = VectorClient(self._http)
|
|
97
|
+
return self._vectors
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def files(self) -> FileClient:
|
|
101
|
+
"""File storage: upload, download, presigned URLs."""
|
|
102
|
+
if self._files is None:
|
|
103
|
+
self._files = FileClient(self._http)
|
|
104
|
+
return self._files
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def tables(self) -> TableClient:
|
|
108
|
+
"""NoSQL tables: create, query, insert, update."""
|
|
109
|
+
if self._tables is None:
|
|
110
|
+
self._tables = TableClient(self._http)
|
|
111
|
+
return self._tables
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def chat(self) -> ChatClient:
|
|
115
|
+
"""Chat completions with streaming."""
|
|
116
|
+
if self._chat is None:
|
|
117
|
+
self._chat = ChatClient(self._http)
|
|
118
|
+
return self._chat
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def threads(self) -> ThreadClient:
|
|
122
|
+
"""Conversation threads."""
|
|
123
|
+
if self._threads is None:
|
|
124
|
+
self._threads = ThreadClient(self._http)
|
|
125
|
+
return self._threads
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def events(self) -> EventClient:
|
|
129
|
+
"""Real-time WebSocket events."""
|
|
130
|
+
if self._events is None:
|
|
131
|
+
self._events = EventClient(
|
|
132
|
+
base_url=self._base_url,
|
|
133
|
+
api_key=self._api_key,
|
|
134
|
+
token=self._token,
|
|
135
|
+
)
|
|
136
|
+
return self._events
|
|
137
|
+
|
|
138
|
+
async def close(self) -> None:
|
|
139
|
+
"""Close the underlying HTTP client."""
|
|
140
|
+
await self._http.close()
|
|
141
|
+
|
|
142
|
+
async def __aenter__(self) -> AINativeClient:
|
|
143
|
+
return self
|
|
144
|
+
|
|
145
|
+
async def __aexit__(self, *args: Any) -> None:
|
|
146
|
+
await self.close()
|
ainative_agent/errors.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""AINative SDK error types.
|
|
2
|
+
|
|
3
|
+
Refs #2372
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class AINativeError(Exception):
|
|
10
|
+
"""Base exception for all AINative SDK errors."""
|
|
11
|
+
|
|
12
|
+
def __init__(self, message: str) -> None:
|
|
13
|
+
super().__init__(message)
|
|
14
|
+
self.message = message
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class APIError(AINativeError):
|
|
18
|
+
"""Raised on non-2xx API responses."""
|
|
19
|
+
|
|
20
|
+
def __init__(self, message: str, status_code: int, body: str | None = None) -> None:
|
|
21
|
+
super().__init__(message)
|
|
22
|
+
self.status_code = status_code
|
|
23
|
+
self.body = body
|
|
24
|
+
|
|
25
|
+
def __repr__(self) -> str:
|
|
26
|
+
return f"APIError(status_code={self.status_code}, message={self.message!r})"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class AuthenticationError(APIError):
|
|
30
|
+
"""Raised on 401 responses."""
|
|
31
|
+
|
|
32
|
+
def __init__(self, message: str = "Invalid or expired credentials") -> None:
|
|
33
|
+
super().__init__(message, 401)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class NotFoundError(APIError):
|
|
37
|
+
"""Raised on 404 responses."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, message: str = "Resource not found") -> None:
|
|
40
|
+
super().__init__(message, 404)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class RateLimitError(APIError):
|
|
44
|
+
"""Raised on 429 responses."""
|
|
45
|
+
|
|
46
|
+
def __init__(self, message: str = "Rate limit exceeded", retry_after: int | None = None) -> None:
|
|
47
|
+
super().__init__(message, 429)
|
|
48
|
+
self.retry_after = retry_after
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class NetworkError(AINativeError):
|
|
52
|
+
"""Raised on connection failures."""
|
|
53
|
+
|
|
54
|
+
def __init__(self, message: str, cause: Exception | None = None) -> None:
|
|
55
|
+
super().__init__(message)
|
|
56
|
+
self.__cause__ = cause
|