How PyRIT's HTTP target reaches a custom LLM application
Teams that already run their own chat or LLM API often want to red team it without writing a vendor SDK or changing the application. PyRIT's HTTPTarget handles this by replaying a raw HTTP request that the team captured from the application itself, typically from browser DevTools or from Burp. The request is saved as a template, PyRIT places each attack prompt into the position where the user's message normally goes, and the reply is read back out of the response. Because the target works from the same request the real client sends, the test exercises the application's own authentication headers, cookies, routing and payload shape rather than a simplified stand-in.
Reply extraction is the step most likely to fail quietly, so it deserves a deliberate choice. PyRIT's HTTP target can pull the answer from a JSON path or with a regular expression, and it accepts httpx client parameters such as timeouts. Confirm with the application's owners which field carries the model's text, whether streaming or wrapper fields change the shape of the body, and how errors and rate limits appear in the response. A parser that returns an empty string or an error message will make scoring look cleaner than the system really is.
The limit to plan around is that HTTPTarget does not keep conversation history. Each request reaches the application as a standalone call, so any attack that depends on editing or replaying earlier turns needs a different target, and the team should decide early which of its planned attacks are single-turn. Before relying on the target, confirm that the captured request contains no short-lived tokens that expire during a run, and that the test account and environment are approved for adversarial traffic.
What you need before the first request runs
A working HTTP target depends on four things lining up: a PyRIT install, a faithful copy of the request the application actually sends, a network and trust path to the endpoint, and an account the testers are allowed to use. Check each one with the application's owners before any prompt is sent.
Python and PyRIT installed with pip
PyRIT installs from PyPI with pip, and the package supports Python 3.10 up to but not including 3.15. The PyRIT documentation recommends Python 3.13, so pin that version in the test environment. Confirm the installed version matches the documentation version you are following, since the HTTP target's parameters can change between releases.
PyRIT on PyPIWritten authorization for the target
Get written approval from the application owner that names the endpoint, the test account, the permitted prompt categories and the test window. A captured request is only a starting point; the authorization decides what you may send with it. Keep the document with the test records so reviewers can match each run to an approved scope.
A captured request from the application
Capture the chat request from browser DevTools or Burp, including the method, path, headers, cookies and JSON body that the real client sends. Remove any values that would expire or identify a person before you save it to a file. Mark the field that carries the user prompt so you know where PyRIT will place each objective.
Network path and TLS trust
The machine running PyRIT must reach the application endpoint along the same route as real users, including any VPN, proxy or gateway. If the endpoint uses an internal certificate authority, add that root to the trust store used by the Python process, or the httpx client will reject the connection. Test reachability with a single benign request before enabling any attack.
Session or token for a test account
Use a dedicated test account with the least privilege that still exercises the chat feature. Confirm that the account is allowed to send the traffic you plan to generate and that its session or bearer token will remain valid for the whole run. Keep tokens in an environment file, not inside the saved request.
Session lifetime and rate limits
Ask the application owners how long sessions last, whether tokens refresh, and what request rate triggers throttling or account lockout. Multi-prompt runs can hit these limits quickly, and a locked test account can stop a test window. Agree on a concurrency level and a stop condition before the first attack starts.
How to configure HTTPTarget from a captured request
This sequence turns a request you captured from your application into a working PyRIT target that sends a prompt and returns the model's reply. You finish with a saved request template and a verified parser, so later attacks can reuse the same connection.
Capture the chat request in browser DevTools or Burp
Send one ordinary message in the application while DevTools (Network tab) or Burp Proxy is recording. Locate the request that carries the message to the chat API, then copy it as raw HTTP, including the method, path, headers, cookies, and JSON body. Confirm that replaying the copied request outside the browser, with a tool such as curl or Burp Repeater, returns the same kind of reply you saw on screen. Requests that rely on short-lived tokens will need refreshing before each test session.
Replace the user prompt with the placeholder
In the captured body, find the field that holds your typed message and replace its value with the placeholder PyRIT fills at runtime. Check the PyRIT documentation for the exact placeholder token in the version you install, since the prompt will be inserted there. Leave all other fields, such as model name, session identifiers, and system fields, as the browser sent them. Confirm the body is still valid JSON by pasting it into a validator, because a broken quote here will fail every request later.
Save the raw request to a file
Save the edited request as a plain text file in your test project, keeping the original request line, headers, and line endings. Store secrets such as session cookies or bearer tokens in your environment or secret store rather than in the file where possible, and keep the file out of version control. Confirm the file loads in the HTTPTarget constructor without errors, which means the request template was read as intended.
Set the response parser to a JSON path or regex
Decide how PyRIT will extract the model's reply from the response. Use a JSON path when the API returns structured JSON with the reply in a known field, or a regular expression when the reply is embedded in text or HTML. Run the parser against one saved response from the browser to confirm it returns only the assistant's text, without metadata, markup, or the echoed prompt. Adjust the path or pattern until that check passes, since a wrong parser will score noise as model output.
Set httpx client parameters such as timeouts
Configure the httpx client options that HTTPTarget accepts, starting with request timeouts sized to the slowest response you observed in the browser, plus headroom. Set any proxy or TLS verification options your environment needs, such as an internal certificate authority, and record why each is set. Confirm the settings by sending a request to an endpoint you know is slow and checking that the timeout triggers at the expected point, not earlier or never.
Send one benign prompt and compare the parsed reply
Send a harmless question such as a request for a short fact that your application should answer. Print or log the raw response alongside the parsed output, then compare the parsed text against what the browser displayed for the same message. The check passes when the reply matches in content and contains no extra fields or markup. If it does not match, return to the parser step, because every later attack result depends on this extraction being correct.
Choosing JSON path or regex for the response
When the application returns JSON, PyRIT's HTTPTarget can extract the reply with a JSON path expression, which points at a specific field in the response object. This is the more stable option because the reply sits at a named location and survives changes to whitespace, element order and surrounding markup. A path still depends on the schema, so a renamed key or a new wrapper object will break it. Confirm the path against several real responses, including error responses, before you start a run.
- Field location: the path targets one key, so the extractor does not need to know how the rest of the body looks.
- Schema drift: a renamed or nested field fails the path, which is why the schema should be pinned or versioned with the application team.
- Streaming and wrappers: server-sent events or envelope objects often need a different path than a plain completion.
- Error bodies: a 200 response with an error object can yield no matching field, so the run should treat a missing path as a failure.
- Test fixtures: keep a few saved responses so a path can be checked again after each application release.
Check that the path resolves to the assistant text and not to metadata, such as a message ID or a token count.
When the application returns plain text, HTML or a non-JSON envelope, a regular expression is the practical extraction method. The pattern must capture only the reply, so it depends on markers that surround it, such as a container tag or a fixed prefix. Regex patterns are easy to write and hard to keep correct, because small changes to markup, escaping or line breaks can cause them to match the wrong span or nothing at all. Keep the pattern as narrow as the format allows and test it against captured responses.
- Anchor choice: anchor on stable markers, not on CSS classes or layout text that designers change often.
- Multiline content: replies that span lines need the correct flags, or the capture stops at the first newline.
- Greedy matches: a broad pattern can pull in the rest of the page, including scripts or footers, which then gets scored as the model's reply.
- HTML entities: escaped characters in the captured text can change what a scorer sees, so confirm how the output is decoded.
- Multiple matches: repeated markers can return several captures, so confirm which one holds the reply.
Run the pattern against a set of captured responses, including refusals and empty replies, before any attack depends on it.
The two methods fail in different ways over time. A JSON path usually breaks in a visible, specific way when a key moves, which makes the failure easier to diagnose. A regex can break silently when the markup changes slightly and still matches something, so the captured text looks plausible but is wrong. For a long-lived test setup against an application that ships often, the maintenance effort depends on how often the response format changes and how well the team tracks those changes. Ask the application team which response fields are contractual and which are incidental.
- Change frequency: ask how often the response shape changes and whether releases are announced to the testing team.
- Silent drift: a regex that still matches after a markup change can score the wrong text without any error.
- Ownership: name who updates the path or pattern when the application changes, and how that update is reviewed.
- Version pinning: where the application team can pin an API version, extraction changes less often.
- Regression checks: a short test that runs extraction against saved responses catches drift before a red team run.
Ask for a written description of the response contract before you choose a method, because that contract determines how often the extractor will need attention.
A parse failure should stop the run. If the extractor cannot find the reply, a run that continues will record an empty or partial response as the target's answer. Scorers then judge that empty value, and the results can show the application as safe when the test never actually reached the model. This is one of the most common ways a red team report becomes misleading. Configure the run so a missing path or a non-matching pattern raises an error, then investigate before the next attempt.
- Empty replies as results: an empty string is not a refusal, and it should not be scored as one.
- Error handling: check how the target surfaces an extraction failure, and confirm the run halts and logs the raw response.
- Raw response retention: keep the unparsed body with the failed attempt so the cause can be diagnosed.
- Authentication expiry: a login error page often fails extraction, so the failure may signal an expired session rather than a parser problem.
- Alerting: route failures to the operator, and do not let them disappear into aggregate counts.
Before a full run, confirm with the application team that a deliberately malformed or unauthorized request produces a visible failure in PyRIT's output.
Why prompts must be JSON-escaped and how converters handle it
When PyRIT sends a prompt through an HTTP target, the prompt is placed inside a request body that the application parses as JSON. Characters that are harmless in plain text can change the structure of that body, so the escaping step deserves the same attention as the attack objective itself.
Characters that break the body
Double quotes, backslashes, raw newlines, tabs and some Unicode sequences all have meaning inside a JSON string. If a prompt containing a quote is pasted directly into a template such as {"message": "PROMPT"}, the body becomes malformed or the value is truncated early. Check every special character class your test objectives use before the first run, because a single unescaped quote can invalidate an entire batch.
Invalid requests that look like failures
A malformed body often returns an HTTP 400 or a generic server error. Teams reading the results may conclude that the application is fragile or that the model refused, when in fact the prompt never reached the model. Record the status code and raw request for each attempt, and separate transport errors from refusals in your reporting so that findings describe the application rather than the test harness.
Converters transform the prompt
PyRIT converters apply a transformation to the prompt before it reaches the target. Converter behavior depends on the converter and the PyRIT version, so the exact output must be confirmed in the PyRIT documentation for the version you run. Treat a converter as part of the test design: it changes what the attack actually sends, and the results must record which converter was applied.
HTTP Target docsConfirm escaping against captured traffic
Before relying on converters, send a test prompt containing quotes, a backslash and a newline, then compare the body PyRIT sends with the body your browser or Burp captured for a benign request. Confirm that the application decodes the value back to the original text. This check tells you whether a failure comes from escaping, from the endpoint or from the model.
Keep escaped and raw prompts apart
Some attacks rely on the exact characters of an objective, so a converter that escapes or encodes the prompt can change the test itself. Decide whether each objective should be tested raw, escaped for transport, or both. Log the original objective alongside the transformed prompt in memory so reviewers can see what was sent and what was intended.
How a PyRIT attack flows through the HTTP target
The flow starts in the attack module on the tester's machine, which picks an objective and passes it through any converters that encode or escape it. HTTPTarget then fills the captured request template with that prompt and sends it across the trust boundary to the application's own API. The response returns through the JSON path or regex parser, and the conversation is stored in PyRIT memory. Check that the parser extracts only the model's reply, and that the stored record matches what the application actually returned.
The attack module drives the HTTP target across the trust boundary to the application API and records each reply in memory.
Mapping request fields, placeholders and response paths
This table maps each part of a captured HTTP request to what the team must set in PyRIT's HTTP target, who usually supplies the value, and what to verify before the first attack run. Read it top to bottom alongside a real capture from your own application, since each row depends on the exact request your browser or Burp session sent.
| Element | What the team must set | Who supplies the value | What to verify |
|---|---|---|---|
| Method and URL | The HTTP method and full endpoint the chat request uses, copied from the captured request line | Application engineering team, from the captured request | The endpoint responds to the same method outside the browser, and it is not a page load or polling call |
| Headers | Request headers the app requires, such as content type and any custom application header, with values kept as they were captured | Application engineering team, from the captured request | Headers that change per session or per request are identified and handled, not pasted as fixed values |
| Cookies | Session cookie values included in the raw request, with a plan for when they expire | Test team, from a logged-in test account | The session remains valid for the full test run and the account has only the access the test requires |
| Authorization token | Bearer or other token header, if the application uses one, placed in the raw request | Test team, issued for a dedicated test identity | The token has a known lifetime and the test identity is limited to the test environment |
| Body prompt placeholder | The prompt field in the captured JSON or form body replaced with the placeholder PyRIT fills with each attack prompt | Test team, after reviewing the body structure | Prompts containing quotes, backslashes or newlines produce valid JSON, which may require a JSON-escaping converter |
| Other body fields | Model, conversation ID, message IDs and similar fields copied as captured, or marked for update if they change | Application engineering team | Stale IDs do not cause the target to return errors or silently drop the prompt |
| Response path | A JSON path or regex that extracts the model's reply from the response body | Test team, by reading a sample response | The extracted text matches the visible reply, including when the response is streamed or wrapped in metadata |
| Client settings | httpx parameters such as timeouts for slow model responses | Test team, with input from the application owner | Timeouts exceed typical model latency so long replies are not recorded as failures |
Securing the credentials and test data in the HTTP target
A saved HTTP target file often carries live session tokens, cookies and customer data that were visible in the application when it was captured. The cards below cover where those secrets live, how little access the test account needs, what to strip before sharing, and who can read the results PyRIT stores.
Keep tokens out of the request file
A raw request copied from DevTools or Burp usually contains an Authorization header, a session cookie or both. Keep the saved request file free of these values and load them from PyRIT's credential file at ~/.pyrit/.env, so the request file can be reviewed, versioned and shared without exposing a working session. Check that the file contains placeholders only before it is committed to any repository.
Limit the test account
Create a dedicated test user with the lowest role that still reaches the features under test, and avoid administrator or shared staff accounts. Confirm that the account cannot reach production customer records, cannot change its own permissions and cannot trigger payments or outbound messages. Ask the application owner to confirm which endpoints the account can call, because the prompt field is often reachable from more places than the chat screen.
Redact captured requests before sharing
Requests captured in a live session can include names, email addresses, account numbers and other personal data in cookies, query strings and request bodies. Before a request file leaves the test team, remove or replace these values and the session identifiers they carry. Keep the unredacted original only in the encrypted store your security team controls, and record who performed the redaction.
Protect the memory store
PyRIT memory records every prompt, response and score, and the stored conversations can contain harmful test content and any sensitive data the application returned. PyRIT stores this memory in SQLite or Azure SQL, so set file permissions on a local SQLite database or apply role-based access and encryption controls on Azure SQL. Confirm the retention period with your data owner before the first run, since PyRIT does not delete results on its own schedule for you.
Rotate and expire test credentials
Session tokens captured during testing remain valid until the application expires them, which can outlast the engagement. Schedule rotation of the test account password, revoke any tokens issued during the run and remove the .env entries when testing ends. Ask the application team how long their sessions and refresh tokens last, and confirm that the test account's activity is visible in their audit logs.
Where the HTTP target is the wrong choice
HTTPTarget does not handle conversation history, so it is the wrong choice for any attack that needs to edit or replay earlier turns. Multi-turn strategies such as Crescendo build up a conversation over several exchanges and adjust earlier messages as they go. If the application keeps its own session state server-side, PyRIT can send each new prompt but cannot rewrite what the model has already seen in that session. The decision should be made before you capture the request, because it determines which target class you build and which attacks your test plan can include. Check the attack list in the PyRIT documentation on prompt targets against the attacks you intend to run.
Ask the application team how conversation state is stored. Confirm whether the chat endpoint expects a session identifier, a conversation or thread ID, or a full message history in each request body, and whether that identifier is issued by the server or generated by the client. If the server holds the history and rotates identifiers, a single-turn HTTP test may still work for objective-based probing, but a multi-turn plan will not. If the client sends the full history, you can reconstruct it yourself in a custom target, which is a development decision rather than a configuration change. Also confirm whether sessions expire, how long they last, and whether a failed request resets them, since these details decide whether a multi-turn run can be resumed.
Record the answers in the test plan with the attack strategies you expect to run. For a single-turn scan, the HTTP target is usually sufficient and the captured request only needs its prompt placeholder and response parser set correctly. For multi-turn work, plan a target that can manage history explicitly, and confirm with the application owner that the test environment supports the extra session handling. Agree on who owns session tokens and cookies, how they are stored outside the repository, and when they are rotated, so that a long run does not fail halfway through because a session expired.
Why HTTP target runs fail and how to fix them
This table lists the failures teams most often hit when pointing PyRIT's HTTP target at their own application, with the likely cause and a first fix for each. Work down the rows in order when a run returns errors or empty results, since session and parser problems usually show up before the others.
| Failure | Likely cause | Fix |
|---|---|---|
| Session cookie or token rejected | The captured session expired or was tied to a single browser login | Recapture the request from a fresh session, then replace the cookie or bearer value in the raw request before each test window |
| Parser returns empty text | The JSON path or regex does not match the response shape, often because the reply is nested or streamed | Check the response body in DevTools or Burp, correct the JSON path or regex, and run one prompt to confirm the extracted text before a full run |
| JSON escaping error | The prompt contains quotes, backslashes or newlines that break the JSON body in the template | Apply PyRIT's JSON-escaping converter to the prompt, and confirm the request body still parses as valid JSON |
| TLS certificate trust error | The application uses an internal certificate authority that the test host does not trust | Add the internal CA to the trust store used by the Python environment, and confirm the verification setting with your platform team instead of disabling checks |
| Requests time out | Model responses are slower than the default httpx timeout, especially for long or multi-step replies | Pass explicit httpx client parameters such as a longer timeout, and confirm the application's own gateway timeout is at least as long |
| Rate limiting or throttling | Concurrent attack runs send more requests than the application or its gateway allows | Reduce concurrency and add retry handling, and ask the application owner for the approved request rate for the test window |
| Multi-turn context lost | HTTPTarget does not keep conversation history, so follow-up turns arrive without earlier context | Use a target that supports editable history for these attacks, or confirm that the application stores context server-side through a session identifier |
Questions teams ask before testing a custom LLM API with PyRIT
Can our team test a custom LLM API with PyRIT in house?
Yes, if your engineers can run Python, read an HTTP request, and interpret responses from your application. PyRIT installs with pip, and the documentation recommends Python 3.13, while the PyPI package supports Python 3.10 up to but not including 3.15. The harder part is not the install but deciding which attacks matter for your application, writing the request template correctly, and reviewing results. Teams without a security testing practice often find that the attack design and scoring work takes more time than the tool setup. DeployOpen can plan and run this work in a fixed scope if you prefer a partner for it.
What drives the effort of an HTTP target setup?
The main drivers are the number of endpoints, the authentication scheme, and the response format. Each endpoint that accepts a prompt usually needs its own captured request and its own response extraction rule. Authentication adds work when tokens expire, are issued by a login flow, or are bound to a session, because the captured request may stop working during a test. Response formats matter too: a JSON path is simple when the reply is a clean field, while a regex is needed when the reply is embedded in HTML or mixed text. Streaming responses, signed request bodies and CSRF tokens add further steps. Ask your team to list these before estimating any work.
What does the application owner need to provide?
The application owner should provide a test environment that mirrors production as closely as possible, test accounts with the roles you want to exercise, and documentation of the request flow. PyRIT's HTTP target works from a raw HTTP request captured in browser developer tools or Burp, so someone must capture that request and confirm which parts change per prompt. The owner should also confirm rate limits, allowed hours for testing, and who receives alerts from the application's monitoring. Written approval for the scope and a named contact for incidents are standard prerequisites before any attack runs against a live system.
Is the HTTP target suitable for every attack type?
No. The HTTP target does not handle conversation history, so attacks that need to edit or replay earlier turns require a different target. Single-turn attacks, where each prompt stands alone, fit the HTTP target well. Multi-turn strategies that depend on prior messages need your application to keep state in a way PyRIT can reproduce, or they need another target type. Confirm this with your test plan before choosing attacks, because a multi-turn strategy run against a stateless target will not test what you intended.
How does the HTTP target handle prompts that contain special characters?
Prompts are inserted into the request body, so characters such as quotes, backslashes and newlines can break the JSON structure if they are not escaped. PyRIT provides converters that can transform prompts before they reach the target, and JSON escaping is one way to keep the payload valid. Test this early with a benign prompt containing quotes and line breaks, and check the application's server logs to confirm the request arrived as intended. Failed requests can look like safe refusals in results, so confirm that every recorded response came from a successful call.
What security controls should we check before running attacks against our API?
Confirm that credentials are stored outside the captured request file and read from a secure location rather than pasted into shared notes. PyRIT reads credentials from ~/.pyrit/.env and settings from ~/.pyrit/.pyrit_conf, so set file permissions on those paths and keep them out of version control. Keep captured requests free of production tokens where possible, and limit the test accounts to the minimum roles needed. Record every run in PyRIT's memory, which stores conversations and results in SQLite or Azure SQL, and decide who may read that data because it can contain sensitive prompts and responses.
Where can I confirm the current HTTP target behavior?
Check the PyRIT documentation for the version you install, since the HTTP target page describes how raw requests are sent, how responses are extracted from a JSON path or regex, and how httpx client parameters such as timeouts are passed. The current release is PyRIT v1.1.0, and the project's releases page lists changes between versions. Confirm details against your own captured request before relying on them, because a documentation example may not match your application's response format.
How DeployOpen scopes and runs PyRIT testing on your application
DeployOpen plans and runs PyRIT testing against your own application API, inside the environment where it runs. We agree the endpoint, request capture, response parsing and test objectives in writing before work starts, then hand over the configuration, memory records and findings so your team can repeat the run.
How we scope
- Confirm which application endpoints, user roles and conversation flows are in the written scope for PyRIT's HTTP target.
- Agree how requests are captured from browser DevTools or Burp and which session tokens the test account will use.
- Define how responses are parsed, either by JSON path or regex, and which fields count as the model's answer.
How we build
- Build the raw request template with the prompt placeholder and check that the application accepts it outside PyRIT first.
- Set httpx client options such as timeouts for your application's latency, and confirm the response parser on sample traffic.
- Apply converters that JSON-escape prompts so quotes and newlines do not break the request body.
How we hand over
- Deliver the request template, parser configuration and environment variable layout for your team to review and version.
- Provide the PyRIT memory records for each run, with the objectives, prompts, responses and scorer results needed to trace a finding.
- Document the findings with severity, reproduction steps, recommended fixes and a retest plan agreed in the written scope.
How we support
- Ongoing support, upgrades and continuous testing are available as a retainer after the fixed-scope engagement ends.
- Retesting after fixes is included in the written scope where agreed, so your team can confirm the change closed the finding.
- Ask in the quote how PyRIT upgrades, application API changes and session handling changes will be handled over time.

