Skip to content

BUG: OpenAIChatTarget(n>1) requests n choices but keeps only choices[0] #4742

Todo

Description

Describe the bug

OpenAIChatTarget(n=3) sends n=3, so the API generates and bills for 3 choices, but the response contains only the first. The other choices, including a content_filter one, are silently dropped.

Root cause: the Chat Completions response parser (pyrit/prompt_target/common/chat_completions_response_parser.py, e.g. message = response.choices[0].message around line 267 and the choices[0] finish-reason check) only looks at choices[0]. By contrast, OpenAICompletionTarget keeps every choice ([choice.text for choice in response.choices]).

The n docstring ("How many chat completion choices to generate for each input message") suggests the extra choices are meant to be usable.

Steps/Code to Reproduce

import asyncio
from unittest.mock import AsyncMock

from openai.types.chat import ChatCompletion
from openai.types.completion import Completion

from pyrit.models import Message, MessagePiece
from pyrit.prompt_target import OpenAIChatTarget, OpenAICompletionTarget
from pyrit.setup import IN_MEMORY, initialize_pyrit_async


def user_message():
    return Message(message_pieces=[MessagePiece(role="user", original_value="hi")])


async def main():
    await initialize_pyrit_async(memory_db_type=IN_MEMORY, silent=True)

    chat = OpenAIChatTarget(model_name="gpt-4o", endpoint="https://api.openai.com/v1", api_key="k", n=3)
    chat._async_client.chat.completions.create = AsyncMock(
        return_value=ChatCompletion.model_validate({
            "id": "x", "object": "chat.completion", "created": 0, "model": "gpt-4o",
            "choices": [
                {"index": i, "finish_reason": reason, "message": {"role": "assistant", "content": content}}
                for i, (content, reason) in enumerate([("answer A", "stop"), ("answer B", "stop"), ("", "content_filter")])
            ],
        })
    )
    out = await chat.send_prompt_async(message=user_message())
    print("request n =", chat._async_client.chat.completions.create.call_args.kwargs.get("n"))
    print("OpenAIChatTarget pieces:", [p.converted_value for m in out for p in m.message_pieces])

    completion = OpenAICompletionTarget(model_name="gpt-35-turbo-instruct", endpoint="https://api.openai.com/v1", api_key="k", n=3)
    completion._async_client.completions.create = AsyncMock(
        return_value=Completion.model_validate({
            "id": "c", "object": "text_completion", "created": 0, "model": "m",
            "choices": [{"index": i, "text": text, "finish_reason": "stop"} for i, text in enumerate(["A", "B", "C"])],
        })
    )
    out = await completion.send_prompt_async(message=user_message())
    print("OpenAICompletionTarget pieces:", [p.converted_value for m in out for p in m.message_pieces])


asyncio.run(main())

Expected Results

Either every choice is returned, one piece per choice as OpenAICompletionTarget does, or n > 1 is rejected or warned about so callers don't pay for output they can't see.

Actual Results

request n = 3
OpenAIChatTarget pieces: ['answer A']
OpenAICompletionTarget pieces: ['A', 'B', 'C']

Possible fix

Returning all choices touches the tool-call loop, refusal handling and scoring, which all assume one assistant reply, so I didn't want to pick a direction without you. Would you prefer:

  1. returning each choice (and how should tool calls in non-first choices be treated?),
  2. rejecting n > 1 on the chat target, or
  3. a warning plus a docstring note?

I'm happy to send a PR for whichever you choose.

Versions

  • OS: macOS 27 (arm64)
  • Python version: 3.13.11
  • PyRIT version: 1.3.0.dev0, installed from main (95ffd2f14) in editable mode with uv sync --locked

AI assistance: an AI coding assistant (Claude Code) helped me find these code paths, write the reproduction and draft this report. I ran the reproduction above against main @ 95ffd2f14; the output shown is from that run.

Activity

  1. romanlutz commented on Dec 1, 2026

    @romanlutz
    Contributor

    I'm not sure why people keep picking up issues when the author clearly states they want to do it themselves... I'll close other people's PRs and will wait for yours Akshay Hitesh Shah (@AkshayShah03), just FYI and there's no hurry.

    Frankly, I'm not sure either. I like not discarding potentially useful information but we don't have a simple way to leverage more than n=1 responses right now. I would probably add a warning (option 3) but curious if Richard Lundeen (@richlundeen) has thoughts perhaps.

  2. AkshayShah03 commented on Dec 1, 2026

    @AkshayShah03
    ContributorAuthor

    Thanks Roman Lutz (@romanlutz)! I'll go with the warning (option 3) unless Richard Lundeen (@richlundeen) would prefer another direction. I'll wait a bit for their input before opening the PR.

  3. richlundeen commented on Dec 1, 2026

    @richlundeen
    Contributor

    Really good issue Akshay Hitesh Shah (@AkshayShah03)!

    Roman Lutz (@romanlutz); here is what I'd do. LMK what you think.

    Proposal

    Continue the conversation with choice 0. Keep choices 1..n-1 as alternatives attached to that response, persisted
    and loaded with it.

    1. Model: Message.choices

    • Add choices: list[Message] to Message (default empty), populated only on assistant responses. In a tool loop,
      each assistant step can have its own alternatives.
    • Each choice is a full Message, not a single piece, because one choice can contain text, audio, and tool calls.
    • Choice 0 is the Message itself. choices holds the alternatives only, so existing code that reads the response
      is unchanged.

    2. Persistence: choice_index on MessagePiece

    • Add a nullable integer choice_index column to the prompt memory entry. NULL or 0 means the main response.
    • Alternatives are stored as ordinary MessagePiece rows with the same conversation_id and sequence as the
      main response, distinguished by choice_index.
    • This reuses the existing table, scores (which attach to piece IDs, so each choice can be scored), and
      data-path/media handling. No new table is needed.
    • Requires an Alembic migration that works on both SQLite and Azure SQL. Follow
      .github/instructions/database.instructions.md.

    3. Reading history

    • Conversation queries such as get_conversation_messages_async return only the main response
      (choice_index NULL or 0) by default. Conversation history sent to targets, normalization, and every existing
      caller is unaffected.
    • When loading a Message, rows with choice_index > 0 for the same conversation_id and sequence are grouped
      into choices.
    • The Message invariant (all pieces share conversation_id, sequence, and role) still holds, because the
      alternatives live in choices, not in message_pieces.

    4. Target and parser

    • build_response_pieces_async, or a sibling helper, builds one Message per choice instead of reading only
      choices[0].
    • Each choice needs its own finish_reason, content-filter flag, and truncation flag.
    • Token usage covers the whole request and is not split per choice. Record it once, on the main response.
    • The target returns [main_message] with main_message.choices populated, so the list[Message] contract stays
      the same.

    5. Setting n: handle it like temperature

    Keep n as a constructor setting with a default, and override it the same way temperature is overridden. Do not
    add a per-request setting.

    • OpenAIChatTarget already takes n in its constructor and already includes it in the target identity next to
      temperature (_build_identifier).
    • To override it, use the registry's normal path: recreate_instance(source=target, params={"n": 3}) builds an
      independent copy of the target with every other setting unchanged. Temperature overrides already work this way
      (pyrit/registry/registry.py, recreate_instance).
    • Because n is part of the target identity, results produced with different n values stay distinguishable in
      memory and analytics, just like different temperatures.
    • Expose it in the GUI catalog the way temperature is: add a supports_n_override flag alongside
      supports_temperature_override in pyrit/backend/mappers/target_mappers.py. Derive it from whether the target
      declares an n parameter, so no separate capability flag is needed.
    • Targets that can't honor n don't declare it, so recreate_instance rejects an n override as an unknown
      parameter. This includes OpenAIResponseTarget, because the Responses API has no n.
    • Add a shared validate_n helper in pyrit/prompt_target/common/utils.py (requires n >= 1), next to
      validate_temperature.

    6. Continuing a different choice

    The target and normalizer never decide which choice wins; that is attack logic (see doc/code/framework.md).

    • Memory provides an operation that copies the conversation (existing duplicate_conversation_async /
      duplicate_messages_async) and makes a chosen alternative the main response in the copy.
    • The attack decides when to call it, for example after scoring all choices, and links the new branch from
      AttackResult.related_conversations. If needed, add a new ConversationType such as ALTERNATIVE.

    Edge cases to handle

    • Choice 0 fails but another succeeds. Validation and retry currently look only at choice 0. Decide the rule:
      retry the whole request, or promote the first successful choice to main. Document whichever is chosen.
    • Converters. Response converters currently run on the returned response. Decide whether they also run on each
      choice. Running them on each choice is probably right so scorers see consistent values.
    • Hashing. The normalizer computes hashes per message. Choices need the same treatment.
    • Tool-call loops. If every choice continued its own tool loop, branches would multiply at each step. The target
      avoids this by continuing only one path:
      • Default: keep only the main path. Send n on every step. Continue with choice 0, and attach the alternatives
        to that step's assistant Message.choices. Store alternative tool calls but do not run them. Cost stays at
        one request per step, and each tool runs once, so tools with side effects don't run n times. An attack can later
        copy the conversation at that step and continue an alternative (section 6).
      • Optional: vary only the final answer. Run tool steps with n=1. When a reply has no pending tool calls, make
        one extra request for the other n-1 final answers. Every choice uses the same tool results. The extra request
        is needed because you can't tell a reply is final until it arrives.
      • Separate end-to-end attempts (split once, then run a full loop per choice) produce separate conversations,
        so that belongs in the attack, not the target.
      • Today no target needs this: only OpenAIResponseTarget loops, and the Responses API has no n. It applies to
        future tool-loop support in a chat target. For now, I think we should nix this.

    Suggested PR breakdown

    1. Fail fast: reject or warn on n > 1 in OpenAIChatTarget until the rest lands, so users stop paying for
      discarded choices. This is your proposal above so I don't think much needs to change here for the PR you're creating Akshay Hitesh Shah (@AkshayShah03)
    2. Message.choices, the choice_index column and migration, and memory read/write so main-history queries
      exclude alternatives.
    3. Chat Completions parser and target: build all choices, validate n, and expose n overrides like
      temperature.
    4. Attack-side support: score choices, continue a chosen alternative, and record related conversations.
  4. richlundeen commented on Dec 2, 2026

    @richlundeen
    Contributor

    Actually, please pause on my above comments. Sry, I was thinking about this on my drive. I want to research a couple things and I'll respond tomorrow

  5. richlundeen commented on Dec 3, 2026

    @richlundeen
    Contributor

    Following up on my "pause" comment: let's deprecate n instead of building multi-choice support. I'm withdrawing the proposal above.

    What I found:

    • Every API that offers n also accepts the full conversation history from the caller: Chat Completions, Gemini's candidateCount, and xAI's sample_batch. So sending the prompt once per sample, each in its own copy of the conversation, gets the same samples. Each one also goes through PyRIT's normal converters, scoring, retries and content-filter handling, and can be continued like any other conversation. The GUI's n= button already works this way.
    • Providers are dropping it. The Responses API has no n, Gemini 3.x and later reject candidateCount, xAI marks sample_batch for deprecation, and Anthropic never had it.
    • The only thing we lose is billing the prompt once for all samples, and today the extra choices are thrown away anyway.

    Plan:

    1. Deprecate the n argument on OpenAIChatTarget, LiteLLMChatTarget and OpenAICompletionTarget, for removal in 1.4.0.
    2. When it's removed, reject n > 1 in extra_body_parameters on the chat targets, since they only read the first choice.

    Akshay Hitesh Shah (@AkshayShah03), #4793 can become the deprecation PR; I left the details there. Thanks for the careful report!

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

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions