evallabs-sdk 0.2.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.
evallabs/__init__.py ADDED
@@ -0,0 +1,81 @@
1
+ """Eval Labs SDK: records the tools an AI agent really calls, so Eval Labs can test and monitor it.
2
+
3
+ Published on PyPI as ``evallabs-sdk``; imported as ``evallabs``.
4
+ """
5
+
6
+ __version__ = "0.2.0"
7
+
8
+ from evallabs.agent_logging import (
9
+ AgentLogConfig,
10
+ AgentLogContext,
11
+ AgentLogEmitter,
12
+ agent_log_context_from_eval_request,
13
+ configure_agent_logging,
14
+ emit_agent_log,
15
+ flush_agent_logs,
16
+ get_agent_log_context,
17
+ get_agent_log_emitter,
18
+ use_agent_log_context,
19
+ )
20
+ from evallabs.actors import current_actor, record_answer, record_handoff, subagent, trace_subagent
21
+ from evallabs.describe import describe_agent, registered_tools
22
+ from evallabs.decorators import trace_agent, trace_eval_request, trace_span, trace_step, trace_tool, traced_request
23
+ from evallabs.events import record_custom_event, record_policy_check
24
+ from evallabs.monitoring import (
25
+ configure_monitoring,
26
+ configure_monitoring_from_env,
27
+ current_trace_id,
28
+ disable_monitoring,
29
+ flush_monitoring,
30
+ monitoring_session,
31
+ record_feedback,
32
+ )
33
+ from evallabs.payload_capture import configure_tracing
34
+ from evallabs.sinks import HTTPTraceSink, InMemoryTraceSink, JsonlTraceSink, load_jsonl_trace_events
35
+ from evallabs.tracer import EvalsTracer
36
+
37
+ __all__ = [
38
+ "__version__",
39
+ "AgentLogConfig",
40
+ "AgentLogContext",
41
+ "AgentLogEmitter",
42
+ "EvalsTracer",
43
+ "HTTPTraceSink",
44
+ "InMemoryTraceSink",
45
+ "JsonlTraceSink",
46
+ "agent_log_context_from_eval_request",
47
+ "configure_agent_logging",
48
+ "configure_monitoring",
49
+ "configure_monitoring_from_env",
50
+ "current_actor",
51
+ "current_trace_id",
52
+ "describe_agent",
53
+ "disable_monitoring",
54
+ "flush_monitoring",
55
+ "monitoring_session",
56
+ "record_feedback",
57
+ "configure_tracing",
58
+ "emit_agent_log",
59
+ "flush_agent_logs",
60
+ "get_agent_log_context",
61
+ "get_agent_log_emitter",
62
+ "load_jsonl_trace_events",
63
+ "record_custom_event",
64
+ "record_answer",
65
+ "record_handoff",
66
+ "record_policy_check",
67
+ "registered_tools",
68
+ "trace_agent",
69
+ "trace_eval_request",
70
+ "trace_span",
71
+ "trace_step",
72
+ "subagent",
73
+ "trace_subagent",
74
+ "trace_tool",
75
+ "traced_request",
76
+ "use_agent_log_context",
77
+ ]
78
+
79
+ from evallabs._threads import install as _install_thread_context
80
+
81
+ _install_thread_context()
evallabs/_compat.py ADDED
@@ -0,0 +1,18 @@
1
+ """Small stand-ins so the SDK runs on Python 3.10 as well as 3.11+."""
2
+
3
+ from datetime import timezone
4
+ from enum import Enum
5
+
6
+ UTC = timezone.utc
7
+
8
+ try: # Python 3.11+
9
+ from enum import StrEnum
10
+ except ImportError: # Python 3.10
11
+
12
+ class StrEnum(str, Enum): # type: ignore[no-redef]
13
+ """An Enum whose members are also strings, like enum.StrEnum."""
14
+
15
+ def __str__(self) -> str:
16
+ return str(self.value)
17
+
18
+ __all__ = ["UTC", "StrEnum"]
evallabs/_threads.py ADDED
@@ -0,0 +1,56 @@
1
+ """Keep tracing when an agent runs a tool in another thread.
2
+
3
+ Python's context variables (where the SDK keeps the current test) don't follow work handed to a
4
+ ThreadPoolExecutor or a new Thread: without this, a tool run by `executor.submit(...)` or
5
+ `loop.run_in_executor(...)` inside a test would not be recorded. (asyncio tasks and asyncio.to_thread
6
+ already carry them.)
7
+
8
+ Only while a test or monitored request is being traced, work submitted from it runs with a copy of
9
+ the submitting thread's context. Outside a traced request nothing changes. Set
10
+ EVALLABS_THREAD_CONTEXT=0 to turn this off.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import contextvars
16
+ import os
17
+ import threading
18
+ from concurrent.futures import ThreadPoolExecutor
19
+ from typing import Any
20
+
21
+ from evallabs.context import get_current_tracer
22
+
23
+ _installed = False
24
+
25
+
26
+ def install() -> None:
27
+ global _installed
28
+ if _installed or os.getenv("EVALLABS_THREAD_CONTEXT", "1").strip().lower() in ("0", "false", "off", "no"):
29
+ return
30
+ _installed = True
31
+
32
+ original_submit = ThreadPoolExecutor.submit
33
+
34
+ def submit(self: ThreadPoolExecutor, fn: Any, /, *args: Any, **kwargs: Any) -> Any:
35
+ if get_current_tracer() is None:
36
+ return original_submit(self, fn, *args, **kwargs)
37
+ return original_submit(self, contextvars.copy_context().run, fn, *args, **kwargs)
38
+
39
+ submit.__doc__ = original_submit.__doc__
40
+ submit.__wrapped__ = original_submit # type: ignore[attr-defined]
41
+ ThreadPoolExecutor.submit = submit # type: ignore[method-assign]
42
+
43
+ original_start = threading.Thread.start
44
+
45
+ def start(self: threading.Thread) -> None:
46
+ target = getattr(self, "_target", None)
47
+ # A pool's worker thread runs many tasks: those get their context from submit(), not here.
48
+ if get_current_tracer() is not None and getattr(target, "__module__", "") != "concurrent.futures.thread":
49
+ context = contextvars.copy_context()
50
+ run = self.run
51
+ self.run = lambda: context.run(run) # type: ignore[method-assign]
52
+ original_start(self)
53
+
54
+ start.__doc__ = original_start.__doc__
55
+ start.__wrapped__ = original_start # type: ignore[attr-defined]
56
+ threading.Thread.start = start # type: ignore[method-assign]
evallabs/actors.py ADDED
@@ -0,0 +1,92 @@
1
+ """Multi-agent systems: tell Eval Labs which sub-agent is acting, and when control passes between them.
2
+
3
+ @trace_subagent("billing")
4
+ def billing_agent(state): ... # tool calls made inside are stamped actor="billing"
5
+
6
+ with subagent("triage"): # same thing, as a block
7
+ record_handoff("billing", reason="refund request") # triage -> billing
8
+ ...
9
+ record_answer("billing") # who gave the final answer
10
+
11
+ The current sub-agent is kept in a context variable, so it follows the request through nested calls
12
+ and asyncio tasks. All of this is a no-op when nothing is listening (no tracer active), and a
13
+ single-agent app never needs it.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from collections.abc import Callable, Iterator
19
+ from contextlib import contextmanager
20
+ from contextvars import ContextVar
21
+ from functools import wraps
22
+ from inspect import iscoroutinefunction
23
+ from typing import Any, TypeVar
24
+
25
+ from evallabs.contract import TraceEventType
26
+ from evallabs.context import get_current_tracer
27
+
28
+ F = TypeVar("F", bound=Callable[..., Any])
29
+ _stack: ContextVar[tuple[str, ...]] = ContextVar("evals_subagent_stack", default=())
30
+
31
+
32
+ def current_actor() -> str | None:
33
+ stack = _stack.get()
34
+ return stack[-1] if stack else None
35
+
36
+
37
+ @contextmanager
38
+ def subagent(name: str) -> Iterator[None]:
39
+ """Everything inside runs as sub-agent ``name``."""
40
+
41
+ if not name or not str(name).strip():
42
+ raise ValueError("subagent name must not be empty")
43
+ token = _stack.set((*_stack.get(), str(name)))
44
+ try:
45
+ yield
46
+ finally:
47
+ _stack.reset(token)
48
+
49
+
50
+ def trace_subagent(name: str) -> Callable[[F], F]:
51
+ """Decorator form of ``subagent(name)``."""
52
+
53
+ def decorator(func: F) -> F:
54
+ if iscoroutinefunction(func):
55
+ @wraps(func)
56
+ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
57
+ with subagent(name):
58
+ return await func(*args, **kwargs)
59
+ return async_wrapper # type: ignore[return-value]
60
+
61
+ @wraps(func)
62
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
63
+ with subagent(name):
64
+ return func(*args, **kwargs)
65
+ return wrapper # type: ignore[return-value]
66
+
67
+ return decorator
68
+
69
+
70
+ def record_handoff(to_actor: str, *, from_actor: str | None = None, reason: str = "", status: str = "completed") -> None:
71
+ """Control passes from ``from_actor`` (default: the current sub-agent) to ``to_actor``."""
72
+
73
+ source = from_actor or current_actor()
74
+ tracer = get_current_tracer()
75
+ if tracer is None or not source or not to_actor:
76
+ return
77
+ tracer.record(
78
+ TraceEventType.HANDOFF,
79
+ payload={"from_actor": source, "to_actor": str(to_actor), "reason": reason, "status": status},
80
+ message=f"Handoff {source} -> {to_actor}",
81
+ )
82
+
83
+
84
+ def record_answer(actor: str | None = None) -> None:
85
+ """The sub-agent (default: the current one) that gave the user the final answer."""
86
+
87
+ who = actor or current_actor()
88
+ tracer = get_current_tracer()
89
+ if tracer is None or not who:
90
+ return
91
+ tracer.record(TraceEventType.CUSTOM_EVENT, payload={"name": "answered_by", "data": {"actor": who}},
92
+ message=f"{who} answered the user")