Skip to content

feat: add LiteLLM as AI gateway prompt target#2154

Open
RheagalFire wants to merge 4 commits into
microsoft:mainfrom
RheagalFire:feat/add-litellm-provider
Open

feat: add LiteLLM as AI gateway prompt target#2154
RheagalFire wants to merge 4 commits into
microsoft:mainfrom
RheagalFire:feat/add-litellm-provider

Conversation

@RheagalFire

Copy link
Copy Markdown

Description

Adds LiteLLMChatTarget - a new prompt target that uses the LiteLLM SDK to access 100+ LLM providers (Anthropic, AWS Bedrock, Google Vertex, Cohere, etc.) directly, without requiring a separate proxy server.

from pyrit.prompt_target import LiteLLMChatTarget

# Anthropic (reads ANTHROPIC_API_KEY from env)
target = LiteLLMChatTarget(model_name="anthropic/claude-sonnet-4-6")

# AWS Bedrock (reads AWS credentials from env)
target = LiteLLMChatTarget(model_name="bedrock/anthropic.claude-v2")

# Google Vertex AI
target = LiteLLMChatTarget(model_name="vertex_ai/gemini-pro")

# Self-hosted LiteLLM proxy
target = LiteLLMChatTarget(
    model_name="anthropic/claude-sonnet-4-6",
    api_base="http://localhost:4000",
    api_key="sk-proxy-key",
)

Changes:

  • pyrit/prompt_target/litellm_chat_target.py - New LiteLLMChatTarget extending PromptTarget with:
    • litellm.acompletion() for async chat completions
    • drop_params=True by default (silently drops provider-unsupported kwargs for cross-provider compatibility)
    • Exception translation: litellm.exceptions.* mapped to PyRIT's RateLimitException / PyritException hierarchy (no bare Exception catches)
    • Token usage capture in response metadata
    • Tool call / function call support
    • Lazy import litellm so users without the package are unaffected
  • pyrit/prompt_target/__init__.py - Registered LiteLLMChatTarget
  • pyproject.toml - Added litellm>=1.83.0,<2.0.0 as optional dependency (pip install pyrit[litellm])

Tests and Documentation

22 unit tests in tests/unit/prompt_target/target/test_litellm_chat_target.py:

  • Constructor validation: missing model raises ValueError, LITELLM_MODEL env var fallback, explicit override
  • drop_params=True default + opt-out with drop_params=False
  • Request body construction: API key forwarded when set, omitted when blank (lets LiteLLM read provider env vars); optional params (temperature, top_p, max_tokens, api_base) forwarded correctly
  • Full request-response cycle: text responses parsed, tool calls serialized as JSON, token usage captured in metadata
  • Empty/malformed response handling: no choices raises EmptyResponseException, empty content raises EmptyResponseException
  • Exception translation: litellm.exceptions.RateLimitError -> RateLimitException, AuthenticationError -> PyritException, APIConnectionError/Timeout -> retryable RateLimitException, unknown errors -> PyritException
  • Finish reason validation: stop, length, tool_calls, content_filter accepted; unknown reasons raise PyritException
  • Message building: role preservation across multi-turn conversations

All 22 tests pass:

tests/unit/prompt_target/target/test_litellm_chat_target.py  22 passed in 2.15s

Ruff lint clean (line-length=120, preview=true).

JupyText not applicable - no notebook documentation added for this target yet.

@rlundeen2 rlundeen2 self-assigned this Jul 9, 2026
@rlundeen2

rlundeen2 commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

I've been wanting to do this also; @RheagalFire this is a great start. I'll likely push to your branch to flush it out and support all the things (multi-modal, identifiers, underlying model, integration tests, capabilities detection, other gaps). So from your perspective I would consider this "merged" and I'll take it and try to get it in before the next release.

TY for the help and nudge!

rlundeen2 and others added 3 commits July 10, 2026 14:00
…s, token usage)

Extends the LiteLLM target for parity with OpenAIChatTarget and shares logic instead of reinventing it:

- Extract shared Chat Completions helpers (chat_completions_message_builder, chat_completions_response_parser) used by both OpenAIChatTarget and LiteLLMChatTarget for request building and response parsing (text, image, audio, tool calls, content-filter handling).

- Add multimodal support (image + audio input, audio output via audio_response_config) with capabilities derived from LiteLLM's model registry and a conservative text-only fallback.

- Support the full OpenAI parameter set plus an extra_body_parameters passthrough; auth via sync/async token providers; identifiers that exclude the api_key; underlying_model capability lookup; and LiteLLM-owned retry (num_retries from PyRIT's global convention) to avoid double-retrying.

- Add a provider-neutral TokenUsage value object (input/output/total/reasoning/cached + extra) and capture it for both targets; capture LiteLLM per-call cost.

- Add litellm as an optional extra and include it in the 'all' extra.

- Modernize type syntax (X | None), tidy docstrings per the style guide, and add unit + integration tests (image/audio on a gpt-5 deployment).

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

Make TokenUsage a pure value object (fields + to_metadata/from_metadata) and
move Chat Completions usage parsing into chat_completions_response_parser as
token_usage_from_chat_completion, explicit to the one wire shape both chat
targets actually send.

- Drop the speculative Responses-API sniffing (no caller sends that shape);
  a Responses target should parse its own usage in its own module.
- Tolerate dict-or-attribute usage payloads so a mapping no longer silently
  yields all-None counts.
- Capture LiteLLM/Anthropic top-level cache fields
  (cache_read_input_tokens -> cached_tokens, cache_creation_input_tokens ->
  extra), preserving a zero cached count.
- Move/expand parsing tests into test_chat_completions_helpers; test_token_usage
  now covers only metadata round-tripping.
- Convert remaining Sphinx roles to plain double-backtick references.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…ts to gpt-5.4

Revert the PLATFORM_OPENAI_CHAT_MODEL / PLATFORM_OPENAI_AUDIO_MODEL additions to
.env_example and default the chat/vision integration fixtures to the deployed
gpt-5.4 model instead of the generic "gpt-5". Also convert two stray Sphinx roles
in the integration test docstrings to plain double-backtick references.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Comment thread pyproject.toml
"azure-cognitiveservices-speech>=1.46.0",
]
litellm = [
"litellm>=1.83.0,<2.0.0",

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.

FWIW it doesn't add a ton on top of what we already have. Could consider making it a dependency without extra. That could change for litellm, of course, and then we'd have to move it into an extra. The current state as extra is probably the safest.

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.

3 participants