页面简介
Defining custom scanners and the supporting types, tools, and registration helpers.
正文摘录
Scanner Scanner Scan transcript content. Source class Scanner(Protocol[T]): def __call__(self, input: T, /) -> Awaitable[Result | list[Result]] input T Input to scan. ScannerInput Union of all valid scanner input types. Source ScannerInput = Union[ Transcript, ChatMessage, Sequence[ChatMessage], Event, Sequence[Event], Timeline, Sequence[Timeline], ] Result Scan result. Source class Result(BaseModel, Generic[ParsedT]) Attributes uuid str | None Unique identifer for scan result. value JsonValue Scan value. answer str | None Answer extracted from model output (optional) explanation str | None Explanation of result (optional). metadata dict[str, Any] | None Additional metadata related to the result (optional) references list[Reference] References to relevant messages or events. label str | None Label for result to indicate its origin. type str | None Type to designate contents of ‘value’ (used in value_type field in result data frames). parsed SkipJsonSchema[ParsedT | None] Typed parsed answer set by generate_answer()/parse_answer() (unaffected by value_to_float; None when parsing failed or the result was built elsewhere). In-memory only: excluded from serialization and dropped when pickled, so it survives neither storage nor process boundaries. Error Scan error (runtime error which occurred during scan). Source class Error(BaseModel) Attributes transcript_id str Target transcript id. scanner str Scanner name. error str Error message. traceback str Error traceback. refusal bool Was this error a refusal. Loader Load transcript data. Source class Loader(Protocol[TLoaderResult]): def __call__( self, transcript: Transcript, ) -> AsyncIterator[TLoaderResult] transcript Transcript Transcript to yield from. Scanners llm_scanner Create a scanner that uses an LLM to scan transcripts. This scanner presents a conversation transcript to an LLM along with a custom prompt and answer specification, enabling automated analysis of conversations for specific patterns, behaviors, or outcomes. Messages are extracted via transcript_messages(), which automatically selects the best strategy (timelines → events → raw messages) and respects context window limits. Each segment is scanned independently with globally unique message numbering ([M1], [M2], …) across all segments. Source @scanner(messages="all") def llm_scanner( *, question: str | Callable[[Transcript], Awaitable[str]] | None = None, answer: AnswerSpec, value_to_float: ValueToFloat | None = None, template: str | tuple[str, str] | None = None, template_variables: dict[str, Any] | Callable[[Transcript], dict[str, Any]] | None = None, preprocessor: MessagesPreprocessor[Transcript] | None = None, model: str | Model | None = None, model_role: str | None = None, cache: bool | CachePolicy | None = None, retry_refusals: bool | int = 3, name: str | None = None, content: TranscriptContent | None = None, context_window: int | None = None, timeline: str | None = None, compaction: Literal["all", "last"] | int = "all", depth: int | None = None, reducer: Callable[[list[Result]], Awaitable[Result]] | None = None, nonce: str | None = None, ) -> Scanner[Transcript] question str | Callable[[Transcript], Awaitable[str]] | None Question for the scanner to answer. Can be a static string (e.g., “Did the assistant refuse the request?”) or a function that takes a Transcript and returns an string for dynamic questions based on transcript content. Can be omitted if you provide a custom template. answer AnswerSpec Specification of the answer format. Pass “boolean”, “numeric”, or “string” for a simple answer; pass list[str] for a set of labels; or pass MultiLabels for multi-classification. value_to_float ValueToFloat | None Optional function to convert the answer value to a float. template str | tuple[str, str] | None Overall template for scanner prompt. The scanner template should include the following variables: - {{ question }} (question for the model to answer) - {{ messages }} (transcript message history as string) - {{ answer_prompt }} (prompt for a specific type of answer). - {{ answer_format }} (instructions on how to format the answer) In addition, scanner templates can bind to any data within Transcript.metadata (e.g. {{ metadata.score }}). Pass a tuple[str, str] of (prefix, suffix) to render the prompt as two content blocks. The first block is intended to hold the cacheable shared prefix (e.g. preamble + transcript messages); the second holds the per-scanner tail (e.g. question and answer format). Both templates receive the full variable bag. When template is None (default) or a tuple, the prompt is sent as a multi-block user message with cache_prompt=True, allowing prompt-cache hits across scanners that share the same prefix bytes for the same transcript. Passing a single str keeps the legacy single-block behavior (no caching). template_variables dict[str, Any] | Callable[[Transcript], dict[str, Any]] | None Additional variables to make available in the template. Optionally takes a function which receives the current Transcript which can return variables. preprocessor MessagesPreprocessor[Transcript] | None Transform conversation messages before analysis. Controls exclusion of system messages, reasoning tokens, and tool calls. A dict of these options also works, as in scan job YAML (e.g. {"exclude_reasoning": true}). Defaults to removing system messages. Note: custom transform functions that accept a Transcript are not supported when context_window or timeline scanning produces multiple segments, as the transform receives list[ChatMessage] per segment. model str | Model | None Optional model specification. Can be a model name string or Model instance. If None, uses the default model. model_role str | None Optional model role for role-based model resolution. When set, the model is resolved via get_model(model, role=model_role) at scan time, allowing deferred role resolution when roles are not yet available at scanner construction time. cache bool | CachePolicy | None Response caching policy for the judge model call. Pass True for default caching, a :class:CachePolicy for explicit expiry/scope, or None (default) for no caching. Threaded through to model.generate() via GenerateConfig.cache. retry_refusals bool | int Retry model refusals. Pass an int for number of retries (defaults to 3). Pass True to use the default or False to not retry refusals. If the limit of refusals is exceeded then a RuntimeError is raised. name str | None Scanner name. Use this to assign a name when passing llm_scanner() directly to scan() rather than delegating to it from another scanner. content TranscriptContent | None Override the transcript content filters for this scanner. For example, TranscriptContent(timeline=True) requests timeline data so the scanner can process span-level segments. context_window int | None Override the model’s context window size for chunking. When set, transcripts exceeding this limit are split into multiple segments, each scanned independently. timeline str | None Name of the timeline to extract messages from (e.g. a stored "target" timeline). Setting it loads timelines, so no content override is needed. None (default) uses the transcript’s first timeline (or one built from its events) when the scanner’s content includes timelines or events, and otherwise its messages. Raises ValueError if no timeline with the given name exists. compaction Literal['all', 'last'] | int How to handle compaction boundaries when extracting messages from events. "all" (default) scans all compaction segments; "last" scans only the most recent. depth int | None Maximum nesting level of scannable spans to scan when timelines are present. 1 = top-level agent/solver spans; 2 = top-level plus their first scannable descendants; None (default) = all depths. Pure container spans (e.g. the synthetic root) and utility spans do not consume a depth level. Ignored for events-only or messages-only transcripts. reducer Callable[[list[Result]], Awaitable[Result]] | None Custom reducer for aggregating multi-segment results. Accepts any Callable[[list[Result]], Awaitable[Result]]. If None, uses a default reducer based on the answer type (e.g., ResultReducer.any for boolean, ResultReducer.mean for numeric). Standard reducers are available on ResultReducer. On timeline scans the reducer is applied within each span before the per-span Results are wrapped in a resultset (cross-span attribution is preserved). Resultset answers (e.g. list[Model]) bypass reduction and return a resultset directly. nonce str | None A code written on every marker in the rendered transcript (message headers such as [M2] USER (3f9a1c7e):, tool calls, tool errors, reasoning and prefill tags, and placeholders for content that is not text; see messages_as_str()) and available to the template as { scout_nonce }. Make it with secrets.token_hex(4) when the scanner is built. Never write a literal nonce in code: an agent that can read the scanner file, or that knows the value from elsewhere, can forge markers. Must be at least 8 ASCII letters and digits (raises ValueError otherwise). A scout_nonce key in template_variables is always ignored. The default template puts the nonce on its transcript start and end lines and tells the model that text that looks like a marker but lacks the nonce is part of the message it appears in. grep_scanner Pattern-based transcript scanner. Scans transcript messages and events for text patterns using grep-style matching. By default, patterns are treated as literal strings (like grep without -E). Set regex=True to treat patterns as regular expressions. What gets searched depends on what’s populated in the transcript: - Messages are searched if transcript.messages is populated - Events are searched if transcript.events is populated - Control population via @scanner(messages=..., events=...) Source @scanner(messages="all") def grep_scanner( pattern: str | list[str] | dict[str, str | list[str]], *, regex: bool = False, ignore_case: bool =