Inferensys

Prompt

Agent Session Reconstruction Prompt for Auditors

A practical prompt playbook for using Agent Session Reconstruction Prompt for Auditors in production AI workflows.
Developer reviewing multi-agent chat interface on laptop, agent conversation logs visible, casual coding session at WeWork desk.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the core job, the intended user, required inputs, and the boundaries where this prompt should not be applied.

This prompt is designed for auditors, governance engineers, and compliance officers who need to reconstruct a single, coherent narrative from raw multi-agent execution logs. The job-to-be-done is transforming fragmented, timestamped event streams—user requests, agent reasoning steps, tool calls, and final outputs—into a chronological, human-readable summary suitable for audit review. The ideal user is someone who already has access to structured or semi-structured agent logs but lacks the time to manually piece together a session's causal chain. Required context includes the raw log data, the session identifier, and any known agent role definitions to correctly attribute actions.

You should use this prompt when the audit objective is to understand what happened in a specific user interaction, verify that agent actions were appropriate, or detect missing events. It is particularly effective for post-hoc reviews of escalated support tickets, compliance spot-checks, or debugging unexpected agent behavior. The prompt is designed to handle logs from systems with multiple specialized agents, parallel tool calls, and interleaved events. It explicitly checks for temporal inconsistencies, such as responses that appear before their triggering requests, and flags missing context gaps where a handoff or tool result is referenced but not present in the provided log data.

Do not use this prompt for real-time monitoring dashboards, aggregate trend analysis across thousands of sessions, or as a replacement for structured log storage. It is a reconstruction tool, not a live observability system. If the raw logs contain redacted or encrypted fields, the prompt will note the gap but cannot recover the original data. For high-risk domains such as healthcare or finance, the output of this prompt is a draft audit artifact that requires human review before being accepted as an official record. The next step after generating the narrative is to validate its factual consistency against the source logs using an evaluation rubric, checking for hallucinated events or misattributed actions.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Agent Session Reconstruction Prompt delivers reliable audit narratives and where it introduces unacceptable risk.

01

Good Fit: Structured Log Sources

Use when: Raw logs contain structured agent decision records, tool call payloads, and handoff events with consistent timestamps. The prompt excels at synthesizing these into a linear narrative. Guardrail: Validate that required fields (agent_id, timestamp, event_type) are present before reconstruction; abort with a clear error if the schema is incomplete.

02

Bad Fit: Unstructured or Lossy Logs

Avoid when: Logs are free-text notes, incomplete streams, or missing critical events like tool calls or handoffs. The model will hallucinate plausible transitions to fill gaps. Guardrail: Pre-process logs to detect missing event types and flag the reconstruction as 'partial' with explicit gap markers rather than allowing the model to invent continuity.

03

Required Inputs: Timestamped Event Stream

What to watch: The prompt requires a chronologically ordered list of events with agent identifiers, action types, and payloads. Missing timestamps cause the model to guess ordering. Guardrail: Enforce a strict input schema in the application layer before the prompt is assembled. Reject sessions with fewer than two events or spans exceeding 24 hours without explicit human approval.

04

Operational Risk: Temporal Inconsistency

What to watch: Clock skew, out-of-order ingestion, or missing heartbeat events can create impossible timelines (e.g., a response before the request). The model may silently reorder events to make the narrative coherent. Guardrail: Run a pre-check for timestamp monotonicity and flag reversed events. Include a 'temporal anomalies detected' warning in the output header if any are found.

05

Operational Risk: Sensitive Data Exposure

What to watch: Raw tool call arguments or agent reasoning traces may contain PII, credentials, or business-sensitive parameters that should not appear in an auditor-facing narrative. Guardrail: Redact sensitive fields (API keys, email addresses, payment data) at the application layer before log assembly. Never rely on the prompt to perform redaction.

06

Operational Risk: Narrative Bias

What to watch: The model may frame agent decisions as more deliberate or justified than they were, smoothing over errors or presenting coincidental success as intent. Guardrail: Require the output to separate 'what happened' (event sequence) from 'inferred intent' (model commentary). Include an eval check that every inferred motivation is anchored to an explicit reasoning trace in the source logs.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template with square-bracket placeholders for reconstructing a multi-agent session narrative from raw logs.

This prompt template is designed to be the core instruction you send to an LLM when an auditor needs a chronological, narrative summary of a specific user interaction that spanned multiple agents. It forces the model to act as a forensic analyst, not a creative writer. The template uses square-bracket placeholders for all variable inputs, ensuring you can programmatically inject raw logs, session metadata, and output constraints without manual editing. Before using this template, ensure your raw logs are structured and contain the minimum required fields: a consistent timestamp format, a unique event identifier, and a clear actor (user, agent name, or tool name). The prompt is designed to be strict; it instructs the model to flag missing data rather than hallucinate a coherent story.

text
You are an AI forensic auditor. Your task is to reconstruct a strict chronological narrative of a multi-agent session from the provided raw event logs.

## INPUT DATA
- Session ID: [SESSION_ID]
- User Query: [USER_QUERY]
- Raw Event Log (JSON):
[RAW_EVENT_LOG]

## OUTPUT SCHEMA
Produce a JSON object conforming to this exact schema:
{
  "session_id": "string",
  "reconstruction": {
    "summary": "A one-paragraph executive summary of the user's request and the final outcome.",
    "timeline": [
      {
        "sequence_number": "integer",
        "timestamp": "ISO 8601 string from the log",
        "actor": "user | agent_name | tool_name",
        "action": "A concise, factual description of the event.",
        "reasoning": "The agent's stated reasoning for the action, or null for user/tool events.",
        "source_event_ids": ["list of event IDs from the raw log that support this step"]
      }
    ],
    "anomalies": [
      {
        "type": "temporal_inconsistency | missing_event | duplicate_action | unauthorized_action | other",
        "description": "A clear description of the anomaly.",
        "related_event_ids": ["list of relevant event IDs"]
      }
    ],
    "unresolved_questions": ["A list of questions that cannot be answered from the provided logs alone."]
  },
  "audit_metadata": {
    "generated_at": "ISO 8601 timestamp of this analysis",
    "log_completeness": "complete | partial | corrupt",
    "confidence_score": "0.0 to 1.0 rating of how well the logs support the reconstruction"
  }
}

## CONSTRAINTS
1. **Chronological Order Only:** Reconstruct events strictly by their timestamp. Do not group by agent or topic.
2. **Evidence Grounding:** Every step in the timeline must include `source_event_ids` that directly reference the [RAW_EVENT_LOG]. Do not infer events that are not present in the log.
3. **Anomaly Detection:** Actively scan for temporal inconsistencies (e.g., a response before a request), gaps in the event sequence, and actions taken by agents outside their defined role. Flag these in the `anomalies` array.
4. **Handle Missing Data:** If the logs are incomplete or corrupt, set `log_completeness` to the appropriate value, lower the `confidence_score`, and list specific gaps in `unresolved_questions`. Do not fabricate a clean narrative from bad data.
5. **No Speculation:** The `reasoning` field must be a direct quote or a close, faithful paraphrase of the agent's stated reasoning in the log. If no reasoning is present, use `null`.

## RISK LEVEL
[RISK_LEVEL]

## EXAMPLES
[EXAMPLES]

To adapt this template, start by mapping your internal log schema to the RAW_EVENT_LOG placeholder. The prompt expects a JSON array of event objects, but the model can handle a JSON string if that's how your logging system exports data. The most critical adaptation is the anomalies type list; you should tailor the enum values to match the known failure modes of your specific agent framework. For high-risk audit scenarios, always set the RISK_LEVEL to high and add a final instruction in the CONSTRAINTS section to refuse to answer if the confidence_score falls below a threshold like 0.7. After generating the output, you must validate the JSON against the schema and verify that every source_event_ids reference is a real ID in the input log to prevent hallucinated citations.

IMPLEMENTATION TABLE

Prompt Variables

Required and optional inputs for the Agent Session Reconstruction Prompt. Each placeholder must be populated with validated data before the prompt is sent. Missing or malformed inputs are the most common cause of incomplete reconstructions.

PlaceholderPurposeExampleValidation Notes

[SESSION_ID]

Unique identifier for the user session being reconstructed. Used to scope log retrieval and label the output.

session_2025-01-17_14-22-09_uuid-8a3f

Must match a real session ID in the log store. Null or missing causes retrieval failure. Validate with exists() check before prompt assembly.

[RAW_LOGS]

Complete, unmodified agent execution logs for the session. Includes timestamps, agent IDs, tool calls, responses, and handoff events.

{"events": [{"ts": "2025-01-17T14:22:09Z", "agent": "router", "action": "classify", ...}]}

Must be valid JSON array of event objects. Schema check required: each event must have ts, agent, and action fields. Empty array is valid but will produce a near-empty reconstruction.

[USER_REQUEST]

The original user input that initiated the session. Provides the starting context for the reconstruction narrative.

I need to cancel my subscription and get a refund for last month

String, can be empty for system-initiated sessions. If null, reconstruction must note the session had no explicit user trigger. Validate against session metadata.

[AGENT_ROSTER]

Mapping of agent IDs to human-readable names, roles, and capabilities. Used to annotate which agent performed each action.

{"router": {"name": "Intent Router", "role": "Classifies and routes user requests"}, ...}

Must be a valid JSON object. Each agent ID in RAW_LOGS should have a corresponding entry. Missing entries cause 'Unknown Agent' labels in output. Validate with cross-reference check.

[POLICY_BOUNDARIES]

Document defining allowed agent actions, scope limits, and escalation rules. Used to flag potential boundary violations in the reconstruction.

Agents must not initiate refunds without human approval. Escalation required for amounts over $100.

String or structured policy object. Optional but strongly recommended for audit use. If null, boundary violation checks are skipped. Validate policy version matches session timestamp.

[OUTPUT_SCHEMA]

Expected structure for the reconstructed session narrative. Defines sections, field types, and required elements.

{"sections": ["summary", "timeline", "tool_calls", "handoffs", "anomalies"], "required_fields": ["session_id", "start_time", "end_time"]}

Must be a valid JSON Schema or structured section list. If null, use default reconstruction format. Validate schema is parseable before prompt assembly.

[TEMPORAL_TOLERANCE_SECONDS]

Maximum acceptable gap between sequential events before flagging a temporal inconsistency. Controls anomaly detection sensitivity.

5

Integer, default 5. Values below 1 may generate excessive false-positive gap flags. Values above 60 may miss real inconsistencies. Validate as positive integer.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the session reconstruction prompt into an audit workflow with validation, retries, and human review gates.

This prompt is designed to be called programmatically as part of an audit pipeline, not as a one-off chat interaction. The typical harness receives raw agent logs, session metadata, and a reconstruction request, then assembles the prompt with the required [RAW_LOGS], [SESSION_ID], [USER_QUERY], and [AUDIT_SCOPE] placeholders. The model response should be a structured JSON object containing the chronological narrative, a list of detected anomalies, and a completeness score. Because this output may be used as evidence in compliance reviews, the harness must validate the response against a strict schema before storing it.

Implement a validation layer that checks the reconstructed timeline for internal consistency: every event must have a timestamp, every tool call must have a corresponding response event, and the final agent response must appear after all tool calls. If the model output fails schema validation or contains unresolved placeholders, retry once with a more explicit instruction to fix the specific violation. For high-risk audits, route outputs with a completeness score below 0.8 or with unresolved temporal anomalies to a human review queue. Log every reconstruction attempt, including the raw prompt, model response, validation result, and reviewer decision, to maintain an audit trail of the reconstruction process itself.

Choose a model with strong instruction-following and long-context handling, such as Claude 3.5 Sonnet or GPT-4o, since raw agent logs can exceed 10k tokens. Set temperature to 0 or very low (0.1) to maximize deterministic, repeatable reconstructions. If the logs span multiple sessions or contain tool outputs with sensitive data, apply a redaction step before prompt assembly. Never pass raw PII or credentials into the reconstruction prompt. For production deployments, cache the prompt template and version it alongside your audit tooling so that reconstruction behavior is reproducible across audit periods.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structured JSON payload the prompt must return. Use this contract to validate the model's output before storing it in an audit system or presenting it to a reviewer.

Field or ElementType or FormatRequiredValidation Rule

session_id

string

Must match the [SESSION_ID] input exactly. Fail if missing or mismatched.

reconstruction_timestamp

ISO 8601 datetime

Must be a valid timestamp generated at reconstruction time. Fail if unparseable.

chronological_narrative

array of objects

Array must contain at least one event. Fail if empty or null.

chronological_narrative[].sequence_number

integer

Must be a strictly increasing integer starting from 1. Fail if gaps or duplicates exist.

chronological_narrative[].timestamp

ISO 8601 datetime

Must be parseable and monotonically non-decreasing across the array. Flag if an event timestamp is earlier than its predecessor.

chronological_narrative[].actor

enum: [USER, AGENT, TOOL, HUMAN_REVIEWER, SYSTEM]

Must be one of the allowed enum values. Fail on unrecognized actors.

chronological_narrative[].event_type

string

Must be a descriptive label (e.g., 'user_request', 'tool_call', 'handoff'). Fail if null or whitespace-only.

chronological_narrative[].description

string

Must be a non-empty summary of the event grounded in the provided [RAW_LOGS]. Fail if hallucinated or unsupported.

temporal_inconsistencies

array of objects

Must be an array, even if empty. Each object requires 'event_a_sequence', 'event_b_sequence', and 'description' fields.

missing_events_flag

boolean

Must be true if the prompt detects a gap in the log sequence, false otherwise. Fail if null.

source_log_references

array of strings

Each string must reference a log entry ID present in the [RAW_LOGS] input. Fail if a reference cannot be resolved.

PRACTICAL GUARDRAILS

Common Failure Modes

When reconstructing agent sessions from raw logs, these failure modes surface first. Each card explains what breaks and how to guard against it before auditors see the output.

01

Temporal Inconsistency in Event Ordering

What to watch: Log entries with missing, duplicated, or out-of-order timestamps cause the reconstruction to misrepresent the actual sequence of agent actions. Clock skew between services, buffered writes, and batched log ingestion are common culprits. Guardrail: Sort events by a monotonic sequence ID or Lamport clock, not wall-clock time alone. Flag any event where the timestamp deviates from the sequence order by more than a configurable threshold and surface the anomaly in the audit summary.

02

Missing Intermediate Tool Calls

What to watch: The reconstruction omits tool invocations that occurred between logged steps because some tools log to a separate system, use fire-and-forget semantics, or truncate verbose payloads. Auditors see an incomplete action trail. Guardrail: Cross-reference agent decision logs with a canonical tool execution log. Insert placeholder entries for any tool call referenced in the agent's reasoning but absent from the tool log, marked with a missing-record flag and a confidence note.

03

Hallucinated Narrative Bridging

What to watch: The model fills gaps between sparse log entries with plausible but fabricated reasoning, creating a coherent story that auditors may mistake for ground truth. This is especially dangerous when logs contain only input/output pairs without intermediate rationale. Guardrail: Require the prompt to distinguish between logged and inferred content using explicit markers. Run a post-generation check that every inferred statement has at least one adjacent logged event as an anchor, and flag unsupported narrative spans for human review.

04

Context Window Truncation of Long Sessions

What to watch: Multi-agent sessions with hundreds of steps exceed the model's context window, forcing the reconstruction to drop early events or summarize aggressively. Critical early context—such as the original user request or an initial authorization check—gets lost. Guardrail: Chunk the session into overlapping segments, reconstruct each independently, then merge with a deduplication pass. Always preserve the first N events and the last M events in full. Validate that the merged output references the original user intent from the session start.

05

Agent Identity Confusion in Multi-Agent Traces

What to watch: When logs use inconsistent agent identifiers—short names, UUIDs, role labels—the reconstruction misattributes actions to the wrong agent. An escalation that looks like a handoff to a specialist may be presented as a single agent changing its mind. Guardrail: Normalize all agent identifiers to a canonical agent_id before reconstruction. Include a role-to-agent mapping table in the prompt context. Add a post-reconstruction validation step that checks every attributed action against the canonical agent registry and flags mismatches.

06

Sensitive Data Leakage in Audit Summaries

What to watch: Raw logs may contain PII, credentials, or regulated data in tool arguments, user inputs, or error messages. The reconstruction prompt inadvertently surfaces these in the narrative summary, creating a compliance violation in the audit artifact itself. Guardrail: Redact sensitive fields before they enter the prompt using a pre-processing step with a known redaction schema. Use placeholder tokens such as [REDACTED:email] in the prompt input. Validate the output with a regex and NER-based scan for residual PII before delivering the audit report.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of a reconstructed agent session before sharing it with auditors. Each criterion targets a specific failure mode in multi-agent log reconstruction.

CriterionPass StandardFailure SignalTest Method

Chronological Integrity

All events appear in ascending timestamp order with no backward jumps

Events are out of sequence or timestamps are non-monotonic

Parse all timestamps in the output and assert each is >= the previous timestamp

Event Completeness

Every log event from the raw input is represented in the narrative

Raw log events are missing from the reconstruction without explanation

Count distinct event IDs in raw logs and assert the reconstruction references each one

Temporal Gap Detection

Gaps exceeding [GAP_THRESHOLD] seconds are explicitly flagged with a reason or marked as unknown

A gap > [GAP_THRESHOLD] exists in the timeline but the output makes no mention of it

Compute inter-event deltas and check that any delta > [GAP_THRESHOLD] has a corresponding flag in the output

Tool Call Attribution

Every tool call is attributed to the correct agent and includes function name, arguments, and response summary

A tool call is attributed to the wrong agent or the arguments are hallucinated

Cross-reference each tool call in the reconstruction against the raw tool call log entries by agent ID

User Intent Preservation

The original user request is stated verbatim or accurately paraphrased at the start of the narrative

The user request is missing, altered, or conflated with agent actions

Compare the reconstruction's user request statement against the raw [USER_INPUT] field using a semantic similarity threshold

Handoff Documentation

Every agent-to-agent handoff is recorded with sender, receiver, payload summary, and timestamp

A handoff event from the raw logs is omitted or the payload is misrepresented

Identify all handoff events in raw logs by event type and assert each has a corresponding entry in the reconstruction

Final Response Accuracy

The final agent response in the reconstruction matches the raw [FINAL_OUTPUT] field exactly or within an acceptable paraphrase threshold

The reconstructed final response contains fabricated details not present in the raw output

Run an exact string match or controlled paraphrase comparison between the reconstruction's final response and [FINAL_OUTPUT]

Uncertainty Flagging

Any event with missing data, ambiguous agent identity, or unparseable fields is flagged with an uncertainty note

The reconstruction presents uncertain or missing data as confident fact

Search the reconstruction for uncertainty markers and verify they correspond to known gaps or parse failures in the raw logs

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a single representative log file. Remove strict schema enforcement and focus on narrative coherence. Use a lightweight output format like plain text or simple Markdown rather than a full JSON audit record.

Prompt modification

  • Replace [OUTPUT_SCHEMA] with: Return a chronological narrative with timestamps and agent names.
  • Drop [TEMPORAL_CONSISTENCY_CHECKS] and [MISSING_EVENT_FLAGS] sections.
  • Add: If you cannot determine the order of two events, note the ambiguity.

Watch for

  • Events presented out of order without flags
  • Missing tool call parameters in the narrative
  • Overly confident language when logs are sparse
  • No indication of gaps in the session timeline
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.