-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy path__init__.py
More file actions
1412 lines (1163 loc) · 47.3 KB
/
__init__.py
File metadata and controls
1412 lines (1163 loc) · 47.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Agent Control - Unified agent control, monitoring, and SDK client.
This package provides a complete interface for controlling your agents with
automatic registration, rule enforcement, and server communication.
Usage:
import agent_control
# Initialize at the base of your agent file
agent_control.init(
agent_name="my-customer-service-bot"
)
# Apply server-defined controls using the decorator
# Control configuration is on server - update rules without code changes!
@agent_control.control()
async def chat(message: str) -> str:
return await assistant.respond(message)
# Apply all controls for this agent
@agent_control.control(policy="safety-policy")
async def process(input: str) -> str:
return await pipeline.run(input)
# Use custom step name for control matching
@agent_control.control(step_name="user_query_handler")
async def handle_input(user_message: str) -> str:
return await process_query(user_message)
# Or use the client directly for server-side checks
async with agent_control.AgentControlClient() as client:
result = await agent_control.evaluation.check_evaluation(
client,
agent_name,
step={"type": "llm", "name": "chat", "input": "Hello"},
stage="pre",
)
"""
from importlib.metadata import PackageNotFoundError, version
try:
__version__ = version("agent-control-sdk")
except PackageNotFoundError:
__version__ = "0.0.0.dev"
import asyncio
import os
import threading
from collections.abc import Callable, Coroutine
from dataclasses import dataclass
from datetime import UTC, datetime
from typing import Any, Literal, TypeVar
import httpx
from agent_control_models import (
Agent,
ControlAction,
ControlDefinition,
ControlMatch,
ControlScope,
ControlSelector,
EvaluationRequest,
EvaluationResult,
EvaluatorResult,
EvaluatorSpec,
JSONObject,
Step,
StepSchema,
TemplateControlInput,
TemplateDefinition,
TemplateValue,
UnrenderedTemplateControl,
)
from agent_control_telemetry.trace_context import (
clear_trace_context_provider,
get_trace_context_from_provider,
set_trace_context_provider,
)
from . import agents, controls, evaluation, evaluators, policies
from ._control_registry import (
StepSchemaDict,
get_registered_steps,
merge_explicit_and_auto_steps,
)
from ._control_registry import (
clear as clear_step_registry,
)
from .client import AgentControlClient
from .control_decorators import ControlSteerError, ControlViolationError, control
from .evaluation import check_evaluation_with_local, evaluate_controls
from .observability import (
LogConfig,
add_event,
configure_logging,
get_event_batcher,
get_event_sink,
get_log_config,
get_logger,
get_registered_control_event_sink_factory_names,
get_registered_control_event_sinks,
init_observability,
is_observability_enabled,
log_control_evaluation,
register_control_event_sink,
register_control_event_sink_factory,
shutdown_observability,
sync_shutdown_observability,
unregister_control_event_sink,
unregister_control_event_sink_factory,
write_events,
)
from .tracing import (
get_current_span_id,
get_current_trace_id,
get_trace_and_span_ids,
is_otel_available,
with_trace,
)
from .validation import ensure_agent_name
# Module logger
logger = get_logger(__name__)
# ============================================================================
# Global State
# ============================================================================
# Import state container to avoid circular imports
from ._state import state # noqa: E402
F = TypeVar("F", bound=Callable[..., Any])
# Policy refresh loop state
_refresh_lock = threading.Lock()
_policy_refresh_interval_seconds: int | None = None
_refresh_thread: threading.Thread | None = None
_refresh_stop_event: threading.Event | None = None
# Session lifecycle state used to discard stale manual refresh results.
_session_lock = threading.Lock()
_session_generation = 0
@dataclass(frozen=True)
class _RefreshContext:
"""Connection/session snapshot for a single refresh request."""
session_generation: int
agent_name: str
server_url: str
api_key: str | None
def get_server_controls() -> list[dict[str, Any]] | None:
"""Get the cached server controls.
Returns the controls that were fetched during init() or the last
refresh_controls() call. Returns None if no controls are cached.
Returns:
List of control dicts or None if not initialized.
Example:
controls = agent_control.get_server_controls()
if controls:
print(f"Loaded {len(controls)} controls")
for c in controls:
print(f" - {c['name']} (execution: {c['control'].get('execution', 'server')})")
"""
return state.server_controls
def to_template_control_input(
data: dict[str, Any] | ControlDefinition,
) -> TemplateControlInput:
"""Convert stored control data into template authoring input."""
return controls.to_template_control_input(data)
def _publish_server_controls(
controls: list[dict[str, Any]] | None,
) -> list[dict[str, Any]] | None:
"""Publish controls using swap-only snapshot semantics."""
if controls is None:
state.server_controls = None
return None
# Snapshot copy: publish a new list reference and avoid in-place mutation.
state.server_controls = list(controls)
return state.server_controls
def _run_coro_in_new_loop[T](coro: Coroutine[Any, Any, T]) -> T:
"""Run a coroutine on a dedicated event loop in the current thread."""
loop = asyncio.new_event_loop()
try:
asyncio.set_event_loop(loop)
return loop.run_until_complete(coro)
finally:
loop.close()
asyncio.set_event_loop(None)
def _snapshot_refresh_context() -> _RefreshContext:
"""Capture a consistent session snapshot for a refresh request."""
with _session_lock:
session_generation = _session_generation
agent = state.current_agent
server_url = state.server_url
api_key = state.api_key
if agent is None:
raise RuntimeError("Agent not initialized. Call agent_control.init() first.")
if server_url is None:
raise RuntimeError("Server URL not set. Call agent_control.init() first.")
return _RefreshContext(
session_generation=session_generation,
agent_name=agent.agent_name,
server_url=server_url,
api_key=api_key,
)
async def _fetch_controls_for_context_async(context: _RefreshContext) -> list[dict[str, Any]]:
"""Fetch controls for a previously snapshotted session context."""
async with AgentControlClient(
base_url=context.server_url,
api_key=context.api_key,
) as client:
response = await agents.list_agent_controls(
client,
context.agent_name,
rendered_state="rendered",
enabled_state="enabled",
)
controls: list[dict[str, Any]] = response.get("controls", [])
return controls
async def _fetch_controls_async() -> list[dict[str, Any]]:
"""Fetch controls from the server without publishing.
Snapshots connection state into locals before any I/O so the result
is safe to discard if shutdown fires mid-flight.
Returns:
Raw list of control dicts from the server.
Raises:
RuntimeError: If the SDK is not initialized.
Exception: On network / server errors (caller decides policy).
"""
context = _snapshot_refresh_context()
return await _fetch_controls_for_context_async(context)
def _policy_refresh_worker(stop_event: threading.Event, interval_seconds: int) -> None:
"""Background worker that periodically refreshes controls."""
while not stop_event.wait(interval_seconds):
if stop_event.is_set():
break
try:
controls = _run_coro_in_new_loop(_fetch_controls_async())
except Exception as exc:
logger.error(
"Background policy refresh loop iteration failed: %s",
exc,
exc_info=True,
)
continue
# Do not publish if shutdown was requested during the fetch.
if stop_event.is_set():
break
_publish_server_controls(controls)
logger.info("Refreshed %d control(s) from server", len(controls))
def _stop_policy_refresh_loop() -> None:
"""Stop the background policy refresh loop if running."""
global _policy_refresh_interval_seconds, _refresh_thread, _refresh_stop_event
with _refresh_lock:
stop_event = _refresh_stop_event
refresh_thread = _refresh_thread
_policy_refresh_interval_seconds = None
_refresh_stop_event = None
_refresh_thread = None
if stop_event is not None:
stop_event.set()
if refresh_thread is not None and refresh_thread.is_alive():
refresh_thread.join(timeout=2)
if refresh_thread.is_alive():
logger.warning("Timed out while stopping policy refresh loop thread")
def _start_policy_refresh_loop(interval_seconds: int) -> None:
"""Start a background loop that refreshes controls on a fixed interval."""
global _policy_refresh_interval_seconds, _refresh_thread, _refresh_stop_event
if interval_seconds <= 0:
return
stop_event = threading.Event()
refresh_thread = threading.Thread(
target=_policy_refresh_worker,
args=(stop_event, interval_seconds),
name="agent-control-policy-refresh",
daemon=True,
)
with _refresh_lock:
_policy_refresh_interval_seconds = interval_seconds
_refresh_stop_event = stop_event
_refresh_thread = refresh_thread
refresh_thread.start()
logger.info("Started policy refresh loop (interval=%ss)", interval_seconds)
async def refresh_controls_async() -> list[dict[str, Any]] | None:
"""Refresh controls from the server asynchronously.
Fetches the latest controls from the server and updates the cache.
Use this when you've made changes to controls in the UI or API
and want the SDK to pick them up without restarting.
Returns:
List of control dicts or None if fetch failed.
Example:
# After updating a control in the UI
controls = await agent_control.refresh_controls_async()
print(f"Refreshed {len(controls)} controls")
"""
context = _snapshot_refresh_context()
try:
controls = await _fetch_controls_for_context_async(context)
except Exception as exc:
logger.error(
"Failed to refresh controls; keeping previous cache (%d control(s)): %s",
len(state.server_controls or []),
exc,
exc_info=True,
)
return state.server_controls
with _session_lock:
if context.session_generation != _session_generation:
logger.info(
"Discarding stale control refresh result for superseded SDK session"
)
return state.server_controls
refreshed_controls = _publish_server_controls(controls)
if refreshed_controls is not None:
logger.info("Refreshed %d control(s) from server", len(refreshed_controls or []))
else:
logger.info("Refreshed 0 control(s) from server")
return refreshed_controls
def refresh_controls() -> list[dict[str, Any]] | None:
"""Refresh controls from the server synchronously.
Fetches the latest controls from the server and updates the cache.
Use this when you've made changes to controls in the UI or API
and want the SDK to pick them up without restarting.
Returns:
List of control dicts or None if fetch failed.
Example:
# After updating a control in the UI
controls = agent_control.refresh_controls()
print(f"Refreshed {len(controls)} controls")
"""
try:
asyncio.get_running_loop()
# We're in an async context - run in thread
result_container: list[list[dict[str, Any]] | None] = [None]
exception_container: list[Exception | None] = [None]
def run_in_thread() -> None:
try:
result_container[0] = _run_coro_in_new_loop(refresh_controls_async())
except Exception as e:
exception_container[0] = e
thread = threading.Thread(target=run_in_thread, daemon=True)
thread.start()
thread.join(timeout=10)
if exception_container[0]:
raise exception_container[0]
return result_container[0]
except RuntimeError:
# No running event loop - we're in a sync context
return _run_coro_in_new_loop(refresh_controls_async())
# ============================================================================
# Public API Functions
# ============================================================================
def init(
agent_name: str,
agent_description: str | None = None,
agent_version: str | None = None,
server_url: str | None = None,
api_key: str | None = None,
controls_file: str | None = None,
steps: list[StepSchemaDict] | None = None,
conflict_mode: Literal["strict", "overwrite"] = "overwrite",
observability_enabled: bool | None = None,
observability_sink_name: str | None = None,
observability_sink_config: JSONObject | None = None,
log_config: dict[str, Any] | None = None,
policy_refresh_interval_seconds: int = 60,
**kwargs: object
) -> Agent:
"""
Initialize Agent Control with your agent's information.
This function should be called once at the base of your agent file.
It will:
1. Create an Agent instance with your metadata
2. Register with the Agent Control server via /initAgent endpoint
3. Fetch controls from the server
4. Auto-discover and load local controls.yaml as fallback
5. Enable the @control decorator
Args:
agent_name: Unique identifier for your agent (will be normalized to lowercase)
agent_description: Optional description of what your agent does
agent_version: Optional version string (e.g., "1.0.0")
server_url: Optional server URL (defaults to AGENT_CONTROL_URL env var
or http://localhost:8000)
api_key: Optional API key for authentication (defaults to AGENT_CONTROL_API_KEY env var)
controls_file: Optional explicit path to controls.yaml (auto-discovered if not provided)
steps: Optional list of step schemas for registration:
[{"type": "tool", "name": "search", "input_schema": {...}, "output_schema": {...}}]
conflict_mode: Conflict handling mode for initAgent registration.
Defaults to "overwrite" in SDK flows.
observability_enabled: Optional bool to enable/disable observability (defaults to env var)
observability_sink_name: Optional sink selection name. Use "default" to preserve
SDK -> server OSS delivery or "registered" / a named sink factory for custom sinks.
observability_sink_config: Optional JSON config payload for the selected sink.
log_config: Optional logging configuration dict:
{"enabled": True, "span_start": True, "span_end": True, "control_eval": True}
policy_refresh_interval_seconds: Interval for background policy refresh loop.
Defaults to 60 seconds. Set to 0 to disable background refresh.
**kwargs: Additional metadata to store with the agent
Returns:
Agent instance with all metadata
Example:
import agent_control
agent_control.init(
agent_name="customer-service-bot",
agent_description="Handles customer inquiries and support tickets",
agent_version="2.1.0",
steps=[
{
"type": "tool",
"name": "search_knowledge_base",
"input_schema": {"query": {"type": "string"}},
"output_schema": {"results": {"type": "array"}}
}
]
)
# Now use @control decorator to apply the agent's policy
from agent_control import control
@control() # Applies agent's assigned policy
async def handle(message: str):
return message
Environment Variables:
AGENT_CONTROL_URL: Server URL (default: http://localhost:8000)
"""
if not agent_name:
raise ValueError(
"The 'agent_name' argument is required for initialization.\n"
"Please provide a valid agent identifier, e.g.:\n"
' agent_control.init(agent_name="customer-service-bot")'
)
# Validate and normalize agent_name
_agent_name = ensure_agent_name(agent_name)
if policy_refresh_interval_seconds < 0:
raise ValueError("policy_refresh_interval_seconds must be >= 0")
# Re-init behavior: always stop existing loop before mutating shared agent/session globals.
_stop_policy_refresh_loop()
# Configure logging if provided (do this early before any logging happens)
if log_config:
configure_logging(log_config)
# Create agent instance with metadata and store in state
next_agent = Agent(
agent_name=_agent_name,
agent_description=agent_description,
agent_created_at=datetime.now(UTC).isoformat(),
agent_updated_at=None,
agent_version=agent_version,
agent_metadata=kwargs
)
# Bump the session generation before mutating connection state so any
# in-flight manual refresh from a previous session is discarded on return.
global _session_generation
with _session_lock:
_session_generation += 1
state.current_agent = next_agent
state.server_url = server_url or os.getenv('AGENT_CONTROL_URL') or 'http://localhost:8000'
state.api_key = api_key
# Merge auto-discovered steps from @control() decorators with explicit steps.
# Explicit steps take precedence when (type, name) collides.
auto_steps = get_registered_steps()
merge_result = merge_explicit_and_auto_steps(steps, auto_steps)
registration_steps: list[dict[str, Any]] = [dict(step) for step in merge_result.steps]
if auto_steps:
if merge_result.overridden_keys:
formatted = ", ".join(
f"{step_type}:{step_name}" for step_type, step_name in merge_result.overridden_keys
)
logger.warning(
"Skipping %d auto-discovered step(s) overridden by explicit steps: %s",
len(merge_result.overridden_keys),
formatted,
)
logger.debug(
"Auto-discovered %d step(s) from @control() decorators (%d after merge)",
len(auto_steps),
len(registration_steps),
)
# Register with server and fetch controls
server_controls = None
try:
async def register() -> list[dict[str, Any]] | None:
# Type assertions for mypy - these values are guaranteed to be set above
assert state.server_url is not None
assert state.current_agent is not None
async with AgentControlClient(
base_url=state.server_url, api_key=state.api_key
) as client:
# Check server health first
try:
health = await client.health_check()
logger.info("Connected to Agent Control server: %s", state.server_url)
logger.debug("Server status: %s", health.get('status', 'unknown'))
except Exception as e:
logger.error("Server not available: %s", e, exc_info=True)
return None
# Register agent with steps
try:
response = await agents.register_agent(
client,
state.current_agent,
steps=registration_steps,
conflict_mode=conflict_mode,
)
created = response.get('created', False)
controls: list[dict[str, Any]] = response.get('controls', [])
if created:
logger.info("Agent registered: %s", _agent_name)
else:
logger.info("Agent updated: %s", _agent_name)
if registration_steps:
logger.debug("Registered %d step(s)", len(registration_steps))
return controls
except httpx.HTTPStatusError:
# Surface API errors like name conflicts
raise
except Exception as e:
logger.error("Failed to register agent: %s", e, exc_info=True)
return None
# Run registration - handle both sync and async contexts
try:
# Check if we're already in an event loop
asyncio.get_running_loop()
# We're in an async context - schedule the coroutine
result_container: list[list[dict[str, Any]] | None] = [None]
exception_container: list[Exception | None] = [None]
def run_in_thread() -> None:
try:
result_container[0] = _run_coro_in_new_loop(register())
except Exception as e:
exception_container[0] = e
thread = threading.Thread(target=run_in_thread, daemon=True)
thread.start()
thread.join(timeout=10) # 10 second timeout
if exception_container[0]:
raise exception_container[0]
server_controls = result_container[0]
except RuntimeError:
# No running event loop - we're in a sync context
server_controls = _run_coro_in_new_loop(register())
except httpx.HTTPStatusError:
# Surface server-side errors (e.g., 409 conflicts)
raise
except Exception as e:
logger.error("Could not connect to server: %s", e, exc_info=True)
logger.info("Will use local controls if available")
# Store server controls globally for later use by @control decorator.
published_controls = _publish_server_controls(server_controls)
if published_controls:
logger.info("Loaded %d control(s) from server", len(published_controls))
else:
logger.debug(
"No controls returned from server "
"(use local controls.yaml or @control decorator)"
)
# Initialize observability if enabled
batcher = init_observability(
server_url=state.server_url,
api_key=state.api_key,
enabled=observability_enabled,
sink_name=observability_sink_name,
sink_config=observability_sink_config,
)
if batcher:
logger.info("Observability enabled")
if policy_refresh_interval_seconds > 0:
_start_policy_refresh_loop(policy_refresh_interval_seconds)
else:
logger.debug("Policy refresh loop disabled (policy_refresh_interval_seconds=0)")
return state.current_agent
# ============================================================================
# Shutdown
# ============================================================================
def _reset_state() -> None:
"""Clear all global SDK state."""
global _session_generation
with _session_lock:
_session_generation += 1
state.current_agent = None
state.control_engine = None
state.server_controls = None
state.server_url = None
state.api_key = None
async def ashutdown() -> None:
"""Shut down the SDK and release all background resources.
Flushes pending observability events, stops the policy refresh loop,
and resets global state. Idempotent - safe to call multiple times.
Use this from async code. For sync code use :func:`shutdown`.
"""
await asyncio.to_thread(_stop_policy_refresh_loop)
await shutdown_observability()
_reset_state()
logger.info("Agent Control SDK shut down")
def shutdown() -> None:
"""Shut down the SDK and release all background resources.
Flushes pending observability events, stops the policy refresh loop,
and resets global state. Idempotent - safe to call multiple times.
Use this from sync code. For async code use :func:`ashutdown`.
"""
_stop_policy_refresh_loop()
sync_shutdown_observability()
_reset_state()
logger.info("Agent Control SDK shut down")
async def get_agent(
agent_name: str,
server_url: str | None = None,
api_key: str | None = None,
) -> dict[str, Any]:
"""
Get agent details from the server by name.
Args:
agent_name: Agent identifier
server_url: Optional server URL (defaults to AGENT_CONTROL_URL env var)
api_key: Optional API key for authentication (defaults to AGENT_CONTROL_API_KEY env var)
Returns:
Dictionary containing:
- agent: Agent metadata
- steps: List of steps registered with the agent
Raises:
httpx.HTTPError: If request fails or agent not found
Example:
import asyncio
import agent_control
# Fetch agent from server
async def main():
agent_data = await agent_control.get_agent(
"customer-service-bot"
)
print(f"Agent: {agent_data['agent']['agent_name']}")
print(f"Steps: {len(agent_data['steps'])}")
asyncio.run(main())
# Or using the client directly
async with agent_control.AgentControlClient() as client:
agent_data = await agent_control.agents.get_agent(
client, "customer-service-bot"
)
"""
_final_server_url = server_url or os.getenv('AGENT_CONTROL_URL') or 'http://localhost:8000'
async with AgentControlClient(base_url=_final_server_url, api_key=api_key) as client:
return await agents.get_agent(client, agent_name)
def current_agent() -> Agent | None:
"""
Get the currently initialized agent (from init()).
Returns:
Current Agent instance or None if not initialized
Example:
agent_control.init(
agent_name="My Bot",
)
agent = agent_control.current_agent()
print(agent.agent_name) # "My Bot"
"""
return state.current_agent
async def list_agents(
server_url: str | None = None,
api_key: str | None = None,
cursor: str | None = None,
limit: int = 20,
) -> dict[str, Any]:
"""
List all registered agents from the server.
Args:
server_url: Optional server URL (defaults to AGENT_CONTROL_URL env var)
api_key: Optional API key for authentication (defaults to AGENT_CONTROL_API_KEY env var)
cursor: Optional cursor for pagination (agent name of last item from previous page)
limit: Number of results per page (default 20, max 100)
Returns:
Dictionary containing:
- agents: List of agent summaries with agent_name,
policy_id, created_at, step_count, evaluator_count
- pagination: Object with limit, total, next_cursor, has_more
Raises:
httpx.HTTPError: If request fails
Example:
import asyncio
import agent_control
async def main():
result = await agent_control.list_agents()
print(f"Total agents: {result['pagination']['total']}")
for agent in result['agents']:
print(f" - {agent['agent_name']}")
# Fetch next page
if result['pagination']['has_more']:
next_page = await agent_control.list_agents(
cursor=result['pagination']['next_cursor']
)
asyncio.run(main())
"""
_final_server_url = server_url or os.getenv('AGENT_CONTROL_URL') or 'http://localhost:8000'
async with AgentControlClient(base_url=_final_server_url, api_key=api_key) as client:
return await agents.list_agents(client, cursor=cursor, limit=limit)
# ============================================================================
# Agent Policy/Control Convenience Functions
# ============================================================================
async def add_agent_policy(
agent_name: str,
policy_id: int,
server_url: str | None = None,
api_key: str | None = None,
) -> dict[str, Any]:
"""Associate a policy with an agent (idempotent)."""
_final_server_url = server_url or os.getenv('AGENT_CONTROL_URL') or 'http://localhost:8000'
async with AgentControlClient(base_url=_final_server_url, api_key=api_key) as client:
return await agents.add_agent_policy(client, agent_name, policy_id)
async def get_agent_policies(
agent_name: str,
server_url: str | None = None,
api_key: str | None = None,
) -> dict[str, Any]:
"""List policy IDs associated with an agent."""
_final_server_url = server_url or os.getenv('AGENT_CONTROL_URL') or 'http://localhost:8000'
async with AgentControlClient(base_url=_final_server_url, api_key=api_key) as client:
return await agents.get_agent_policies(client, agent_name)
async def remove_agent_policy_association(
agent_name: str,
policy_id: int,
server_url: str | None = None,
api_key: str | None = None,
) -> dict[str, Any]:
"""Remove one policy association from an agent (idempotent)."""
_final_server_url = server_url or os.getenv('AGENT_CONTROL_URL') or 'http://localhost:8000'
async with AgentControlClient(base_url=_final_server_url, api_key=api_key) as client:
return await agents.remove_agent_policy_association(client, agent_name, policy_id)
async def remove_all_agent_policies(
agent_name: str,
server_url: str | None = None,
api_key: str | None = None,
) -> dict[str, Any]:
"""Remove all policy associations from an agent."""
_final_server_url = server_url or os.getenv('AGENT_CONTROL_URL') or 'http://localhost:8000'
async with AgentControlClient(base_url=_final_server_url, api_key=api_key) as client:
return await agents.remove_all_agent_policies(client, agent_name)
async def add_agent_control(
agent_name: str,
control_id: int,
server_url: str | None = None,
api_key: str | None = None,
) -> dict[str, Any]:
"""Associate a control with an agent (idempotent)."""
_final_server_url = server_url or os.getenv('AGENT_CONTROL_URL') or 'http://localhost:8000'
async with AgentControlClient(base_url=_final_server_url, api_key=api_key) as client:
return await agents.add_agent_control(client, agent_name, control_id)
async def remove_agent_control(
agent_name: str,
control_id: int,
server_url: str | None = None,
api_key: str | None = None,
) -> dict[str, Any]:
"""Remove a direct control association from an agent (idempotent)."""
_final_server_url = server_url or os.getenv('AGENT_CONTROL_URL') or 'http://localhost:8000'
async with AgentControlClient(base_url=_final_server_url, api_key=api_key) as client:
return await agents.remove_agent_control(client, agent_name, control_id)
# ============================================================================
# Control Management Convenience Functions
# ============================================================================
async def list_controls(
server_url: str | None = None,
api_key: str | None = None,
cursor: int | None = None,
limit: int = 20,
name: str | None = None,
enabled: bool | None = None,
template_backed: bool | None = None,
step_type: str | None = None,
stage: Literal["pre", "post"] | None = None,
execution: Literal["server", "sdk"] | None = None,
tag: str | None = None,
) -> dict[str, Any]:
"""
List all controls from the server with optional filtering.
Args:
server_url: Optional server URL (defaults to AGENT_CONTROL_URL env var)
api_key: Optional API key for authentication (defaults to AGENT_CONTROL_API_KEY env var)
cursor: Control ID to start after (for pagination)
limit: Number of results per page (default 20, max 100)
name: Optional filter by name (partial, case-insensitive)
enabled: Optional filter by enabled status
template_backed: Optional filter by whether the control is template-backed
step_type: Optional filter by step type (built-ins: 'tool', 'llm')
stage: Optional filter by stage ('pre' or 'post')
execution: Optional filter by execution ('server' or 'sdk')
tag: Optional filter by tag
Returns:
Dictionary containing:
- controls: List of control summaries
- pagination: Object with limit, total, next_cursor, has_more
Raises:
httpx.HTTPError: If request fails
Example:
import asyncio
import agent_control
async def main():
# List all controls
result = await agent_control.list_controls()
print(f"Total controls: {result['pagination']['total']}")
# Filter enabled LLM controls
llm_controls = await agent_control.list_controls(
enabled=True,
step_type="llm"
)
asyncio.run(main())
"""
_final_server_url = server_url or os.getenv('AGENT_CONTROL_URL') or 'http://localhost:8000'
async with AgentControlClient(base_url=_final_server_url, api_key=api_key) as client:
return await controls.list_controls(
client,
cursor=cursor,
limit=limit,
name=name,
enabled=enabled,
template_backed=template_backed,
step_type=step_type,
stage=stage,
execution=execution,
tag=tag,
)
async def create_control(
name: str,
data: dict[str, Any] | ControlDefinition | TemplateControlInput,
server_url: str | None = None,
api_key: str | None = None,
) -> dict[str, Any]:
"""
Create a new control with configuration.
Args:
name: Unique name for the control
data: Raw control definition or template-backed control input
server_url: Optional server URL (defaults to AGENT_CONTROL_URL env var)
api_key: Optional API key for authentication (defaults to AGENT_CONTROL_API_KEY env var)
Returns:
Dictionary containing:
- control_id: ID of the created control
- configured: Always True because create requires data
Raises:
httpx.HTTPError: If request fails
HTTPException 409: Control with this name already exists
HTTPException 422: If data doesn't match schema
Example:
import asyncio
import agent_control
async def main():
# Create and configure in one call