reglow-agent-client 0.1.1__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,20 @@
1
+ """reglow-agent-client —— Reglow Agent 薄 SDK(Python)"""
2
+ from .client import AgentClient
3
+ from .errors import ApiError
4
+ from .models import AgentDefinition, AgentRun, AgentWorkflow, Approval, Page, RunEvent
5
+ from .studio_bridge import SdkStudioAgentBridge, StudioSnapshot
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ __all__ = [
10
+ "AgentClient",
11
+ "AgentDefinition",
12
+ "AgentRun",
13
+ "AgentWorkflow",
14
+ "ApiError",
15
+ "Approval",
16
+ "Page",
17
+ "RunEvent",
18
+ "SdkStudioAgentBridge",
19
+ "StudioSnapshot",
20
+ ]
@@ -0,0 +1,558 @@
1
+ """Reglow Agent 薄 SDK(Python)
2
+
3
+ 原则:只做 DTO / HTTP / 错误映射 / 幂等请求重试;不实现业务逻辑、不缓存状态。
4
+ 默认管理端前缀 `/admin/api/v1/agent`,所有请求带 `X-Tenant-Id` 与可选 `Authorization`。
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from typing import Any, Iterator
9
+
10
+ import httpx
11
+
12
+ from .errors import ApiError
13
+ from .models import AgentDefinition, AgentRun, AgentWorkflow, Approval, Page, RunEvent
14
+
15
+ DEFAULT_PREFIX = "/admin/api/v1/agent"
16
+
17
+
18
+ class AgentClient:
19
+ def __init__(
20
+ self,
21
+ base_url: str,
22
+ *,
23
+ tenant_id: int = 0,
24
+ token: str | None = None,
25
+ timeout: float = 30.0,
26
+ admin_prefix: str = DEFAULT_PREFIX,
27
+ headers: dict[str, str] | None = None,
28
+ transport: httpx.BaseTransport | None = None,
29
+ ):
30
+ self.base_url = base_url.rstrip("/")
31
+ self.tenant_id = tenant_id
32
+ self.admin_prefix = admin_prefix.rstrip("/")
33
+
34
+ default_headers: dict[str, str] = {"Accept": "application/json"}
35
+ if tenant_id is not None:
36
+ default_headers["X-Tenant-Id"] = str(tenant_id)
37
+ if token:
38
+ default_headers["Authorization"] = f"Bearer {token}"
39
+ if headers:
40
+ default_headers.update(headers)
41
+
42
+ self._http = httpx.Client(
43
+ base_url=self.base_url,
44
+ headers=default_headers,
45
+ timeout=timeout,
46
+ transport=transport,
47
+ )
48
+
49
+ self.definitions = _Definitions(self)
50
+ self.tools = _Tools(self)
51
+ self.workflows = _Workflows(self)
52
+ self.runs = _Runs(self)
53
+ self.approvals = _Approvals(self)
54
+ self.sessions = _Sessions(self)
55
+ self.memory = _Memory(self)
56
+ self.blackboard = _Blackboard(self)
57
+ self.knowledge = _Knowledge(self)
58
+ self.eval = _Eval(self)
59
+ self.feedback = _Feedback(self)
60
+ self.audit = _Audit(self)
61
+
62
+ # ─── 基础设施 ───
63
+
64
+ def close(self) -> None:
65
+ self._http.close()
66
+
67
+ def __enter__(self) -> "AgentClient":
68
+ return self
69
+
70
+ def __exit__(self, *args) -> None:
71
+ self.close()
72
+
73
+ def _request(
74
+ self,
75
+ method: str,
76
+ path: str,
77
+ *,
78
+ params: dict | None = None,
79
+ json: dict | None = None,
80
+ ) -> Any:
81
+ query = {k: v for k, v in (params or {}).items() if v is not None}
82
+ response = self._http.request(
83
+ method, f"{self.admin_prefix}{path}", params=query or None, json=json
84
+ )
85
+ payload: dict | None
86
+ try:
87
+ payload = response.json()
88
+ except ValueError:
89
+ payload = None
90
+
91
+ if response.status_code >= 400 or (
92
+ isinstance(payload, dict) and payload.get("success") is False
93
+ ):
94
+ code = payload.get("code") if isinstance(payload, dict) else response.status_code
95
+ message = (
96
+ payload.get("msg") if isinstance(payload, dict) else response.text
97
+ ) or f"HTTP {response.status_code}"
98
+ raise ApiError(int(code or response.status_code), str(message), response.status_code, payload)
99
+
100
+ if payload is None:
101
+ return None
102
+ return payload.get("data")
103
+
104
+
105
+ class _Group:
106
+ def __init__(self, client: AgentClient):
107
+ self._c = client
108
+
109
+
110
+ class _Definitions(_Group):
111
+ def list(
112
+ self,
113
+ *,
114
+ page: int = 1,
115
+ size: int = 10,
116
+ keyword: str | None = None,
117
+ status: str | None = None,
118
+ kind: str | None = None,
119
+ ) -> Page:
120
+ data = self._c._request(
121
+ "GET",
122
+ "/definitions",
123
+ params={"page": page, "size": size, "keyword": keyword, "status": status, "kind": kind},
124
+ )
125
+ return Page.from_api(data, cast=AgentDefinition.from_api)
126
+
127
+ def create(
128
+ self,
129
+ *,
130
+ key: str,
131
+ name: str,
132
+ spec: dict,
133
+ kind: str = "conversational",
134
+ description: str | None = None,
135
+ eval_suite: str | None = None,
136
+ ) -> AgentDefinition:
137
+ data = self._c._request(
138
+ "POST",
139
+ "/definitions",
140
+ json={
141
+ "key": key,
142
+ "name": name,
143
+ "kind": kind,
144
+ "description": description,
145
+ "spec": spec,
146
+ "eval_suite": eval_suite,
147
+ },
148
+ )
149
+ return AgentDefinition.from_api(data or {})
150
+
151
+ def get(self, definition_id: int) -> AgentDefinition:
152
+ return AgentDefinition.from_api(
153
+ self._c._request("GET", f"/definitions/{definition_id}") or {}
154
+ )
155
+
156
+ def update(self, definition_id: int, **fields) -> AgentDefinition:
157
+ data = self._c._request("PUT", f"/definitions/{definition_id}", json=fields)
158
+ return AgentDefinition.from_api(data or {})
159
+
160
+ def publish(self, definition_id: int, *, change_note: str | None = None) -> AgentDefinition:
161
+ data = self._c._request(
162
+ "POST", f"/definitions/{definition_id}/publish", json={"change_note": change_note}
163
+ )
164
+ return AgentDefinition.from_api(data or {})
165
+
166
+ def versions(self, definition_id: int) -> list[dict]:
167
+ return self._c._request("GET", f"/definitions/{definition_id}/versions") or []
168
+
169
+ def delete(self, definition_id: int) -> None:
170
+ self._c._request("DELETE", f"/definitions/{definition_id}")
171
+
172
+
173
+ class _Tools(_Group):
174
+ def list(self, *, page: int = 1, size: int = 10, keyword: str | None = None) -> Page:
175
+ return Page.from_api(
176
+ self._c._request(
177
+ "GET", "/tools", params={"page": page, "size": size, "keyword": keyword}
178
+ )
179
+ )
180
+
181
+ def register(self, **payload) -> dict:
182
+ return self._c._request("POST", "/tools", json=payload) or {}
183
+
184
+ def update(self, tool_id: int, **fields) -> dict:
185
+ return self._c._request("PUT", f"/tools/{tool_id}", json=fields) or {}
186
+
187
+ def delete(self, tool_id: int) -> None:
188
+ self._c._request("DELETE", f"/tools/{tool_id}")
189
+
190
+
191
+ class _Workflows(_Group):
192
+ def list(self, *, page: int = 1, size: int = 10, keyword: str | None = None) -> Page:
193
+ data = self._c._request(
194
+ "GET", "/workflows", params={"page": page, "size": size, "keyword": keyword}
195
+ )
196
+ return Page.from_api(data, cast=AgentWorkflow.from_api)
197
+
198
+ def create(self, *, key: str, name: str, spec: dict, mode: str = "dag") -> AgentWorkflow:
199
+ data = self._c._request(
200
+ "POST", "/workflows", json={"key": key, "name": name, "mode": mode, "spec": spec}
201
+ )
202
+ return AgentWorkflow.from_api(data or {})
203
+
204
+ def get(self, workflow_id: int) -> AgentWorkflow:
205
+ return AgentWorkflow.from_api(
206
+ self._c._request("GET", f"/workflows/{workflow_id}") or {}
207
+ )
208
+
209
+ def publish(self, workflow_id: int, *, change_note: str | None = None) -> AgentWorkflow:
210
+ data = self._c._request(
211
+ "POST", f"/workflows/{workflow_id}/publish", json={"change_note": change_note}
212
+ )
213
+ return AgentWorkflow.from_api(data or {})
214
+
215
+ def update(self, workflow_id: int, **fields) -> AgentWorkflow:
216
+ data = self._c._request("PUT", f"/workflows/{workflow_id}", json=fields)
217
+ return AgentWorkflow.from_api(data or {})
218
+
219
+ def delete(self, workflow_id: int) -> None:
220
+ self._c._request("DELETE", f"/workflows/{workflow_id}")
221
+
222
+ def versions(self, workflow_id: int) -> list[dict]:
223
+ return self._c._request("GET", f"/workflows/{workflow_id}/versions") or []
224
+
225
+ def run(
226
+ self,
227
+ workflow_id: int,
228
+ *,
229
+ input: dict | None = None,
230
+ idempotency_key: str | None = None,
231
+ worker: str = "sdk-worker",
232
+ ) -> AgentRun:
233
+ data = self._c._request(
234
+ "POST",
235
+ f"/workflows/{workflow_id}/run",
236
+ json={"input": input or {}, "idempotency_key": idempotency_key, "worker": worker},
237
+ )
238
+ return AgentRun.from_api(data or {})
239
+
240
+
241
+ class _Runs(_Group):
242
+ def create(
243
+ self,
244
+ *,
245
+ agent_key: str | None = None,
246
+ agent_id: int | None = None,
247
+ workflow_id: int | None = None,
248
+ input: dict | None = None,
249
+ trigger_type: str = "api",
250
+ idempotency_key: str | None = None,
251
+ budget: dict | None = None,
252
+ ) -> AgentRun:
253
+ data = self._c._request(
254
+ "POST",
255
+ "/runs",
256
+ json={
257
+ "agent_key": agent_key,
258
+ "agent_id": agent_id,
259
+ "workflow_id": workflow_id,
260
+ "input": input or {},
261
+ "trigger_type": trigger_type,
262
+ "idempotency_key": idempotency_key,
263
+ "budget": budget,
264
+ },
265
+ )
266
+ return AgentRun.from_api(data or {})
267
+
268
+ def get(self, run_id: int) -> AgentRun:
269
+ return AgentRun.from_api(self._c._request("GET", f"/runs/{run_id}") or {})
270
+
271
+ def list(
272
+ self,
273
+ *,
274
+ page: int = 1,
275
+ size: int = 10,
276
+ status: str | None = None,
277
+ agent_id: int | None = None,
278
+ ) -> Page:
279
+ data = self._c._request(
280
+ "GET",
281
+ "/runs",
282
+ params={"page": page, "size": size, "status": status, "agent_id": agent_id},
283
+ )
284
+ return Page.from_api(data, cast=AgentRun.from_api)
285
+
286
+ def cancel(self, run_id: int) -> AgentRun:
287
+ return AgentRun.from_api(self._c._request("POST", f"/runs/{run_id}/cancel") or {})
288
+
289
+ def events(self, run_id: int, *, after_seq: int = 0, limit: int = 200) -> list[RunEvent]:
290
+ data = self._c._request(
291
+ "GET",
292
+ f"/runs/{run_id}/events",
293
+ params={"after_seq": after_seq, "limit": limit},
294
+ )
295
+ return [RunEvent.from_api(item) for item in (data or [])]
296
+
297
+ def iter_events(
298
+ self, run_id: int, *, after_seq: int = 0, page_size: int = 200
299
+ ) -> Iterator[RunEvent]:
300
+ cursor = after_seq
301
+ while True:
302
+ batch = self.events(run_id, after_seq=cursor, limit=page_size)
303
+ if not batch:
304
+ return
305
+ for event in batch:
306
+ cursor = event.seq
307
+ yield event
308
+ if len(batch) < page_size:
309
+ return
310
+
311
+ def timeline(self, run_id: int) -> dict:
312
+ return self._c._request("GET", f"/runs/{run_id}/timeline") or {}
313
+
314
+ def diff(self, run_id: int, against_id: int) -> dict:
315
+ return (
316
+ self._c._request(
317
+ "GET", f"/runs/{run_id}/diff", params={"against_id": against_id}
318
+ )
319
+ or {}
320
+ )
321
+
322
+ def resume(self, run_id: int, *, worker: str = "sdk-worker") -> AgentRun:
323
+ data = self._c._request(
324
+ "POST", f"/runs/{run_id}/resume", params={"worker": worker}
325
+ )
326
+ return AgentRun.from_api(data or {})
327
+
328
+ def compensate(self, run_id: int) -> AgentRun:
329
+ return AgentRun.from_api(self._c._request("POST", f"/runs/{run_id}/compensate") or {})
330
+
331
+ def replay(
332
+ self, run_id: int, *, allow_side_effects: bool = False, worker: str = "sdk-worker"
333
+ ) -> AgentRun:
334
+ data = self._c._request(
335
+ "POST",
336
+ f"/runs/{run_id}/replay",
337
+ params={"allow_side_effects": allow_side_effects, "worker": worker},
338
+ )
339
+ return AgentRun.from_api(data or {})
340
+
341
+
342
+ class _Approvals(_Group):
343
+ def list(self, *, status: str = "pending", page: int = 1, size: int = 10, run_id: int | None = None) -> Page:
344
+ data = self._c._request(
345
+ "GET", "/approvals", params={"status": status, "page": page, "size": size, "run_id": run_id}
346
+ )
347
+ return Page.from_api(data, cast=Approval.from_api)
348
+
349
+ def approve(self, approval_id: int, *, comment: str | None = None) -> dict:
350
+ return self._c._request(
351
+ "POST", f"/approvals/{approval_id}/approve", json={"comment": comment}
352
+ ) or {}
353
+
354
+ def reject(self, approval_id: int, *, comment: str | None = None) -> dict:
355
+ return self._c._request(
356
+ "POST", f"/approvals/{approval_id}/reject", json={"comment": comment}
357
+ ) or {}
358
+
359
+ def modify(
360
+ self, approval_id: int, *, edited_output: Any, comment: str | None = None
361
+ ) -> dict:
362
+ return self._c._request(
363
+ "POST",
364
+ f"/approvals/{approval_id}/modify",
365
+ json={"edited_output": edited_output, "comment": comment},
366
+ ) or {}
367
+
368
+
369
+ class _Sessions(_Group):
370
+ def create(self, **payload) -> dict:
371
+ return self._c._request("POST", "/sessions", json=payload) or {}
372
+
373
+ def get(self, session_id: int) -> dict:
374
+ return self._c._request("GET", f"/sessions/{session_id}") or {}
375
+
376
+ def list(self, *, page: int = 1, size: int = 10, user_id: int | None = None) -> Page:
377
+ return Page.from_api(
378
+ self._c._request(
379
+ "GET", "/sessions", params={"page": page, "size": size, "user_id": user_id}
380
+ )
381
+ )
382
+
383
+ def messages(self, session_id: int, *, after_seq: int = 0, limit: int = 200) -> list:
384
+ return self._c._request(
385
+ "GET",
386
+ f"/sessions/{session_id}/messages",
387
+ params={"after_seq": after_seq, "limit": limit},
388
+ ) or []
389
+
390
+ def append(self, session_id: int, **payload) -> dict:
391
+ return self._c._request("POST", f"/sessions/{session_id}/messages", json=payload) or {}
392
+
393
+ def summarize(self, session_id: int) -> dict:
394
+ return self._c._request("POST", f"/sessions/{session_id}/summarize") or {}
395
+
396
+ def context(self, session_id: int, *, max_tokens: int = 4000) -> dict:
397
+ return self._c._request(
398
+ "GET", f"/sessions/{session_id}/context", params={"max_tokens": max_tokens}
399
+ ) or {}
400
+
401
+ def close(self, session_id: int) -> dict:
402
+ return self._c._request("POST", f"/sessions/{session_id}/close") or {}
403
+
404
+
405
+ class _Memory(_Group):
406
+ def list(
407
+ self, *, scope: str, scope_id: str, kind: str | None = None, keyword: str | None = None, limit: int = 50
408
+ ) -> list:
409
+ return self._c._request(
410
+ "GET",
411
+ "/memory",
412
+ params={"scope": scope, "scope_id": scope_id, "kind": kind, "keyword": keyword, "limit": limit},
413
+ ) or []
414
+
415
+ def write(self, **payload) -> dict:
416
+ return self._c._request("POST", "/memory", json=payload) or {}
417
+
418
+ def delete(self, memory_id: int) -> None:
419
+ self._c._request("DELETE", f"/memory/{memory_id}")
420
+
421
+ def purge(self) -> dict:
422
+ return self._c._request("POST", "/memory/purge") or {}
423
+
424
+
425
+ class _Blackboard(_Group):
426
+ def list(self, run_id: int) -> list:
427
+ return self._c._request("GET", f"/runs/{run_id}/blackboard") or []
428
+
429
+ def get(self, run_id: int, key: str) -> dict | None:
430
+ return self._c._request("GET", f"/runs/{run_id}/blackboard/{key}")
431
+
432
+ def put(
433
+ self,
434
+ run_id: int,
435
+ key: str,
436
+ value: Any,
437
+ *,
438
+ expected_version: int | None = None,
439
+ updated_by: str | None = None,
440
+ ) -> dict:
441
+ return self._c._request(
442
+ "PUT",
443
+ f"/runs/{run_id}/blackboard/{key}",
444
+ json={"value": value, "expected_version": expected_version, "updated_by": updated_by},
445
+ ) or {}
446
+
447
+ def delete(self, run_id: int, key: str, *, expected_version: int | None = None) -> None:
448
+ self._c._request(
449
+ "DELETE",
450
+ f"/runs/{run_id}/blackboard/{key}",
451
+ params={"expected_version": expected_version},
452
+ )
453
+
454
+
455
+ class _Knowledge(_Group):
456
+ def search(self, **payload) -> dict:
457
+ return self._c._request("POST", "/knowledge/search", json=payload) or {}
458
+
459
+ def citations(self, *, run_id: int | None = None, session_id: int | None = None) -> list:
460
+ return self._c._request(
461
+ "GET", "/knowledge/citations", params={"run_id": run_id, "session_id": session_id}
462
+ ) or []
463
+
464
+
465
+ class _Eval(_Group):
466
+ def suites(self) -> list:
467
+ return self._c._request("GET", "/eval/suites") or []
468
+
469
+ def cases(self, suite: str) -> list:
470
+ return self._c._request("GET", "/eval/cases", params={"suite": suite}) or []
471
+
472
+ def upsert_case(self, **payload) -> dict:
473
+ return self._c._request("POST", "/eval/cases", json=payload) or {}
474
+
475
+ def run(self, **payload) -> dict:
476
+ return self._c._request("POST", "/eval/run", json=payload) or {}
477
+
478
+ def runs(self, *, suite: str | None = None, page: int = 1, size: int = 10) -> Page:
479
+ return Page.from_api(
480
+ self._c._request(
481
+ "GET", "/eval/runs", params={"suite": suite, "page": page, "size": size}
482
+ )
483
+ )
484
+
485
+ def delete_case(self, case_id: int) -> None:
486
+ self._c._request("DELETE", f"/eval/cases/{case_id}")
487
+
488
+ def get_run(self, eval_run_id: int) -> dict:
489
+ return self._c._request("GET", f"/eval/runs/{eval_run_id}") or {}
490
+
491
+ def regression(self, **payload) -> dict:
492
+ return self._c._request("POST", "/eval/regression", json=payload) or {}
493
+
494
+ def gate(self, *, agent_key: str, suite: str, threshold: float = 0.8) -> dict:
495
+ return self._c._request(
496
+ "GET",
497
+ "/eval/gate",
498
+ params={"agent_key": agent_key, "suite": suite, "threshold": threshold},
499
+ ) or {}
500
+
501
+
502
+ class _Feedback(_Group):
503
+ def submit(self, **payload) -> dict:
504
+ return self._c._request("POST", "/feedback", json=payload) or {}
505
+
506
+ def list(self, *, run_id: int | None = None, min_rating: int | None = None, page: int = 1, size: int = 20) -> Page:
507
+ return Page.from_api(
508
+ self._c._request(
509
+ "GET",
510
+ "/feedback",
511
+ params={"run_id": run_id, "min_rating": min_rating, "page": page, "size": size},
512
+ )
513
+ )
514
+
515
+ def summary(self, *, days: int = 7) -> dict:
516
+ return self._c._request("GET", "/feedback/summary", params={"days": days}) or {}
517
+
518
+ def sample_reviews(self, **payload) -> list:
519
+ return self._c._request("POST", "/reviews/sample", json=payload) or []
520
+
521
+ def reviews(self, *, status: str = "pending", page: int = 1, size: int = 20) -> Page:
522
+ return Page.from_api(
523
+ self._c._request(
524
+ "GET", "/reviews", params={"status": status, "page": page, "size": size}
525
+ )
526
+ )
527
+
528
+ def decide_review(self, review_id: int, **payload) -> dict:
529
+ return self._c._request(
530
+ "POST", f"/reviews/{review_id}/decide", json=payload
531
+ ) or {}
532
+
533
+ def review_summary(self) -> dict:
534
+ return self._c._request("GET", "/reviews/summary") or {}
535
+
536
+ def failure_clusters(self, *, days: int = 7, limit: int = 20) -> dict:
537
+ return self._c._request(
538
+ "GET", "/failures/clusters", params={"days": days, "limit": limit}
539
+ ) or {}
540
+
541
+
542
+ class _Audit(_Group):
543
+ def list(self, *, session_id: str, page: int = 1, size: int = 50) -> Page:
544
+ return Page.from_api(
545
+ self._c._request(
546
+ "GET",
547
+ "/audit",
548
+ params={"session_id": session_id, "page": page, "size": size},
549
+ )
550
+ )
551
+
552
+ def verify(self, *, session_id: str) -> dict:
553
+ return (
554
+ self._c._request(
555
+ "GET", "/audit/verify", params={"session_id": session_id}
556
+ )
557
+ or {}
558
+ )
@@ -0,0 +1,22 @@
1
+ """SDK 错误映射:平台统一响应 → ApiError。"""
2
+ from __future__ import annotations
3
+
4
+
5
+ class ApiError(Exception):
6
+ """接口错误:code 为平台业务码,message 为可读信息。"""
7
+
8
+ def __init__(
9
+ self,
10
+ code: int,
11
+ message: str,
12
+ http_status: int = 0,
13
+ payload: dict | None = None,
14
+ ):
15
+ super().__init__(f"[{code}] {message}")
16
+ self.code = code
17
+ self.message = message
18
+ self.http_status = http_status
19
+ self.payload = payload or {}
20
+
21
+ def __str__(self) -> str:
22
+ return f"[{self.code}] {self.message} (HTTP {self.http_status})"