Skip to content

FEAT: Add tool priming via simulated conversations with target tools - #4253

Open
Behnam (behnam-o) wants to merge 34 commits into
microsoft:mainfrom
behnam-o:agents/pyrit-simulated-tool-calls-feature
Open

Behnam (behnam-o) wants to merge 34 commits into
microsoft:mainfrom
behnam-o:agents/pyrit-simulated-tool-calls-feature

Conversation

@behnam-o

@behnam-o Behnam (behnam-o) commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Adds tool priming: before each attack, a simulated conversation fabricates the objective target's own tool calls and results, against the tools the target actually offers, and prepends them before the objective. Tool-using agents tend to trust their own earlier tool results, so a history that "approves" the request can unlock objectives the target refuses when asked directly.

This extends the existing simulated conversation rather than adding a new seed or generator:

  • SeedSimulatedConversation gains mode and use_target_tools, left out of technique fingerprints at their defaults so existing techniques keep theirs:
    • TURN_BY_TURN (default) is the existing two-model conversation. With use_target_tools, the stand-in target gets the objective target's tools and the adversarial chat writes each tool result.
    • ONE_SHOT has the adversarial chat write the whole history in one pass with exactly num_turns tool calls. A deterministic check (known tools, schema-valid arguments, answered calls, shape, call count) feeds problems back until the history passes.
  • generate_simulated_conversation_async takes mode, tools, simulated_target and a runtime max_attempts budget for one-shot writing; a tool-configured simulated_target (real tools, stubs, or MCP) can be passed when calling it directly in turn-by-turn mode. One-shot mode rejects a next-message prompt, converters, a simulated target, and memory labels, which it would otherwise ignore.
  • PromptTarget.get_tool_definitions_async, implemented by OpenAIResponseTarget, OpenAIChatTarget and LiteLLMChatTarget, which also set a new supports_function_tools capability from their configured and declared tools. Targets also declare RUNS_TOOLS_LOCALLY, which decides whether one can stand in for a tool-using target.
  • An unusable history, or an objective target with no tools, is recorded as a preparation_failure instead of failing the run. Attacks that can't record one (such as Crescendo and TAP) raise AdversarialChatResponseBlockedException only when the adversarial chat was blocked or refused, and otherwise a ValueError that names the failure kind.
  • Techniques that use the target's tools add supports_function_tools and native tool-call history to their objective-target requirements, so other targets are skipped.
  • Any turn-by-turn simulated conversation (including existing ones like crescendo_simulated) whose stand-in turn ends in an error is now recorded as a preparation_failure (undetermined) instead of failing the run. Empty stand-in replies are dropped with the user turn they answer, and a conversation with no replies is a preparation_failure too.
  • tool_priming_one_shot in the extra technique catalog, and tool_priming_simulated in the opt-in ToolsInitializer, registered when the adversarial chat runs tool calls. Plus a how-to notebook.

Follow-ups, not in this PR: configuring a custom stand-in target from a technique, and replay datasets of fixed tool histories.

Adds a catalog attack technique that primes a tool-using target with a fabricated history of its
own tool calls and results, written by an adversarial model against the tools the target actually
reports. A deterministic check rejects unknown tools, schema-invalid arguments, unanswered calls and
shape violations, and the adversarial model revises the history until it passes. The history is
prepended natively before the objective.

- SeedSimulatedToolHistory seed and SimulatedToolHistoryGenerator
- PromptTarget.get_tool_definitions_async, implemented by OpenAIResponseTarget
- Prepended histories are checked against the objective target's tools when attacks are prepared
- tool_call_priming entry in the extra technique catalog, a sample replay dataset, and a how-to notebook

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 12, 2026 21:46

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved defects conflate distinct attack configurations in persisted results, cause objective/history sequence collisions, and misreport callbacks as tools, leading to duplicate-name failures and schema loss.

3 open issues
What changed in this PR

Adds tool_call_priming to PyRIT’s technique catalog, enabling attacks to prepend fabricated tool-call histories based on the objective target’s advertised tools.

Changes:

  • Adds configurable history generation with validation and revision feedback.
  • Introduces tool-definition reporting and checks replayed calls against target tool schemas.
  • Integrates the technique with seed preparation, tests, a sample dataset, and a walkthrough.
File Description
tests/​unit/​setup/​test_technique_initializer.py Adds the technique to expected registrations.
tests/​unit/​scenario/​core/​test_attack_technique_factory.py Tests factory requirements and execution wiring.
tests/​unit/​prompt_target/​target/​test_tool.py Tests advertised tool reporting.
tests/​unit/​prompt_target/​target/​test_tool_call_history.py Tests history and argument validation.
tests/​unit/​models/​test_seed_group.py Tests history reservations and group constraints.
tests/​unit/​memory/​test_memory_models.py Tests rejection of generation-config storage.
tests/​unit/​executor/​promptgen/​test_simulated_tool_history_generator.py Covers generation, revisions, and validation failures.
tests/​unit/​executor/​attack/​core/​test_attack_parameters.py Tests generated and replayed history preparation.
tests/​unit/​executor/​attack/​core/​test_attack_executor.py Tests objective-target forwarding.
tests/​unit/​datasets/​test_local_prompt_dataset_semantics.py Validates the sample replay dataset.
pyrit/​setup/​initializers/​techniques/​extra.py Registers tool_call_priming.
pyrit/​scenario/​core/​attack_technique_factory.py Adds factory construction and adversarial-target resolution.
pyrit/​prompt_target/​openai/​openai_response_target.py Reports function-tool definitions.
pyrit/​prompt_target/​common/​tool_provider.py Converts tools to callback-free definitions.
pyrit/​prompt_target/​common/​tool_call_history.py Validates tool contracts and history ordering.
pyrit/​prompt_target/​common/​prompt_target.py Introduces the tool-reporting interface.
pyrit/​models/​target/​tool_definition.py Defines the shared tool-contract model.
pyrit/​models/​seeds/​seed_simulated_tool_history.py Adds generation settings and history shapes.
pyrit/​models/​seeds/​seed_grouping.py Accepts tool-history configuration seeds.
pyrit/​models/​seeds/​seed_group.py Handles generated-history constraints and accessors.
pyrit/​models/​seeds/​seed_dataset.py Extends grouping to the new seed type.
pyrit/​models/​seeds/​attack_seed_group.py Extends merge checks and sequence preservation.
pyrit/​models/​seeds/​__init__.py Exports the new seed and shape enum.
pyrit/​models/​__init__.py Exports tool-history models.
pyrit/​memory/​memory_models.py Rejects storing runtime generation configurations.
pyrit/​executor/​promptgen/​simulated_tool_history_generator.py Implements history generation and revision.
pyrit/​executor/​promptgen/​__init__.py Exports the generator and its types.
pyrit/​executor/​attack/​core/​attack_parameters.py Generates histories and validates replayed calls.
pyrit/​executor/​attack/​core/​attack_executor.py Supplies the target for tool-history preparation.
pyrit/​datasets/​seed_datasets/​local/​examples/​tool-call-priming.prompt Adds two fixed replay examples.
pyrit/​datasets/​executors/​promptgen/​simulated_tool_history.yaml Defines the generation prompt and response schema.
doc/​myst.yml Adds the walkthrough to navigation.
doc/​code/​scenarios/​4_tool_call_priming.py Demonstrates generation, inspection, and replay.
doc/​code/​scenarios/​4_tool_call_priming.ipynb Provides the rendered walkthrough and outputs.
doc/​code/​framework.md Documents tool reporting and replay validation.

Review effort: Balanced

Behnam Ousat and others added 3 commits November 12, 2026 14:06
- Place an appended objective after a simulated tool history's reserved sequence range.
- Include the tool-history writer in the atomic attack's identity, as for simulated conversations.
- Stop reporting custom_functions callbacks as advertised tools; declared tools keep their schemas.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Removes the replay pieces (sample replay dataset, prepended-history check against the objective
target's tools, and the notebook's replay sections) so the PR covers only the technique itself.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- OpenAIChatTarget and LiteLLMChatTarget report the function tools declared in extra_body_parameters,
  through a parser shared with OpenAIResponseTarget.
- The notebook notes which targets qualify and that outcomes vary by model, and shows a successful run.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@behnam-o
Behnam (behnam-o) marked this pull request as ready for review November 12, 2026 23:59
Comment thread doc/code/framework.md Resolved
@richlundeen

Copy link
Copy Markdown
Contributor

⁠Rather than having a new generator, should we extend generate_simulated_conversation? I think setting the conversation up between two models is more flexible. For example, we could set it up as a fake video game developer with an objective and give the adversarial model fake specific tools, or real tools.

Could we reuse simulated_conversation instead of adding SimulatedToolHistoryGenerator? It already uses RedTeamingAttack. Accepting a separate, tool-configured simulated_target would let us build realistic, escalating conversations using real tools, stubbed responses, or a fake MCP server. Tool execution stays on the target; the generated history preserves the structured calls and results.

Below, simulated_target is the proposed new parameter. Assume the models, scorer, and SeedPrompt templates are initialized.

Real tool calls through MCP

history = await generate_simulated_conversation_async(
    objective=objective,
    adversarial_chat=adversarial_chat,
    objective_scorer=scorer,
    adversarial_chat_system_prompt=adversarial_prompt,
    simulated_target_system_prompt=target_prompt,
    simulated_target=OpenAIResponseTarget(
        tool_providers=[real_mcp_provider],
    ),
)

Model-generated tool calls with simulated results

@tool
async def get_project_context(repo: str) -> str:
    """Read the project's background and purpose."""
    return f"{repo} is a video-game project with fictional characters."

history = await generate_simulated_conversation_async(
    objective=objective,
    adversarial_chat=adversarial_chat,
    objective_scorer=scorer,
    adversarial_chat_system_prompt=adversarial_prompt,
    simulated_target_system_prompt=target_prompt,
    simulated_target=OpenAIResponseTarget(
        tools=[get_project_context],
    ),
)

The second example still lets the model decide when to call the tool; only its result is fabricated. A fake MCP provider could serve the same purpose.

Behnam Ousat and others added 5 commits November 17, 2026 11:42
Folds the tool-history seed and generator into SeedSimulatedConversation as modes, per review:
- SeedSimulatedConversation gains mode (TURN_BY_TURN or ONE_SHOT), use_target_tools and max_attempts.
  New fields enter the stored identity only when set, so existing configurations keep their hashes.
- generate_simulated_conversation_async dispatches on mode. ONE_SHOT runs the one-shot history writer;
  TURN_BY_TURN with tools gives the stand-in target the objective target's tools, with results written by
  the adversarial chat, and accepts an explicit simulated_target. Unusable one-shot output is recorded as
  a preparation failure.
- Catalog: tool_priming_one_shot and tool_priming_simulated replace tool_call_priming.
- The history schema moves to the shared json_schemas registry; the prompt no longer repeats it.
- Removes SeedSimulatedToolHistory and ToolHistoryShape, and the framework.md note.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Move the one-shot writer out of promptgen into simulated_conversation as
private helpers, and make num_turns the exact number of tool calls the
history must make, enforced by the existing validation feedback loop.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…ted-tool-calls-feature

# Conflicts:
#	doc/myst.yml
#	pyrit/prompt_target/litellm_chat_target.py
#	pyrit/prompt_target/openai/openai_chat_target.py
#	pyrit/prompt_target/openai/openai_response_target.py
#	tests/unit/scenario/core/test_attack_technique_factory.py
@behnam-o Behnam (behnam-o) changed the title FEAT: Add tool_call_priming technique (simulated tool-call histories) FEAT: Add tool priming via simulated conversations with target tools Nov 23, 2026
@behnam-o

Copy link
Copy Markdown
Collaborator Author

Richard Lundeen (@richlundeen) Done. The generator is gone: tool priming is now a mode of SeedSimulatedConversation / generate_simulated_conversation_async.

  • TURN_BY_TURN + use_target_tools: your two-model setup. The stand-in gets the target's tools, and you can pass a tool-configured simulated_target (real tools, stubs, MCP) when calling it directly (tool_priming_simulated).
  • ONE_SHOT: the adversarial chat writes the whole tool history in one pass, validated until it passes (tool_priming_one_shot).

Picking a custom stand-in from a technique is a follow-up. Mind taking another look? varunj-msft too, since the design changed after your approval.

Behnam Ousat and others added 3 commits November 23, 2026 15:14
…otebook

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…errors as history

Passing both tools and simulated_target now raises instead of replacing the
target's tools, and a stand-in turn that ended in an error is recorded as a
SIMULATED_TARGET_ERROR preparation failure instead of being prepended.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Write all tool results of a simulated conversation in one adversarial
  conversation, load its prompt once off the event loop, and record a
  blocked, refused, or empty tool result as a preparation failure.
- End one-shot generation on blocked or refused replies instead of
  retrying them as invalid JSON, and record the matching failure kind.
- Replace the generic history checker in prompt_target with one-shot
  validation of the parsed items, with tool schemas compiled once.
- Allow any tool-running target (OpenAIResponseTarget, LiteLLMChatTarget)
  as the stand-in, and report LiteLLMChatTarget's configured tools.
- Keep the unused stand-in prompt out of one-shot identity, fix the
  sequence_range docstring, always pass objective_target when building
  attack parameters, and make the tool-history requirement a class constant.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

@varunj-msft varunj-msft left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the follow-up commits, LiteLLM and Claude targets now report their tools. Two things I'd still like to sort out before merging: tool_priming_simulated landing in the extra/all aggregates, and LiteLLM as the stand-in. The other three comments are optional. Happy to approve once those two are in.

Behnam Ousat and others added 3 commits November 24, 2026 09:25
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Register tool_priming_simulated in the opt-in ToolsInitializer, only when
  the adversarial chat runs tool calls, so extra/all aggregates no longer
  fail with the default chat-completions adversarial chat.
- Skip targets that advertise no function tools during technique matching
  (TechniqueRequirements.requires_target_tools, PromptTarget.may_advertise_tools).
- Drop empty stand-in turns instead of discarding the whole conversation.
- Give the stand-in copy only the simulated tools: no inherited tool
  providers, custom functions, or declared and hosted tools.
- Treat extra_body_parameters tools=None as no tools.
- Test the overflow renumbering, reused call_id check, and tool-result
  conversation link.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inclusion review: keep the scope, simplify two shapes

This follows the earlier discussion in #4253 (comment) and the reply in #4253 (comment). Moving tool priming into modes of SeedSimulatedConversation / generate_simulated_conversation_async is the right direction. Keep both modes, both techniques, the target tool reporting, and requires_target_tools. Before the implementation review, change these two shapes:

  1. Keep max_attempts out of the seed identity. For a mode other than TURN_BY_TURN, SeedSimulatedConversation._config_dict adds max_attempts. That mapping sets value and get_identifier(), and SeedEntry reads it back from memory (memory_models.py). But max_attempts is only the retry budget of the writing loop in simulated_conversation.py. So two seeds that differ only in retries get a different stored value, hash, and identifier, and tool_priming_one_shot (max_attempts=5) stores a runtime setting. The framework says that identifiers leave out retries. Make it a runtime argument of the generation call (passed through the technique), or a generator constant, and remove it from _config_dict and from the memory read-back.

  2. Check a declared capability, not a class list, for local tool execution. runs_tools_locally returns isinstance(target, (OpenAIResponseTarget, LiteLLMChatTarget)). AttackTechniqueFactory.check_adversarial_target and ToolsInitializer use it, and _with_simulated_tools also branches on OpenAIResponseTarget. The framework says to match requirements to capabilities, not to concrete classes. The list is already out of date: #4595 is on main after this PR's merge base and lets OpenAIChatTarget run local tools. After a rebase, the PR rejects a tool-running OpenAIChatTarget adversarial chat, and ToolsInitializer does not register tool_priming_simulated for it. Let targets declare that they run tool calls locally, check that declaration, and rebase on main.

I did not review the implementation in detail. That review follows these changes.

Behnam Ousat and others added 2 commits November 24, 2026 12:04
…_priming_simulated single_turn

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Merge main, including microsoft#4595 (OpenAIChatTarget runs local tools); tool
  reporting moves into the shared Chat Completions tool-loop mixin.
- Replace the stand-in class list with a declared RUNS_TOOLS_LOCALLY flag
  on targets, so a tool-running OpenAIChatTarget can stand in.
- Keep max_attempts out of the seed's identity: it is now only a runtime
  argument of generate_simulated_conversation_async (default 5).
- Record a preparation failure when every stand-in reply is empty.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@behnam-o

Copy link
Copy Markdown
Collaborator Author

Richard Lundeen (@richlundeen) Both done:

  1. max_attempts is no longer on the seed or in its identity; it's a runtime argument of generate_simulated_conversation_async (default 5).
  2. Targets declare RUNS_TOOLS_LOCALLY (Responses target and the shared Chat Completions tool loop, so OpenAIChatTarget after FEAT: Run local tools with OpenAIChatTarget #4595 too); the class list is gone.

Merged main. Ready for your implementation review.

Behnam Ousat and others added 10 commits November 24, 2026 13:31
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…verridden

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The tool-history target requirements now live on TechniqueRequirements and
are checked whenever requires_target_tools is set, so a requirements=
override no longer drops them.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
A reply from a reasoning model can start with a reasoning piece, which
was used as the tool result. Also correct two docstrings about the
default stand-in and combining simulated_target with tools.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
OpenAIResponseTarget already orders reasoning after the answer, and other
targets keep reasoning in metadata, so the text-only filter handled a case
no target produces. The docstring fixes from that commit stay.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

@varunj-msft varunj-msft left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both blockers are fixed at 023c3b6, and the three optional ones too (I checked each in its thread). I left three smaller notes inline: I'd still fix the first two before merging, but they don't need another round from me, and the third is optional. Rich's implementation review still applies.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review complete at 023c3b69. The open P2 concerns need changes before approval: declare tool compatibility through the shared capability path, preserve nonblocked preparation errors, reject blank authored call IDs, and strip nested tool configuration with regression coverage. The existing blank-ID and nested-tool threads already cover those two causes; replies add evidence without duplicate findings.

Behnam Ousat and others added 7 commits November 25, 2026 10:42
The stand-in copy removed only the top-level tools and tool_choice, so tools in a nested
extra_body reached it: a chat copy failed to build and a Responses copy sent the source's
tools. The copy and the capability probe now share one helper that strips every tool
setting at both levels.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The configuration fingerprint walks every seed field, so the new mode and use_target_tools
changed the fingerprint of the ten existing simulated techniques even at their defaults,
and technique edits saved before this change no longer resolved. Both fields are now left
out at their defaults, and a test pins a fingerprint computed before they existed.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
A blank call_id passed one-shot validation and only failed later, when the objective was
sent. Calls and outputs now require a nonblank call_id, matching FunctionOutputContent, so
the adversarial chat gets the problem as feedback and can revise the history.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Attacks whose parameters cannot record a preparation failure (Crescendo, RedTeaming, TAP)
got every simulated-conversation failure as AdversarialChatResponseBlockedException, so an
unusable one-shot history or a stand-in error was reported as a block. Blocked and refused
keep that exception; any other kind raises a ValueError that names it.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
In ONE_SHOT mode, a next-message prompt, converter configuration, simulated target, or
memory labels were silently ignored. They now raise a ValueError naming them, and the
stand-in checks run only in TURN_BY_TURN mode, which uses them.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…chat

tool_priming_simulated needs a single adversarial chat that runs tool calls. With several
ADVERSARIAL_CHAT endpoints the default adversarial_chat is a round-robin that does not, so
the text now explains the swap cell by that requirement instead of the recorded run.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Whether an objective target has function tools was a separate may_advertise_tools() check
behind TechniqueRequirements.requires_target_tools, outside the declared capabilities, so
capability reports and the target snapshot did not show it. Targets now declare it as
supports_function_tools: the Responses, Chat and LiteLLM targets set it from their configured
tools, tool providers and declared function tools, also over a custom configuration, since
recreate_instance gives a copy its source's configuration. With use_target_tools, the factory
adds the capability and native tool-call history to the objective-target requirements, which
the shared TargetRequirements check enforces. requires_target_tools and may_advertise_tools
are removed, so TechniqueRequirements matches main again.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants