翻篇收录说明
翻篇网页快照

Scanner Tools – Inspect Scout

https://meridianlabs-ai.github.io/inspect_scout/scanner_tools.html

最近抓取:2026-12-04 20:57:09(北京时间)

最近内容变化:2026-12-02 08:24:19(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Transcript Analysis for AI Agents

正文摘录

Overview The LLM Scanner provides a high-level, batteries-included interface for building LLM-based scanners. Under the hood, it is composed of several lower-level tools: message numbering, prompt construction, answer generation, message extraction, and result reduction. You can use these tools directly when you need more control. For straightforward scanning tasks, prefer llm_scanner() as it handles the entire pipeline for you. Use lower level scanner tools when you need to override or extend specific steps. Here is roughly the implementation of llm_scanner(), but using the lower level tools that we’ll cover in more depth below (click on the numbers at right for further explanation): from inspect_scout import ( Result, ResultReducer, Scanner, Transcript, generate_answer, message_numbering, scanner, scanner_prompt, transcript_messages ) @scanner(messages="all") def environment_scanner() -> Scanner[Transcript]: async def scan(transcript: Transcript) -> Result: # setup numbering and references 1 messages_as_str, extract_refs = message_numbering() # define question to ask llm question = ( "Did the agent fail to complete the task due to " "a broken or misconfigured environment?" ) # scan segments (breaks up transcript to fit in context window) results: list[Result] = [] 2 async for segment in transcript_messages( transcript, messages_as_str=messages_as_str ): # generate prompt using segment, question, and answer type 3 prompt = scanner_prompt( messages=segment.messages_str, question=question, answer="boolean" ) # generate, extract answer/explanation and append results results.append( 4 await generate_answer( prompt, "boolean", extract_refs=extract_refs, ) ) # reduce per-segment results into a single result 5 return await ResultReducer.any(results) return scan 1 Setup message numbering (returns a function that can be used to number and a function that can be used to extract references to messages from model explanations). 2 Iterate over transcript segments (if the transcript exceeds the size of the scanning model’s context window it will need to be broken into segments). 3 Build a prompt for the scanner using the string for this segment (numbered messages), the question, and the answer type. 4 Call the model to generate an answer, extracting references from its explanation using the extract_refs function. 5 When context-window segmentation produces multiple segments, reduce them into a single result. Here we use the .any() reducer which returns True if any segment result was True. Message Presentation The message_numbering() function creates a pair of functions that share a closure-captured counter and message ID map. This enables consistent message numbering across multiple calls (e.g., across segments) and lets you extract [M1]-style references from model output back to the original messages. from inspect_scout import message_numbering messages_as_str, extract_refs = message_numbering() The returned functions work together: messages_as_str(messages) — Renders a list of ChatMessage objects into a numbered string (e.g., [M1] USER: ...). The counter auto-increments across calls, so a second call continues from where the first left off. extract_refs(text) — Resolves [M1], [M2], etc. citations in model output back to Reference objects pointing to the original messages. Preprocessing You can pass a MessagesPreprocessor to control which message content is included in the rendered output: from inspect_scout import message_numbering, MessagesPreprocessor messages_as_str, extract_refs = message_numbering( preprocessor=MessagesPreprocessor( exclude_system=True, # exclude system messages (default) exclude_reasoning=True, # exclude reasoning content exclude_tool_usage=True, # exclude tool calls and output ) ) exclude_system Exclude system messages (defaults to True) exclude_reasoning Exclude reasoning content (defaults to False) exclude_tool_usage Exclude tool calls and output (defaults to False) transform Optional async function that takes the message list and returns a filtered list. When no preprocessor is provided, the default behaviour is to exclude system messages only. Custom Role Labels By default the role prefix in each rendered message is the uppercased ChatMessage.role (e.g. USER:, ASSISTANT:, TOOL:). Set ChatMessage.metadata["role_label"] to a non-empty string to override the prefix for that message. The label is uppercased to match the default convention: from inspect_ai.model import ChatMessageUser ChatMessageUser(content="...", metadata={"role_label": "student"}) # renders as: # STUDENT: # ... The label is honored by message_as_str, messages_as_str (text, list, and format="json" — where it becomes the "role" field), message_numbering (it appears after the [M1] prefix), and any scanner built on these (including llm_scanner). If your messages don’t already carry role_label metadata (e.g. transcripts loaded from an external source), you can attach it on the fly with MessagesPreprocessor.transform: from inspect_ai.model import ChatMessage from inspect_scout import MessagesPreprocessor async def add_role_labels(messages: list[ChatMessage]) -> list[ChatMessage]: for m in messages: # derive a label from whatever signal applies (turn index, agent # name in another metadata field, content prefix, etc.) m.metadata = (m.metadata or {}) | {"role_label": "..."} return messages preprocessor = MessagesPreprocessor(transform=add_role_labels) Prompt Construction The scanner_prompt() function renders the default scanner template—the same template used internally by llm_scanner(). It combines the transcript messages, question, and answer type into a complete prompt: from inspect_scout import scanner_prompt prompt = scanner_prompt( messages=segment.messages_str, question="Did the assistant refuse the user's request?", answer="boolean", ) Custom Prompts For fully custom prompt templates, use answer_type() to resolve an AnswerSpec into an Answer object that exposes .prompt and .format strings: from inspect_scout import answer_type answer = answer_type("boolean") # answer.prompt -> "Answer the following yes or no question..." # answer.format -> "The last line of your response should be..." prompt = f"""Here is a conversation: {segment.messages_str} {answer.prompt} {question} {answer.format} """ This gives you complete control over prompt structure while reusing the answer-type-specific formatting instructions. Answer Generation The generate_answer() function calls the LLM and parses the response into a Result. It supports all answer types, handles refusal retries, and uses tool-based generation for structured answers: from inspect_scout import generate_answer result = await generate_answer( prompt, answer="boolean", extract_refs=extract_refs, ) prompt The scanning prompt (string or message list). answer Answer specification ("boolean", "numeric", "string", list[str], AnswerMultiLabel, or AnswerStructured). model Model to use for generation. Defaults to the current default model. retry_refusals Number of times to retry on content filter refusals (default 3). parse When True (default), parse the output into a Result. When False, return the raw ModelOutput. extract_refs Function to extract [M1]-style references from the explanation. Only used when parse=True. value_to_float Optional function to convert the parsed value to a float. Only used when parse=True. In addition to the serialized value, the returned Result carries the typed parsed answer in its parsed field. For AnswerStructured this is the validated instance of your Pydantic type, with the result typed accordingly: from pydantic import BaseModel, Field from inspect_scout import AnswerStructured, generate_answer class Detection(BaseModel): behavior: str = Field(description="Behavior observed.") confidence: float = Field(description="Confidence from 0 to 1.") # Result[Detection] result = await generate_answer(prompt, answer=AnswerStructured(Detection)) if result.parsed is not None: print(result.parsed.confidence) Note that parsed is None when the response could not be parsed. It is also dropped whenever the Result is serialized, so it does not appear in stored results. Answer Parsing The parse_answer() function provides pure parsing without making an LLM call. Use this when you generate model output through your own code (e.g., via get_model().generate()) but want to use the standard answer extraction logic: from inspect_ai.model import get_model from inspect_scout import parse_answer # generate with your own code model = get_model("openai/gpt-4o") output = await model.generate(prompt) # parse using standard answer extraction result = parse_answer( output, answer="boolean", extract_refs=extract_refs, ) output The ModelOutput to parse. answer Answer specification (same types as generate_answer()). extract_refs Function to extract [M1]-style references from the explanation text. value_to_float Optional function to convert the parsed value to a float. As with generate_answer(), the returned Result carries the typed parsed answer in its parsed field (though for AnswerStructured answers, parse_answer() raises ValidationError on non-conforming output rather than returning parsed=None). Answer Types The answer parameter accepted by scanner_prompt(), generate_answer(), and parse_answer() is an AnswerSpec—a union type that determines how the LLM is prompted, how answers are extracted, and the Python type of the result value: Type LLM Output Result Type boolean ANSWER: yes bool numeric ANSWER: 10 float string ANSWER: brown fox str label ANSWER: C str labels (multiple) ANSWER: C, D list[str] structured JSON object dict[str,JsonValue] Multi-Label Classification Pass list[str] to prompt the model to select a single label. To allow multiple label selections, wrap the labels in AnswerMultiLabel: from inspect_scout import AnswerMultiLabel answer = AnswerMultiLabel(labels=[ "Factual error", "Refusal", "Off-topic response", "Hallucination", ]) Label values (A, B, C, …) are assigned automatically b