trc-8004-sdk 0.1.0b1__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.
sdk/__init__.py ADDED
@@ -0,0 +1,123 @@
1
+ """
2
+ TRC-8004 Agent SDK
3
+
4
+ 去中心化 Agent 协作的 Python SDK,支持:
5
+ - 身份注册与元数据管理 (IdentityRegistry)
6
+ - 验证请求与响应 (ValidationRegistry)
7
+ - 信誉反馈提交 (ReputationRegistry)
8
+ - A2A 协议客户端
9
+
10
+ Quick Start:
11
+ >>> from sdk import AgentSDK
12
+ >>> sdk = AgentSDK(
13
+ ... private_key="your_hex_private_key",
14
+ ... rpc_url="https://nile.trongrid.io",
15
+ ... network="tron:nile",
16
+ ... )
17
+ >>> tx_id = sdk.register_agent(token_uri="https://example.com/agent.json")
18
+ """
19
+
20
+ from .agent_sdk import AgentSDK, SDKConfig
21
+ from .contract_adapter import ContractAdapter, DummyContractAdapter, TronContractAdapter
22
+ from .signer import Signer, SimpleSigner, TronSigner
23
+ from .exceptions import (
24
+ SDKError,
25
+ ConfigurationError,
26
+ MissingContractAddressError,
27
+ InvalidPrivateKeyError,
28
+ ChainIdResolutionError,
29
+ NetworkError,
30
+ RPCError,
31
+ TimeoutError,
32
+ RetryExhaustedError,
33
+ ContractError,
34
+ ContractCallError,
35
+ ContractFunctionNotFoundError,
36
+ TransactionFailedError,
37
+ InsufficientEnergyError,
38
+ SignatureError,
39
+ InvalidSignatureError,
40
+ SignerNotAvailableError,
41
+ DataError,
42
+ InvalidAddressError,
43
+ InvalidHashError,
44
+ SerializationError,
45
+ DataLoadError,
46
+ ValidationError,
47
+ RequestHashMismatchError,
48
+ FeedbackAuthExpiredError,
49
+ FeedbackAuthInvalidError,
50
+ )
51
+ from .retry import (
52
+ RetryConfig,
53
+ DEFAULT_RETRY_CONFIG,
54
+ AGGRESSIVE_RETRY_CONFIG,
55
+ CONSERVATIVE_RETRY_CONFIG,
56
+ NO_RETRY_CONFIG,
57
+ retry,
58
+ retry_async,
59
+ RetryContext,
60
+ )
61
+ from .client import AgentClient
62
+ from .agent_protocol_client import AgentProtocolClient
63
+ from .chain_utils import fetch_event_logs, fetch_trongrid_events, load_request_data, normalize_hash
64
+
65
+ __version__ = "0.1.0"
66
+
67
+ __all__ = [
68
+ # Core
69
+ "AgentSDK",
70
+ "SDKConfig",
71
+ # Adapters
72
+ "ContractAdapter",
73
+ "DummyContractAdapter",
74
+ "TronContractAdapter",
75
+ # Signers
76
+ "Signer",
77
+ "SimpleSigner",
78
+ "TronSigner",
79
+ # Exceptions
80
+ "SDKError",
81
+ "ConfigurationError",
82
+ "MissingContractAddressError",
83
+ "InvalidPrivateKeyError",
84
+ "ChainIdResolutionError",
85
+ "NetworkError",
86
+ "RPCError",
87
+ "TimeoutError",
88
+ "RetryExhaustedError",
89
+ "ContractError",
90
+ "ContractCallError",
91
+ "ContractFunctionNotFoundError",
92
+ "TransactionFailedError",
93
+ "InsufficientEnergyError",
94
+ "SignatureError",
95
+ "InvalidSignatureError",
96
+ "SignerNotAvailableError",
97
+ "DataError",
98
+ "InvalidAddressError",
99
+ "InvalidHashError",
100
+ "SerializationError",
101
+ "DataLoadError",
102
+ "ValidationError",
103
+ "RequestHashMismatchError",
104
+ "FeedbackAuthExpiredError",
105
+ "FeedbackAuthInvalidError",
106
+ # Retry
107
+ "RetryConfig",
108
+ "DEFAULT_RETRY_CONFIG",
109
+ "AGGRESSIVE_RETRY_CONFIG",
110
+ "CONSERVATIVE_RETRY_CONFIG",
111
+ "NO_RETRY_CONFIG",
112
+ "retry",
113
+ "retry_async",
114
+ "RetryContext",
115
+ # Clients
116
+ "AgentClient",
117
+ "AgentProtocolClient",
118
+ # Utils
119
+ "fetch_event_logs",
120
+ "fetch_trongrid_events",
121
+ "load_request_data",
122
+ "normalize_hash",
123
+ ]
@@ -0,0 +1,180 @@
1
+ """
2
+ TRC-8004 SDK Agent Protocol 客户端模块
3
+
4
+ 提供符合 Agent Protocol 标准的 HTTP 客户端。
5
+
6
+ Agent Protocol 是一个开放标准,定义了 AI Agent 的通用接口:
7
+ - 创建任务 (Task)
8
+ - 执行步骤 (Step)
9
+ - 获取结果
10
+
11
+ Classes:
12
+ AgentProtocolClient: Agent Protocol 标准客户端
13
+
14
+ Reference:
15
+ https://agentprotocol.ai/
16
+
17
+ Example:
18
+ >>> from sdk.agent_protocol_client import AgentProtocolClient
19
+ >>> client = AgentProtocolClient(base_url="https://agent.example.com")
20
+ >>> result = client.run({"skill": "quote", "params": {...}})
21
+ """
22
+
23
+ import json
24
+ from typing import Any, Dict, Optional
25
+
26
+ import httpx
27
+
28
+
29
+ class AgentProtocolClient:
30
+ """
31
+ Agent Protocol 标准客户端。
32
+
33
+ 实现 Agent Protocol 规范的核心接口:
34
+ - POST /ap/v1/agent/tasks: 创建任务
35
+ - POST /ap/v1/agent/tasks/{task_id}/steps: 执行步骤
36
+
37
+ Attributes:
38
+ base_url: Agent 服务基础 URL
39
+ timeout: HTTP 请求超时时间
40
+
41
+ Args:
42
+ base_url: Agent 服务基础 URL
43
+ timeout: HTTP 请求超时时间(秒),默认 10.0
44
+
45
+ Example:
46
+ >>> client = AgentProtocolClient(
47
+ ... base_url="https://agent.example.com",
48
+ ... timeout=30.0,
49
+ ... )
50
+ >>> task = client.create_task()
51
+ >>> result = client.execute_step(task["task_id"], '{"action": "quote"}')
52
+
53
+ Note:
54
+ Agent Protocol 是一个开放标准,旨在提供 AI Agent 的通用接口。
55
+ 更多信息请参考: https://agentprotocol.ai/
56
+ """
57
+
58
+ def __init__(self, base_url: str, timeout: float = 10.0) -> None:
59
+ """
60
+ 初始化 Agent Protocol 客户端。
61
+
62
+ Args:
63
+ base_url: Agent 服务基础 URL(如 https://agent.example.com)
64
+ timeout: HTTP 请求超时时间(秒)
65
+ """
66
+ self.base_url = base_url.rstrip("/")
67
+ self.timeout = timeout
68
+
69
+ def create_task(self, input_text: Optional[str] = None) -> Dict[str, Any]:
70
+ """
71
+ 创建新任务。
72
+
73
+ 向 Agent 发送创建任务请求,获取任务 ID。
74
+
75
+ Args:
76
+ input_text: 可选的初始输入文本
77
+
78
+ Returns:
79
+ 任务信息字典,包含 task_id 等字段
80
+
81
+ Raises:
82
+ httpx.HTTPStatusError: HTTP 请求失败
83
+ httpx.TimeoutException: 请求超时
84
+
85
+ Example:
86
+ >>> task = client.create_task()
87
+ >>> print(task["task_id"])
88
+ 'abc123-...'
89
+ >>>
90
+ >>> # 带初始输入
91
+ >>> task = client.create_task(input_text="Hello")
92
+ """
93
+ payload: Dict[str, Any] = {}
94
+ if input_text is not None:
95
+ payload["input"] = input_text
96
+
97
+ with httpx.Client(timeout=self.timeout) as client:
98
+ resp = client.post(f"{self.base_url}/ap/v1/agent/tasks", json=payload)
99
+ resp.raise_for_status()
100
+ return resp.json()
101
+
102
+ def execute_step(
103
+ self,
104
+ task_id: str,
105
+ input_text: Optional[str] = None,
106
+ ) -> Dict[str, Any]:
107
+ """
108
+ 执行任务步骤。
109
+
110
+ 向指定任务发送执行请求,获取步骤结果。
111
+
112
+ Args:
113
+ task_id: 任务 ID(从 create_task 获取)
114
+ input_text: 步骤输入文本(通常是 JSON 字符串)
115
+
116
+ Returns:
117
+ 步骤结果字典,包含 output、status 等字段
118
+
119
+ Raises:
120
+ httpx.HTTPStatusError: HTTP 请求失败
121
+ httpx.TimeoutException: 请求超时
122
+
123
+ Example:
124
+ >>> result = client.execute_step(
125
+ ... task_id="abc123",
126
+ ... input_text='{"action": "quote", "params": {...}}',
127
+ ... )
128
+ >>> print(result["output"])
129
+ """
130
+ payload: Dict[str, Any] = {}
131
+ if input_text is not None:
132
+ payload["input"] = input_text
133
+
134
+ with httpx.Client(timeout=self.timeout) as client:
135
+ resp = client.post(
136
+ f"{self.base_url}/ap/v1/agent/tasks/{task_id}/steps",
137
+ json=payload,
138
+ )
139
+ resp.raise_for_status()
140
+ return resp.json()
141
+
142
+ def run(self, input_payload: Dict[str, Any]) -> Dict[str, Any]:
143
+ """
144
+ 一键运行:创建任务并执行。
145
+
146
+ 便捷方法,自动创建任务并执行一个步骤。
147
+
148
+ Args:
149
+ input_payload: 输入数据字典,将被序列化为 JSON
150
+
151
+ Returns:
152
+ 步骤执行结果
153
+
154
+ Raises:
155
+ ValueError: 任务创建失败(无 task_id)
156
+ httpx.HTTPStatusError: HTTP 请求失败
157
+
158
+ Example:
159
+ >>> result = client.run({
160
+ ... "skill": "market_order",
161
+ ... "params": {
162
+ ... "asset": "TRX/USDT",
163
+ ... "amount": 100,
164
+ ... },
165
+ ... })
166
+ >>> print(result["output"])
167
+
168
+ Note:
169
+ 此方法适用于简单的单步骤任务。
170
+ 对于复杂的多步骤任务,请分别调用 create_task 和 execute_step。
171
+ """
172
+ # 创建任务
173
+ task = self.create_task()
174
+ task_id = task.get("task_id")
175
+ if not task_id:
176
+ raise ValueError("AGENT_TASK_ID_MISSING")
177
+
178
+ # 序列化输入并执行
179
+ input_text = json.dumps(input_payload, ensure_ascii=False)
180
+ return self.execute_step(task_id, input_text)