Repository navigation
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:
- returning each choice (and how should tool calls in non-first choices be treated?),
- rejecting
n > 1on the chat target, or - 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 withuv 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
romanlutz commentedon Dec 1, 2026
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=1responses right now. I would probably add a warning (option 3) but curious if Richard Lundeen (@richlundeen) has thoughts perhaps.AkshayShah03 commentedon Dec 1, 2026
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.
richlundeen commentedon Dec 1, 2026
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.choiceschoices: list[Message]toMessage(default empty), populated only on assistant responses. In a tool loop,each assistant step can have its own alternatives.
Message, not a single piece, because one choice can contain text, audio, and tool calls.Messageitself.choicesholds the alternatives only, so existing code that reads the responseis unchanged.
2. Persistence:
choice_indexonMessagePiecechoice_indexcolumn to the prompt memory entry.NULLor0means the main response.MessagePiecerows with the sameconversation_idandsequenceas themain response, distinguished by
choice_index.data-path/media handling. No new table is needed.
.github/instructions/database.instructions.md.3. Reading history
get_conversation_messages_asyncreturn only the main response(
choice_indexNULL or 0) by default. Conversation history sent to targets, normalization, and every existingcaller is unaffected.
Message, rows withchoice_index > 0for the sameconversation_idandsequenceare groupedinto
choices.Messageinvariant (all pieces shareconversation_id,sequence, androle) still holds, because thealternatives live in
choices, not inmessage_pieces.4. Target and parser
build_response_pieces_async, or a sibling helper, builds oneMessageper choice instead of reading onlychoices[0].finish_reason, content-filter flag, and truncation flag.usagecovers the whole request and is not split per choice. Record it once, on the main response.[main_message]withmain_message.choicespopulated, so thelist[Message]contract staysthe same.
5. Setting
n: handle it liketemperatureKeep
nas a constructor setting with a default, and override it the same waytemperatureis overridden. Do notadd a per-request setting.
OpenAIChatTargetalready takesnin its constructor and already includes it in the target identity next totemperature(_build_identifier).recreate_instance(source=target, params={"n": 3})builds anindependent copy of the target with every other setting unchanged. Temperature overrides already work this way
(
pyrit/registry/registry.py,recreate_instance).nis part of the target identity, results produced with differentnvalues stay distinguishable inmemory and analytics, just like different temperatures.
supports_n_overrideflag alongsidesupports_temperature_overrideinpyrit/backend/mappers/target_mappers.py. Derive it from whether the targetdeclares an
nparameter, so no separate capability flag is needed.ndon't declare it, sorecreate_instancerejects annoverride as an unknownparameter. This includes
OpenAIResponseTarget, because the Responses API has non.validate_nhelper inpyrit/prompt_target/common/utils.py(requiresn >= 1), next tovalidate_temperature.6. Continuing a different choice
The target and normalizer never decide which choice wins; that is attack logic (see
doc/code/framework.md).duplicate_conversation_async/duplicate_messages_async) and makes a chosen alternative the main response in the copy.AttackResult.related_conversations. If needed, add a newConversationTypesuch asALTERNATIVE.Edge cases to handle
retry the whole request, or promote the first successful choice to main. Document whichever is chosen.
choice. Running them on each choice is probably right so scorers see consistent values.
avoids this by continuing only one path:
non every step. Continue with choice 0, and attach the alternativesto that step's assistant
Message.choices. Store alternative tool calls but do not run them. Cost stays atone request per step, and each tool runs once, so tools with side effects don't run
ntimes. An attack can latercopy the conversation at that step and continue an alternative (section 6).
n=1. When a reply has no pending tool calls, makeone extra request for the other
n-1final answers. Every choice uses the same tool results. The extra requestis needed because you can't tell a reply is final until it arrives.
so that belongs in the attack, not the target.
OpenAIResponseTargetloops, and the Responses API has non. It applies tofuture tool-loop support in a chat target. For now, I think we should nix this.
Suggested PR breakdown
n > 1inOpenAIChatTargetuntil the rest lands, so users stop paying fordiscarded 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)
Message.choices, thechoice_indexcolumn and migration, and memory read/write so main-history queriesexclude alternatives.
n, and exposenoverrides liketemperature.richlundeen commentedon Dec 2, 2026
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
richlundeen commentedon Dec 3, 2026
Following up on my "pause" comment: let's deprecate
ninstead of building multi-choice support. I'm withdrawing the proposal above.What I found:
nalso accepts the full conversation history from the caller: Chat Completions, Gemini'scandidateCount, and xAI'ssample_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'sn=button already works this way.n, Gemini 3.x and later rejectcandidateCount, xAI markssample_batchfor deprecation, and Anthropic never had it.Plan:
nargument onOpenAIChatTarget,LiteLLMChatTargetandOpenAICompletionTarget, for removal in 1.4.0.n > 1inextra_body_parameterson 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!