mirror of
https://github.com/BerriAI/litellm.git
synced 2026-10-29 06:33:28 +00:00
* feat(model-catalog): add Rust registry validation (#43136) * doc * feat(model-catalog): add Rust registry validation * test(model-catalog): ignore integration tests * docs(model-catalog): fix validation note grammar --------- Co-authored-by: Yujong Lee <yujong@berri.ai> (cherry picked from commitc289d5d6fb) * test(rust): reorganize core crate tests and split cache and OCR suites (#43177) * test(rust): group cache tests under cache/ and fold test_ocr.py into ocr/ The two failure cases in test_ocr.py duplicated the upstream-500 and timeout rows of PUBLIC_FAILURES, so only the file-input encoding case moves to ocr/test_requests.py Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(rust): split the response cache suite into one file per backend test_response_cache.py grew to 2400 lines. Each backend now has its own file, shared fixtures live in cache/conftest.py and shared helpers in support/cache.py. The helpers alias the private native test handles once, dropping the per-call reportPrivateUsage hits Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * split tokenizer test * test(core): consolidate route integration tests under tests/ with rstest and wiremock Moves the public-API OCR route tests out of src/ocr/route.rs and document.rs into tests/ocr/, split per provider plus lifecycle, machine, and document tests, merging the duplicated pairs. Messages, audio transcription, and chat completions share one wiremock-based upstream and recording secret source in tests/support, and gain table-driven cases for auth, routing, upstream errors, streaming, and declines. Tests of litellm-llms items move to that crate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(messages): keep the stream relay test independent of the stream head contents The stream head carries no headers on main, so the relay test asserts the open-then-deliver order and the relayed body instead of header hand-off. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit10413796c6) * feat(rust): hand upstream response headers to the native Messages stream (#43178) * ci: drop the ocr_testing job now that tests/ocr_tests is gone Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(ocr): restore the live OCR matrix and the ocr_testing job The public litellm.ocr / aocr / Router interface is unchanged by the Rust migration, so the live provider matrix still applies. Drops the stale VCR skip list for the deleted test_rust_bridge.py. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(messages): show streamed upstream headers never reach the native stream The Python handler puts the upstream response headers on the stream's _hidden_params before the first chunk so the proxy can forward them as llm_provider-* headers. The native route drops them, and this test fails on the Rust path while passing on Python. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(messages): hand upstream response headers to the native stream before its first chunk The Messages route fills MessagesStreamHead from the upstream response and yields it on Open. The Python driver converts it through the protocol host and hands it to Stream and SyncStream as their _hidden_params, so a streamed native call carries additional_headers the same way the Python handler does and the proxy can forward them as llm_provider-* headers. The relay contract lives in the core crate test, the hand-off in the host-python driver test, and the header projection in the route host test, so the recording-server test that showed the gap is dropped. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * wip --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit081f73f021) * feat(testkit): agent clients for Claude Code, Codex and opencode (#43181) * feat(testkit): install and configure Claude Code, Codex and opencode against a gateway Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * refactor(testkit): derive targets from target-lexicon and split agents behind a trait Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * refactor(testkit): group sources into agent and install folders Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(testkit): split agents into install, configure and drive with semver-aware launch Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * style(testkit): drop a needless borrow Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> (cherry picked from commit9c10e0f985) * ci: run migrated unit selections on every event in legacy GHA shards (#43182) * ci: run the unit_selection.sh shard files on every event instead of only fork pull requests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * ci: rename fork-flag to unit-flag now that it applies on every event --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit694783ebbe) * test: move tests/test_litellm root and small trees into tests/unit (#43186) * ci: run the unit_selection.sh shard files on every event instead of only fork pull requests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * ci: rename fork-flag to unit-flag now that it applies on every event * test: move tests/test_litellm root and small trees into tests/unit Pure renames, no content changes. Follow-up commits in this PR fix references, merge the three files that already existed in tests/unit, keep live-provider tests in tests/test_litellm and wire CI. * test: carry tests/test_litellm conftest isolation into tests/unit Callback lists, routing fallbacks, cached HTTP clients, logger state, AWS, proxy-URL and keychain env, and session-end client cleanup now reset for unit tests too. The environment isolation owns its MonkeyPatch so a test's own monkeypatch is undone before the model-cost teardown runs. * test: merge, split and prune the moved root and small-tree tests Merge batches/test_batch_utils.py and the chat_completions and messages dispatch tests into the files that already existed in tests/unit. Keep the live Gemini interactions tests, the async image-fetch format test and the OpenAI embedding scorer test in tests/test_litellm since they need real network or keys. Put test_router.py under tests/unit/test_router so the existing package no longer shadows it. Delete eight tests the audit found superseded by stronger ones kept in this move. * ci: run the moved root and small-tree tests under their legacy flags Add the misc and responses-caching-types flags to unit_selection.sh and CircleCI, extend enterprise-routing and mcp-integration, and point the legacy GHA shards, Makefile, redis-compat workflow, merge smoke manifest and change classifier at the new paths. * test: make the new tests/unit directories packages tests/unit/test_package_layout.py requires every directory to carry an __init__.py, and without one the moved and retained test_litellm_responses_bridge.py modules collide on import. * test: scope the unit socket block to tests/unit in shared sessions The GHA shards collect the legacy test-path and the unit selection in one pytest session. The unit conftest's loopback-only block leaked into legacy modules that reach the network at import. The legacy conftest now lifts the restriction at collect and setup time, and the unit conftest re-applies it when collecting its own modules. * test: give the shard-script tests their own GITHUB_OUTPUT They only passed where the runner set it. The CircleCI unit job's env allowlist drops it, so the script's redirect failed there. * test: point the router and module-deletion checks at tests/unit router_code_coverage and code_qa_check_tests only searched tests/test_litellm, so the moved router tests no longer counted. The two silent-experiment tests the audit deleted were the only direct callers of those methods; they are replaced with tests that assert the forwarded shadow request and the recursion guard. --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commitf6882246d4) * refactor(framer): replace Framer trait with tokio-util codecs (#43193) * refactor(framer): replace Framer trait with tokio-util codecs Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor(framer): port SSE and AWS event stream framing to codecs Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(rust): drop clone on Copy capabilities in messages request test Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(rust): use field init shorthand in messages request test Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit3c93ea1697) * test: move tests/test_litellm/llms into tests/unit/llms (#43191) * ci: run the unit_selection.sh shard files on every event instead of only fork pull requests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * ci: rename fork-flag to unit-flag now that it applies on every event * test: move tests/test_litellm root and small trees into tests/unit Pure renames, no content changes. Follow-up commits in this PR fix references, merge the three files that already existed in tests/unit, keep live-provider tests in tests/test_litellm and wire CI. * test: carry tests/test_litellm conftest isolation into tests/unit Callback lists, routing fallbacks, cached HTTP clients, logger state, AWS, proxy-URL and keychain env, and session-end client cleanup now reset for unit tests too. The environment isolation owns its MonkeyPatch so a test's own monkeypatch is undone before the model-cost teardown runs. * test: merge, split and prune the moved root and small-tree tests Merge batches/test_batch_utils.py and the chat_completions and messages dispatch tests into the files that already existed in tests/unit. Keep the live Gemini interactions tests, the async image-fetch format test and the OpenAI embedding scorer test in tests/test_litellm since they need real network or keys. Put test_router.py under tests/unit/test_router so the existing package no longer shadows it. Delete eight tests the audit found superseded by stronger ones kept in this move. * ci: run the moved root and small-tree tests under their legacy flags Add the misc and responses-caching-types flags to unit_selection.sh and CircleCI, extend enterprise-routing and mcp-integration, and point the legacy GHA shards, Makefile, redis-compat workflow, merge smoke manifest and change classifier at the new paths. * test: make the new tests/unit directories packages tests/unit/test_package_layout.py requires every directory to carry an __init__.py, and without one the moved and retained test_litellm_responses_bridge.py modules collide on import. * test: scope the unit socket block to tests/unit in shared sessions The GHA shards collect the legacy test-path and the unit selection in one pytest session. The unit conftest's loopback-only block leaked into legacy modules that reach the network at import. The legacy conftest now lifts the restriction at collect and setup time, and the unit conftest re-applies it when collecting its own modules. * test: move tests/test_litellm/llms into tests/unit/llms Rename-only. Moves the provider tests and the fine-tuning fixtures they load, mirroring the old paths. Follow-up commits merge, split and wire them. * test: merge, split and prune the moved llms tests Merges the Databricks chat transformation tests into the existing unit file, keeps the tests that need real keys or the network in tests/test_litellm, deletes the audited tests a stronger unit test already covers, and points imports at tests.unit.llms. * ci: run the moved llms tests under their legacy flags The Vertex AI and All Other Providers shards keep their legacy test-path for the retained files and add the llm-vertex-ai and llm-other-providers unit selections. CircleCI gets matching unit jobs. * test: make the tests/unit/llms directories packages Adds __init__.py to the moved dirs and drops the legacy ones whose directories no longer hold tests. * test: drop script runners and path hacks the llms split left dangling The __main__ runners in the split openai_like files and the Databricks e2e runner called tests that now live in the other half of the split or were deleted. The retained legacy halves also no longer need sys.path edits. * test: give the shard-script tests their own GITHUB_OUTPUT They only passed where the runner set it. The CircleCI unit job's env allowlist drops it, so the script's redirect failed there. * test: point the router and module-deletion checks at tests/unit router_code_coverage and code_qa_check_tests only searched tests/test_litellm, so the moved router tests no longer counted. The two silent-experiment tests the audit deleted were the only direct callers of those methods; they are replaced with tests that assert the forwarded shadow request and the recursion guard. * test: keep the Databricks manual e2e runner and fix the SageMaker Nova run path The Databricks e2e file is a manual script whose main() calls the tests that were pruned, so pruning them broke the documented run. It is back to its main version. The SageMaker Nova docstring now points at the file's real location in tests/local_testing. * test: keep the job's UNIT_FLAG out of the shard-script tests --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit5e6dc89ba1) * test: move tests/test_litellm integrations and secret_managers into tests/unit (#43194) * ci: run the unit_selection.sh shard files on every event instead of only fork pull requests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * ci: rename fork-flag to unit-flag now that it applies on every event * test: move tests/test_litellm root and small trees into tests/unit Pure renames, no content changes. Follow-up commits in this PR fix references, merge the three files that already existed in tests/unit, keep live-provider tests in tests/test_litellm and wire CI. * test: carry tests/test_litellm conftest isolation into tests/unit Callback lists, routing fallbacks, cached HTTP clients, logger state, AWS, proxy-URL and keychain env, and session-end client cleanup now reset for unit tests too. The environment isolation owns its MonkeyPatch so a test's own monkeypatch is undone before the model-cost teardown runs. * test: merge, split and prune the moved root and small-tree tests Merge batches/test_batch_utils.py and the chat_completions and messages dispatch tests into the files that already existed in tests/unit. Keep the live Gemini interactions tests, the async image-fetch format test and the OpenAI embedding scorer test in tests/test_litellm since they need real network or keys. Put test_router.py under tests/unit/test_router so the existing package no longer shadows it. Delete eight tests the audit found superseded by stronger ones kept in this move. * ci: run the moved root and small-tree tests under their legacy flags Add the misc and responses-caching-types flags to unit_selection.sh and CircleCI, extend enterprise-routing and mcp-integration, and point the legacy GHA shards, Makefile, redis-compat workflow, merge smoke manifest and change classifier at the new paths. * test: make the new tests/unit directories packages tests/unit/test_package_layout.py requires every directory to carry an __init__.py, and without one the moved and retained test_litellm_responses_bridge.py modules collide on import. * test: scope the unit socket block to tests/unit in shared sessions The GHA shards collect the legacy test-path and the unit selection in one pytest session. The unit conftest's loopback-only block leaked into legacy modules that reach the network at import. The legacy conftest now lifts the restriction at collect and setup time, and the unit conftest re-applies it when collecting its own modules. * test: move tests/test_litellm/llms into tests/unit/llms Rename-only. Moves the provider tests and the fine-tuning fixtures they load, mirroring the old paths. Follow-up commits merge, split and wire them. * test: merge, split and prune the moved llms tests Merges the Databricks chat transformation tests into the existing unit file, keeps the tests that need real keys or the network in tests/test_litellm, deletes the audited tests a stronger unit test already covers, and points imports at tests.unit.llms. * ci: run the moved llms tests under their legacy flags The Vertex AI and All Other Providers shards keep their legacy test-path for the retained files and add the llm-vertex-ai and llm-other-providers unit selections. CircleCI gets matching unit jobs. * test: make the tests/unit/llms directories packages Adds __init__.py to the moved dirs and drops the legacy ones whose directories no longer hold tests. * test: drop script runners and path hacks the llms split left dangling The __main__ runners in the split openai_like files and the Databricks e2e runner called tests that now live in the other half of the split or were deleted. The retained legacy halves also no longer need sys.path edits. * test: give the shard-script tests their own GITHUB_OUTPUT They only passed where the runner set it. The CircleCI unit job's env allowlist drops it, so the script's redirect failed there. * test: point the router and module-deletion checks at tests/unit router_code_coverage and code_qa_check_tests only searched tests/test_litellm, so the moved router tests no longer counted. The two silent-experiment tests the audit deleted were the only direct callers of those methods; they are replaced with tests that assert the forwarded shadow request and the recursion guard. * test: move tests/test_litellm integrations and secret_managers into tests/unit Rename-only. Mirrors the old paths, including the directory conftests and the prompt and JSON fixtures. Follow-up commits prune and wire them. * test: prune and repoint the moved integrations tests Deletes the 7 audited tests a stronger test in the same tree already covers, imports the TLS sink helpers from their new conftest path, and restores os.environ after each integrations test. Some presets write OTEL_EXPORTER_OTLP_HEADERS straight into os.environ, and without the legacy tree's test ordering that header leaked into the AgentOps tests. * ci: run the moved integrations tests under their legacy flag The integrations GHA shard and a new CircleCI job run the integrations unit selection. secret_managers joins the misc selection. * docs: point integrations and secret_managers references at tests/unit * test: make the moved integrations directories packages * test: keep the Databricks manual e2e runner and fix the SageMaker Nova run path The Databricks e2e file is a manual script whose main() calls the tests that were pruned, so pruning them broke the documented run. It is back to its main version. The SageMaker Nova docstring now points at the file's real location in tests/local_testing. * test: keep the job's UNIT_FLAG out of the shard-script tests --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commitcf491d1df9) * fix(tests): drop the repeated UNIT_FLAG key in test_unit_shard_missing_paths (#43212) Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com> (cherry picked from commit25de1ab2b0) * fix(jwt): let x-litellm-team-id select DB membership teams when the token also carries a team claim (#43206) * fix(jwt): let x-litellm-team-id select DB membership teams when the token also carries a team claim Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * docs(jwt): describe header team selection under fallback_to_db_teams Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: yassin <yassin@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit7b4fd47c6e) * test: move tests/test_litellm core utils, routing, responses, caching and rust_bridge into tests/unit (#43199) * ci: run the unit_selection.sh shard files on every event instead of only fork pull requests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * ci: rename fork-flag to unit-flag now that it applies on every event * test: move tests/test_litellm root and small trees into tests/unit Pure renames, no content changes. Follow-up commits in this PR fix references, merge the three files that already existed in tests/unit, keep live-provider tests in tests/test_litellm and wire CI. * test: carry tests/test_litellm conftest isolation into tests/unit Callback lists, routing fallbacks, cached HTTP clients, logger state, AWS, proxy-URL and keychain env, and session-end client cleanup now reset for unit tests too. The environment isolation owns its MonkeyPatch so a test's own monkeypatch is undone before the model-cost teardown runs. * test: merge, split and prune the moved root and small-tree tests Merge batches/test_batch_utils.py and the chat_completions and messages dispatch tests into the files that already existed in tests/unit. Keep the live Gemini interactions tests, the async image-fetch format test and the OpenAI embedding scorer test in tests/test_litellm since they need real network or keys. Put test_router.py under tests/unit/test_router so the existing package no longer shadows it. Delete eight tests the audit found superseded by stronger ones kept in this move. * ci: run the moved root and small-tree tests under their legacy flags Add the misc and responses-caching-types flags to unit_selection.sh and CircleCI, extend enterprise-routing and mcp-integration, and point the legacy GHA shards, Makefile, redis-compat workflow, merge smoke manifest and change classifier at the new paths. * test: make the new tests/unit directories packages tests/unit/test_package_layout.py requires every directory to carry an __init__.py, and without one the moved and retained test_litellm_responses_bridge.py modules collide on import. * test: scope the unit socket block to tests/unit in shared sessions The GHA shards collect the legacy test-path and the unit selection in one pytest session. The unit conftest's loopback-only block leaked into legacy modules that reach the network at import. The legacy conftest now lifts the restriction at collect and setup time, and the unit conftest re-applies it when collecting its own modules. * test: move tests/test_litellm/llms into tests/unit/llms Rename-only. Moves the provider tests and the fine-tuning fixtures they load, mirroring the old paths. Follow-up commits merge, split and wire them. * test: merge, split and prune the moved llms tests Merges the Databricks chat transformation tests into the existing unit file, keeps the tests that need real keys or the network in tests/test_litellm, deletes the audited tests a stronger unit test already covers, and points imports at tests.unit.llms. * ci: run the moved llms tests under their legacy flags The Vertex AI and All Other Providers shards keep their legacy test-path for the retained files and add the llm-vertex-ai and llm-other-providers unit selections. CircleCI gets matching unit jobs. * test: make the tests/unit/llms directories packages Adds __init__.py to the moved dirs and drops the legacy ones whose directories no longer hold tests. * test: drop script runners and path hacks the llms split left dangling The __main__ runners in the split openai_like files and the Databricks e2e runner called tests that now live in the other half of the split or were deleted. The retained legacy halves also no longer need sys.path edits. * test: give the shard-script tests their own GITHUB_OUTPUT They only passed where the runner set it. The CircleCI unit job's env allowlist drops it, so the script's redirect failed there. * test: point the router and module-deletion checks at tests/unit router_code_coverage and code_qa_check_tests only searched tests/test_litellm, so the moved router tests no longer counted. The two silent-experiment tests the audit deleted were the only direct callers of those methods; they are replaced with tests that assert the forwarded shadow request and the recursion guard. * test: move tests/test_litellm integrations and secret_managers into tests/unit Rename-only. Mirrors the old paths, including the directory conftests and the prompt and JSON fixtures. Follow-up commits prune and wire them. * test: prune and repoint the moved integrations tests Deletes the 7 audited tests a stronger test in the same tree already covers, imports the TLS sink helpers from their new conftest path, and restores os.environ after each integrations test. Some presets write OTEL_EXPORTER_OTLP_HEADERS straight into os.environ, and without the legacy tree's test ordering that header leaked into the AgentOps tests. * ci: run the moved integrations tests under their legacy flag The integrations GHA shard and a new CircleCI job run the integrations unit selection. secret_managers joins the misc selection. * docs: point integrations and secret_managers references at tests/unit * test: make the moved integrations directories packages * test: keep the Databricks manual e2e runner and fix the SageMaker Nova run path The Databricks e2e file is a manual script whose main() calls the tests that were pruned, so pruning them broke the documented run. It is back to its main version. The SageMaker Nova docstring now points at the file's real location in tests/local_testing. * test: move tests/test_litellm core utils, routing, responses, caching and rust_bridge into tests/unit Rename-only. Mirrors the old paths, including fixtures, the stubtest config and the native-route wheel script. Two files that collide with existing unit files are merged in a follow-up commit. * test: merge, prune and repoint the moved core, routing, responses, caching and rust_bridge tests Merges the two files that collided with existing unit files, folding the legacy extra case into test_is_chat_completion_cached_dict, and deletes the 9 audited tests a stronger test in the same file already covers. Keeps what needs the network in tests/test_litellm: test_tokenizers pulls a tokenizer from the Hugging Face hub, and the gpt2 and r50k_base tokenizer cases download their BPE files. The unit core_utils conftest points TIKTOKEN_CACHE_DIR at litellm's bundled encodings so the rest never depend on import order to stay offline, and FakeSecretVault moves to a shared module so both trees can build it. * ci: run the moved core, routing, responses, caching and rust_bridge tests under their flags core_utils gets a core-utils flag and CircleCI job, and its GHA shard keeps the legacy path for the retained network tests. router_utils and router_strategy join enterprise-routing, responses joins responses-caching-types (minus responses/mcp, which mcp-integration owns), caching joins caching-local and rust_bridge joins misc. The redis-compat, test-rust, stubtest and merge-smoke paths follow the move. * docs: point the Rust crate references at tests/unit * test: make the moved core, routing and rust_bridge directories packages * test: keep the no-loop DualCache batch_get_cache regression test It runs the sync path outside any event loop, which the inside-loop test cannot, so a change that picks the Redis client by loop state would only show up there. * test: keep the job's UNIT_FLAG out of the shard-script tests * fix(url_utils): block 192.0.0.0/24 on every Python patch release * test: move the new budget limiter tests into tests/unit/router_strategy * test: move the new sentry scrubbing tests into tests/unit/litellm_core_utils * test: move the new zerobus tests into tests/unit/integrations * test: make tests/unit/integrations/zerobus a package * test: load litellm's own tiktoken cache setup once instead of resetting it per test --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commita11a93f44a) * refactor(rust): move credential inheritance and the SDK limits out of the legacy callback crate into a driver preflight (#43259) The legacy callback crate carried two rewrites that have nothing to do with the Logging contract: litellm_credential_name inheritance and the max_budget and num_retries_per_request checks. Any later callback host would need them unchanged, which is the smell the crate's AGENTS.md now names. They are now a Preflight the driver in litellm-host-python runs on the keyword view begin returned, before the host projects from it, supplied by python-bridge and passed through run_legacy_call. The call order is unchanged (setup, deployment hook, credentials, limits) and a rejection still fails the call as a host failure, so the failure callbacks run as before. The preflight rewrites the adapter's own copy in place, so no extra dict copy and no new lifecycle method Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> (cherry picked from commite9491d31b5) * refactor(http): hand out an owned Client and route all providers through the pool (#43245) * refactor(messages): take the provider client from the injected HTTP pool The messages route kept its own process-wide reqwest client, so it ignored ssl_verify, CA bundles, client certs, proxies and every other setting that litellm-http resolves. The machine now takes the HttpClientPool and the call's HttpClientConfig, as OCR does, and the bridge passes its shared pool. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(http): hand out an owned Client and move chat, audio and OIDC onto the pool HttpClientPool now returns litellm_http::Client, a newtype only crates/http can build, so every provider client carries the resolved TLS, proxy and timeout settings. Chat completions and audio transcription drop their process-wide reqwest clients and take the pool and call config like messages; their 600s ceiling moves to the request. OidcResolver takes its client instead of building one, and the bridge hands it the pooled one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(secrets): build Google, Azure and CyberArk manager clients from the pool The native secret managers built bare reqwest clients, so they ignored the host's TLS and proxy settings. load_native_manager now takes the pool and the host config and hands each manager a pooled client. CyberArk's CYBERARK_SSL_VERIFY and CYBERARK_CLIENT_CERT/KEY become an override on the host config instead of a hand-built client. To express a certificate and key in separate files, HttpClientConfig::client_certificate is now a ClientIdentity that is either one PEM or a split pair. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(clippy): only crates/http may build a reqwest client Fence reqwest::Client, ClientBuilder and the TLS builder methods with disallowed-types and disallowed-methods so new code takes a litellm_http::Client from the pool. crates/http is exempt as the one place clients are built, and testkit as a dev-only installer. Tests move to litellm_http::Client::plain_for_test or a pooled client. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(secrets-cyberark): keep verifying certificates when the host disables it Python hands CyberArk its own ssl_verify, which wins over the global setting, so CYBERARK_SSL_VERIFY unset or true still verifies even when the host sets ssl_verify false. The pooled client copied the host's Disabled and would send the API key unverified; fall back to the built-in roots instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(python-bridge): treat a missing litellm package as no host HTTP settings Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit1a58162630) * refactor(rust): promote anthropic messages out of experimental_pass_through (#43269) Co-authored-by: Yujong Lee <yujong@berri.ai> (cherry picked from commit2ef3250ec3) * test: stop CI tests from downloading tokenizer files and images (#43257) * test: load the embedding base image from a committed 100x100 PNG instead of downloading it * test: move the volcengine embedding test into tests/unit * test: check gpt2 and r50k_base tokenizer parity against committed tiktoken reference files * test: check hub tokenizer selection against an in-memory Hugging Face hub * test: serve image URLs from respx in the gemini tool-result and format-param tests * ci: drop the emptied legacy core-utils test path * test: cover the cohere and anthropic tokenizer paths in the hub tokenizer test * test: fetch every format-param image through respx and check its bytes reach the request * test: drop the gpt2 and r50k_base parity tests, which no litellm path uses * test: drop comments that restate assertions in the format-param test (cherry picked from commit2530255624) * fix(rust): preserve nested optional import failures (#43265) * fix(rust): preserve nested optional import failures Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(rust): restore Python modules after settings tests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commite1a9378093) * fix(callbacks-legacy-python): traverse and release the retained headers dict (#43274) * fix(callbacks-legacy-python): traverse and release the retained headers dict LegacyLogging keeps the headers dict it hands to pre_call and post_call, but its traverse never reported that edge to the collector and close never dropped it. A cycle a callback builds through that dict could not be collected, and a closed call kept the dict alive until the driver dropped the whole adapter. Visit and clear headers like body, with regression tests for both * refactor(callbacks-legacy-python): move the test support module into its own file --------- Co-authored-by: Yujong Lee <yujong@berri.ai> (cherry picked from commit4eb340abe0) * test(integration): port langfuse callbacks-in-db coverage to the local harness (#43282) * test(integration): port langfuse callbacks-in-db coverage to the local harness Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): assert the langfuse db rows after the exported span Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: yuneng <yuneng@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commite11c3f5815) * test: finish the non-proxy half of tests/test_litellm (#43281) * test: move key-gated tests/test_litellm SDK tests into tests/llm_translation and drop empty folders * test: make token counter and health check unit tests run offline * ci: point unit shards, rust path filter, Makefile and docs at tests/unit * docs: fix stale test_litellm run paths in moved llm_translation tests * fix: correct databricks e2e sys.path depth and contributing example path --------- Co-authored-by: yuneng <yuneng@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit99655b6f86) * refactor(rust): prepare inference and auth foundations for the gateway (#43287) * refactor(rust): prepare inference and auth foundations * fix(rust): keep textract operations parsing from kebab-case model names Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit7ae721bf79) * feat(rust): add config router and gateway crates (#43289) Co-authored-by: Yujong Lee <yujong@berri.ai> (cherry picked from commitaffb547525) * test(integration): run the Langfuse DB-callback test on its own scratch database (#43288) * test(integration): run the Langfuse DB-callback test on its own scratch database The test from #43282 wrote success_callback=langfuse and the LANGFUSE_* env into the shared integration LiteLLM_Config. The suite's long-running gateway reloads that table and only ever adds callbacks, so it kept exporting to the test's closed Langfuse fake for the rest of the shard even after the rows were restored. The owned proxy now gets a scratch database, which also removes the snapshot/restore code. scratch_database moves into _support/database.py so test_cache_and_quota and this test share one copy, and the stock-config guard now checks the callback settings instead of the raw YAML text. * test(integration): include failure_callback in the stock-config Langfuse guard (cherry picked from commitdd63637322) * refactor(rust): expand logging and test coverage across gateway and Anthropic messages (#43295) * refactor(rust): prepare inference and auth foundations * fix(rust): keep textract operations parsing from kebab-case model names Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * done * refactor(types): derive Anthropic beta string conversions with Strum * fix(anthropic): report missing max_tokens as a missing field * refactor(rust): type Anthropic messages headers and auth after the Python layout Delete anthropic/messages/headers.rs. Its OAuth handling, credential ladder and beta merging move to anthropic/common_utils.rs where Python keeps them (optionally_handle_anthropic_oauth, get_auth_header, _merge_beta_headers), and the feature beta injection becomes update_headers_with_anthropic_beta on the messages config, as in Python. The BaseAnthropicMessagesConfig impl is unchanged apart from the bodies of validate_environment and request_headers Beta values are now the AnthropicBeta enum and BetaSet, which sort, dedupe and comma-join by construction. Request params gain typed speed, tools and context_management through Recognized, so the beta logic matches on enums instead of string-comparing JSON. OauthToken parses the sk-ant-oat token once and the chat config shares that detection instead of its own copy Case-insensitive header helpers move next to has_header in litellm-http. One deliberate divergence: a Bearer-prefixed OAuth key configured through api_key or ANTHROPIC_API_KEY is sent with a single Bearer scheme, where Python would emit "Bearer Bearer" Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * done * fix(rust): repair test compilation and clippy failures resolve auth before building the outbound request in prepare tests, give the host hook tests their own error type, and drop the disallowed reqwest client and err().expect() from core tests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> (cherry picked from commit90873c46de) * test(proxy_behavior): scope the management proxy fixture to its package so its spend monitor cannot race the spend tests (#43302) Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit115668f43e) * fix(ci): stop stale CI reds, keep unit tests off the host env, retry CyberArk policy conflicts (#43294) * fix(ci): stop five stale or flaky CI reds and retry CyberArk policy-load conflicts The Langfuse redaction unit test exports to a local OTLP capture instead of polling Langfuse Cloud through a recorded lookup. The passthrough worker-kill test only requires spend rows for requests the surviving worker served. The spend-routes sweep treats the intentional /spend/capture_rate 503 as expected. CyberArk retries a 409 policy load in Python, Rust and the e2e Conjur helper instead of reading it as "variable exists". The integration egress guard now matches the script's own cgroup, so it no longer blocks the CircleCI agent, which runs as the same user. * fix(ci): keep the policy-load backoff typed as float * fix(ci): retry CyberArk policy loads without blocking the event loop and tighten the worker-kill and Langfuse tests * fix(secrets): load CyberArk policy one request at a time per manager * test(secrets): pin that non-conflict CyberArk policy failures are not retried * test(unit): run tests/unit with only an allowlisted host environment CircleCI's unit job inherits every project env var, so real provider keys, REDIS_HOST, DATABASE_URL and AWS or Azure credentials reached tests that assume none are set. Locally, litellm's import-time load_dotenv did the same from any .env up the tree. The unit conftest now drops every variable outside a small allowlist and disables dotenv before litellm is imported. * test(e2e): name a failed search and the stuck batch status instead of misattributing them The websearch session test read an empty web_search_tool_result_error block as a successful search, so a failing search tool surfaced as a session billing bug. The batch cancellation timeout now reports the last status the proxy returned. * fix(ci): scrub the host environment per unit test instead of for the whole pytest process GHA shards run tests/unit next to other suites in one process, so the import-time scrub deleted MCP_TEST_PEER_PYTHON before tests/mcp_tests read it and the MCP upstream fell back to the SDK2 interpreter. The two websearch tests that called OpenAI and Perplexity live are removed: tests/unit no longer sees their keys. * fix(ci): scrub only the host variables present before litellm is imported The per-test scrub also deleted TIKTOKEN_CACHE_DIR, which litellm sets at import to its bundled encodings, so tokenizer paths tried to download them and hit the socket guard. The prisma setup test now passes its own database URL instead of reading one another test leaked into the process environment. * fix(ci): stop the order-dependent unit reds and settle logging tasks on their own queue LoggingWorker marked a task done on whichever queue was current when the callback finished, so a callback that outlived an event-loop change raised "task_done() called too many times" or undercounted the new loop's queue. It now settles the queue the task came from. The rest are test isolation fixes for failures that only appeared when another file ran first on the same xdist worker: a replaced user_api_key_cache, breaker metrics unregistered by prometheus tests, semantic_router's health-check filter on uvicorn.access, logging tasks carried over from bedrock tests, a Router-written model_cost entry, and a stray post captured by the langflow test. The token counter check now asserts bounded chunking instead of wall-clock time. * test(e2e/ui): wait for the logout redirect before visiting a protected page Logout revokes the session server-side before clearing cookies and navigating, so an immediate page.goto either ran with the cookie still set or was aborted by the logout redirect (net::ERR_ABORTED). * test(unit): restore the prometheus metrics config per test and settle logs carried from earlier tests in the a2a cost tests * test(router): pin the router clock in the usage counter tests so a minute rollover cannot empty the read * test(e2e/ui): wait for logout to clear the token cookie instead of for a login redirect * test(integration/mcp): answer the model-info probe another test's proxy sends to the model double (cherry picked from commit14f4c34c61) * test(e2e): assert only litellm-owned batch behavior and move the blank S3 env pin to an integration test (#43321) (cherry picked from commite53e67ede5) * ci: drop main and litellm_* branch filters from the CircleCI litellm-main workflows (#43272) Co-authored-by: yuneng <yuneng@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commitc822c7fffa) * test(e2e): accept the otel cost write as a linked root trace (#42931) * test(e2e): accept the otel cost write as a linked root trace Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(e2e): window and fail-closed the linked otel trace read-back Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(e2e): poll the otel read-back without recursion Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: yuneng <yuneng@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit3ebf6a1fd8) * refactor(rust): exclude gateway and config crates from rc backport * refactor(rust): exclude router crate from rc backport --------- Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Co-authored-by: yassin <yassin@berri.ai>
541 lines
20 KiB
Python
541 lines
20 KiB
Python
"""Tests for litellm/a2a_protocol/main.py non-streaming send behavior."""
|
|
|
|
import asyncio
|
|
|
|
import httpx
|
|
import pytest
|
|
|
|
pytest.importorskip("a2a.compat.v0_3.conversions")
|
|
|
|
from a2a.compat.v0_3 import conversions as _conv
|
|
from a2a.compat.v0_3.types import (
|
|
MessageSendParams,
|
|
SendMessageRequest,
|
|
SendStreamingMessageRequest,
|
|
)
|
|
|
|
import litellm
|
|
from litellm.integrations.custom_logger import CustomLogger
|
|
from litellm.a2a_protocol.main import (
|
|
_send_message,
|
|
_stream_messages,
|
|
aget_agent_card,
|
|
asend_message,
|
|
create_a2a_client,
|
|
)
|
|
from litellm.caching.llm_caching_handler import LLMClientCache
|
|
from litellm.constants import DEFAULT_A2A_AGENT_TIMEOUT
|
|
from litellm.llms.custom_httpx.http_handler import (
|
|
AsyncHTTPHandler,
|
|
get_async_httpx_client,
|
|
httpxSpecialProvider,
|
|
)
|
|
|
|
|
|
def _request() -> SendMessageRequest:
|
|
params = MessageSendParams(
|
|
message={
|
|
"messageId": "m1",
|
|
"role": "user",
|
|
"parts": [{"kind": "text", "text": "hi"}],
|
|
}
|
|
)
|
|
return SendMessageRequest(id="r1", params=params)
|
|
|
|
|
|
def _message_stream_response():
|
|
sr = _conv.pb2_v10.StreamResponse()
|
|
sr.message.message_id = "reply-1"
|
|
sr.message.role = _conv.pb2_v10.Role.ROLE_AGENT
|
|
sr.message.parts.add().text = "hello back"
|
|
return sr
|
|
|
|
|
|
def _status_update_stream_response():
|
|
sr = _conv.pb2_v10.StreamResponse()
|
|
sr.status_update.task_id = "t1"
|
|
sr.status_update.context_id = "c1"
|
|
return sr
|
|
|
|
|
|
class _FakeClient:
|
|
def __init__(self, *events):
|
|
self._events = events
|
|
|
|
async def send_message(self, _pb_request, context=None):
|
|
self.context = context
|
|
for event in self._events:
|
|
yield event
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_message_returns_message_result():
|
|
response = await _send_message(_FakeClient(_message_stream_response()), _request())
|
|
result = response.root.result
|
|
assert type(result).__name__ == "Message"
|
|
assert response.root.id == "r1"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_message_rejects_update_event_final_with_runtime_error():
|
|
with pytest.raises(RuntimeError, match="Message or Task"):
|
|
await _send_message(_FakeClient(_status_update_stream_response()), _request())
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_streaming_trace_id_prefers_logging_trace_id():
|
|
"""The streaming X-LiteLLM-Trace-Id must use the logging object's trace id (same
|
|
as the non-streaming path), not the JSON-RPC request id, so traces correlate."""
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
from a2a.compat.v0_3.types import (
|
|
MessageSendParams,
|
|
SendStreamingMessageRequest,
|
|
)
|
|
|
|
from litellm.a2a_protocol import main as a2a_main
|
|
from litellm.litellm_core_utils.litellm_logging import Logging
|
|
|
|
request = SendStreamingMessageRequest(
|
|
id="rpc-1",
|
|
params=MessageSendParams(
|
|
message={
|
|
"messageId": "m1",
|
|
"role": "user",
|
|
"parts": [{"kind": "text", "text": "hi"}],
|
|
}
|
|
),
|
|
)
|
|
logging_obj = MagicMock(spec=Logging)
|
|
logging_obj.litellm_trace_id = "trace-from-logging"
|
|
|
|
captured: dict = {}
|
|
|
|
async def _capture(*, base_url, extra_headers=None, streaming=False, **_):
|
|
captured["extra_headers"] = extra_headers
|
|
raise RuntimeError("stop")
|
|
|
|
with patch.object(a2a_main, "create_a2a_client", new=AsyncMock(side_effect=_capture)):
|
|
with pytest.raises(RuntimeError, match="stop"):
|
|
async for _ in a2a_main.asend_message_streaming(
|
|
request=request,
|
|
api_base="http://upstream.local",
|
|
litellm_logging_obj=logging_obj,
|
|
):
|
|
pass
|
|
|
|
assert captured["extra_headers"]["X-LiteLLM-Trace-Id"] == "trace-from-logging"
|
|
|
|
|
|
def test_streaming_logging_obj_carries_call_type_into_model_call_details():
|
|
"""The streaming logging object is built by hand rather than through
|
|
``update_environment_variables``, which is the only place ``call_type`` normally
|
|
reaches ``model_call_details``. Callbacks read the call type from there, so
|
|
without this the streamed turn arrives at every logger with no call type at all
|
|
and OTel's GenAI metrics label it ``chat`` instead of ``invoke_agent``."""
|
|
from a2a.compat.v0_3.types import MessageSendParams, SendStreamingMessageRequest
|
|
|
|
from litellm.a2a_protocol.main import _build_streaming_logging_obj
|
|
|
|
request = SendStreamingMessageRequest(
|
|
id="rpc-call-type",
|
|
params=MessageSendParams(
|
|
message={"messageId": "m1", "role": "user", "parts": [{"kind": "text", "text": "hi"}]}
|
|
),
|
|
)
|
|
|
|
logging_obj = _build_streaming_logging_obj(
|
|
request=request,
|
|
agent_name="some-agent",
|
|
agent_id=None,
|
|
litellm_params=None,
|
|
metadata=None,
|
|
proxy_server_request=None,
|
|
)
|
|
|
|
assert logging_obj.model_call_details["call_type"] == "asend_message_streaming"
|
|
|
|
|
|
_AGENT_CARD = {
|
|
"protocolVersion": "0.3.0",
|
|
"name": "recording-agent",
|
|
"url": "http://127.0.0.1:9/",
|
|
"preferredTransport": "JSONRPC",
|
|
"version": "1.0.0",
|
|
"capabilities": {"streaming": True},
|
|
"defaultInputModes": ["text/plain"],
|
|
"defaultOutputModes": ["text/plain"],
|
|
"skills": [],
|
|
}
|
|
|
|
_RPC_REPLY = {
|
|
"jsonrpc": "2.0",
|
|
"id": "reply",
|
|
"result": {
|
|
"messageId": "reply-1",
|
|
"role": "agent",
|
|
"parts": [{"kind": "text", "text": "pong"}],
|
|
"kind": "message",
|
|
},
|
|
}
|
|
|
|
_AGENT_A_HEADERS = {"x-agent-token": "token-for-a", "x-tenant": "tenant-a"}
|
|
_AGENT_B_HEADERS = {"x-agent-token": "token-for-b", "x-tenant": "tenant-b"}
|
|
|
|
|
|
_LANGGRAPH_TASK_REPLY = {
|
|
"jsonrpc": "2.0",
|
|
"id": "reply",
|
|
"result": {
|
|
"kind": "task",
|
|
"id": "run-1:task-1",
|
|
"contextId": "thread-1",
|
|
"history": [
|
|
{
|
|
"kind": "message",
|
|
"role": "user",
|
|
"parts": [{"kind": "text", "text": "hi"}],
|
|
"messageId": "m-user",
|
|
"taskId": "run-1:task-1",
|
|
"contextId": "thread-1",
|
|
},
|
|
{
|
|
"kind": "message",
|
|
"role": "agent",
|
|
"parts": [{"kind": "text", "text": "langgraph echo: hi"}],
|
|
"messageId": "m-agent",
|
|
"taskId": "run-1:task-1",
|
|
"contextId": "thread-1",
|
|
},
|
|
],
|
|
"status": {"state": "completed", "timestamp": "2026-08-24T00:00:00+00:00"},
|
|
"artifacts": [
|
|
{
|
|
"artifactId": "art-1",
|
|
"name": "Assistant Response",
|
|
"parts": [{"kind": "text", "text": "langgraph echo: hi"}],
|
|
}
|
|
],
|
|
},
|
|
}
|
|
|
|
|
|
_LOWERCASE_BINDING_CARD = {
|
|
"name": "langgraph-agent",
|
|
"version": "1.0.0",
|
|
"capabilities": {"streaming": True},
|
|
"defaultInputModes": ["text/plain"],
|
|
"defaultOutputModes": ["text/plain"],
|
|
"skills": [],
|
|
"supportedInterfaces": [{"url": "http://127.0.0.1:9/", "protocolBinding": "jsonrpc", "protocolVersion": "1.0"}],
|
|
}
|
|
|
|
|
|
class _RequestRecorder:
|
|
"""Records the headers httpx put on the wire, per outbound request."""
|
|
|
|
def __init__(self, card=_AGENT_CARD, rpc_reply=_RPC_REPLY):
|
|
self.card = card
|
|
self.rpc_reply = rpc_reply
|
|
self.card_requests = []
|
|
self.card_urls = []
|
|
self.rpc_requests = []
|
|
self.client = None
|
|
|
|
def __call__(self, request: httpx.Request) -> httpx.Response:
|
|
headers = {k.lower(): v for k, v in request.headers.items()}
|
|
if request.method == "GET":
|
|
self.card_requests.append(headers)
|
|
self.card_urls.append(str(request.url))
|
|
return httpx.Response(200, json=self.card)
|
|
self.rpc_requests.append(headers)
|
|
return httpx.Response(200, json=self.rpc_reply)
|
|
|
|
|
|
def _a2a_client_cache_key(timeout: float, provider: str = httpxSpecialProvider.A2AProvider) -> str:
|
|
return "async_httpx_client" + f"timeout_{timeout}" + provider
|
|
|
|
|
|
async def _seed_shared_a2a_client(
|
|
card=_AGENT_CARD, rpc_reply=_RPC_REPLY, provider: str = httpxSpecialProvider.A2AProvider
|
|
) -> _RequestRecorder:
|
|
"""Put the one A2A client the cache will hand out behind a mock transport.
|
|
|
|
Seeding has to happen on the test's own event loop, because the client cache keys on
|
|
it. The injected client is a real httpx.AsyncClient, so the merge of per-request
|
|
headers over client defaults, which is what these tests are about, stays real.
|
|
"""
|
|
recorder = _RequestRecorder(card=card, rpc_reply=rpc_reply)
|
|
handler = AsyncHTTPHandler(timeout=DEFAULT_A2A_AGENT_TIMEOUT)
|
|
owned_client = handler.client
|
|
handler.client = httpx.AsyncClient(transport=httpx.MockTransport(recorder))
|
|
await owned_client.aclose()
|
|
|
|
litellm.in_memory_llm_clients_cache.set_cache(
|
|
key=_a2a_client_cache_key(DEFAULT_A2A_AGENT_TIMEOUT, provider), value=handler
|
|
)
|
|
seeded = get_async_httpx_client(
|
|
llm_provider=provider,
|
|
params={"timeout": DEFAULT_A2A_AGENT_TIMEOUT},
|
|
)
|
|
assert seeded is handler, "cache key drifted from get_async_httpx_client; these tests would test nothing"
|
|
|
|
recorder.client = handler.client
|
|
return recorder
|
|
|
|
|
|
@pytest.fixture
|
|
def isolated_client_cache(monkeypatch):
|
|
cache = LLMClientCache()
|
|
monkeypatch.setattr(litellm, "in_memory_llm_clients_cache", cache)
|
|
return cache
|
|
|
|
|
|
def _send_request(request_id):
|
|
return SendMessageRequest(
|
|
id=request_id,
|
|
params=MessageSendParams(
|
|
message={"messageId": request_id, "role": "user", "parts": [{"kind": "text", "text": "hi"}]}
|
|
),
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_extra_headers_never_land_on_the_shared_cached_client(isolated_client_cache):
|
|
"""get_async_httpx_client hands back a process-wide shared client, so a caller's
|
|
headers written onto it would outlive the request that supplied them."""
|
|
recorder = await _seed_shared_a2a_client()
|
|
|
|
await create_a2a_client(base_url="http://127.0.0.1:9", extra_headers=_AGENT_A_HEADERS)
|
|
|
|
assert "x-agent-token" not in recorder.client.headers
|
|
assert "x-tenant" not in recorder.client.headers
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_callers_with_different_headers_reuse_one_pooled_client(isolated_client_cache):
|
|
"""Headers must not segregate the connection pool. Every A2A caller on one timeout
|
|
shares one cached client, so header sets cannot multiply cached clients."""
|
|
recorder = await _seed_shared_a2a_client()
|
|
|
|
client_a = await create_a2a_client(base_url="http://127.0.0.1:9", extra_headers=_AGENT_A_HEADERS)
|
|
client_b = await create_a2a_client(base_url="http://127.0.0.1:9", extra_headers=_AGENT_B_HEADERS)
|
|
client_none = await create_a2a_client(base_url="http://127.0.0.1:9")
|
|
|
|
assert client_a._litellm_httpx_client is recorder.client
|
|
assert client_b._litellm_httpx_client is recorder.client
|
|
assert client_none._litellm_httpx_client is recorder.client
|
|
|
|
cached = [key for key in isolated_client_cache.cache_dict if "a2a_provider" in key]
|
|
assert len(cached) == 1, f"expected one pooled A2A client, cached: {cached}"
|
|
|
|
|
|
@pytest.mark.parametrize("order", [("a", "b", "none"), ("b", "none", "a"), ("none", "a", "b")])
|
|
@pytest.mark.asyncio
|
|
async def test_each_caller_sends_only_its_own_headers(order, isolated_client_cache):
|
|
"""Whatever order callers arrive in, each request carries that caller's headers and
|
|
no other caller's, and a caller with no extra_headers sends none."""
|
|
recorder = await _seed_shared_a2a_client()
|
|
headers_by_caller = {"a": _AGENT_A_HEADERS, "b": _AGENT_B_HEADERS, "none": None}
|
|
|
|
for caller in order:
|
|
a2a_client = await create_a2a_client(base_url="http://127.0.0.1:9", extra_headers=headers_by_caller[caller])
|
|
await _send_message(a2a_client, _send_request(caller))
|
|
|
|
received = dict(zip(order, recorder.rpc_requests, strict=True))
|
|
assert received["a"]["x-agent-token"] == "token-for-a"
|
|
assert received["a"]["x-tenant"] == "tenant-a"
|
|
assert received["b"]["x-agent-token"] == "token-for-b"
|
|
assert received["b"]["x-tenant"] == "tenant-b"
|
|
assert "x-agent-token" not in received["none"]
|
|
assert "x-tenant" not in received["none"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_streaming_send_carries_only_its_own_caller_headers(isolated_client_cache):
|
|
"""The streaming path shares the same pooled client, so it needs the same guard."""
|
|
recorder = await _seed_shared_a2a_client()
|
|
|
|
client_a = await create_a2a_client(base_url="http://127.0.0.1:9", extra_headers=_AGENT_A_HEADERS, streaming=True)
|
|
await _send_message(client_a, _send_request("a"))
|
|
|
|
client_b = await create_a2a_client(base_url="http://127.0.0.1:9", extra_headers=_AGENT_B_HEADERS, streaming=True)
|
|
streaming_request = SendStreamingMessageRequest(
|
|
id="b",
|
|
params=MessageSendParams(message={"messageId": "b", "role": "user", "parts": [{"kind": "text", "text": "hi"}]}),
|
|
)
|
|
async for _ in _stream_messages(client_b, streaming_request):
|
|
pass
|
|
|
|
received = dict(zip(("a", "b"), recorder.rpc_requests, strict=True))
|
|
assert received["a"]["x-agent-token"] == "token-for-a"
|
|
assert received["b"]["x-agent-token"] == "token-for-b"
|
|
assert received["b"]["x-tenant"] == "tenant-b"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_lowercase_protocol_binding_card_round_trips_the_langgraph_dialect(isolated_client_cache):
|
|
"""LangGraph Platform serves cards with protocolBinding "jsonrpc" and answers in the
|
|
A2A 0.3 JSON dialect ("kind"-discriminated) while declaring protocolVersion "1.0".
|
|
Without binding normalization client creation raises ValueError("no compatible
|
|
transports found."); without the version downgrade the SDK's strict v1 transport
|
|
rejects the reply with 'Message type "lf.a2a.v1.Task" has no field named "kind"'."""
|
|
await _seed_shared_a2a_client(card=_LOWERCASE_BINDING_CARD, rpc_reply=_LANGGRAPH_TASK_REPLY)
|
|
|
|
a2a_client = await create_a2a_client(base_url="http://127.0.0.1:9")
|
|
response = await _send_message(a2a_client, _send_request("lc"))
|
|
|
|
assert type(response.root.result).__name__ == "Task"
|
|
assert response.root.result.artifacts[0].parts[0].root.text == "langgraph echo: hi"
|
|
interface = a2a_client._litellm_agent_card.supported_interfaces[0]
|
|
assert interface.protocol_binding == "JSONRPC"
|
|
assert interface.protocol_version == "0.3"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_agent_card_fetch_carries_the_callers_headers(isolated_client_cache):
|
|
"""Agent cards can sit behind the same auth as the agent, so the card fetch must stay
|
|
authenticated once the headers stop living on the client."""
|
|
recorder = await _seed_shared_a2a_client()
|
|
|
|
await create_a2a_client(base_url="http://127.0.0.1:9", extra_headers=_AGENT_A_HEADERS)
|
|
|
|
assert recorder.card_requests, "no agent card request was made"
|
|
assert recorder.card_requests[-1]["x-agent-token"] == "token-for-a"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_agent_card_path_param_fetches_that_path_with_the_agents_headers(isolated_client_cache):
|
|
"""A Microsoft Foundry agent serves its card only at agentCard/v1.0 behind the same Entra bearer
|
|
as the agent, so an agent registered with agent_card_path fetches exactly that path, authenticated,
|
|
instead of probing the well-known paths."""
|
|
recorder = await _seed_shared_a2a_client()
|
|
|
|
await asend_message(
|
|
request=_send_request("req-foundry"),
|
|
api_base="http://127.0.0.1:9",
|
|
litellm_params={"agent_card_path": "agentCard/v1.0"},
|
|
agent_extra_headers=_AGENT_A_HEADERS,
|
|
)
|
|
|
|
assert recorder.card_urls == ["http://127.0.0.1:9/agentCard/v1.0"]
|
|
assert recorder.card_requests[-1]["x-agent-token"] == "token-for-a"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_aget_agent_card_carries_the_callers_headers_and_path(isolated_client_cache):
|
|
recorder = await _seed_shared_a2a_client(provider=httpxSpecialProvider.A2A)
|
|
|
|
await aget_agent_card(
|
|
base_url="http://127.0.0.1:9", extra_headers=_AGENT_A_HEADERS, relative_card_path="agentCard/v1.0"
|
|
)
|
|
|
|
assert recorder.card_urls == ["http://127.0.0.1:9/agentCard/v1.0"]
|
|
assert recorder.card_requests[-1]["x-agent-token"] == "token-for-a"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_the_pooled_a2a_client_arrives_with_cookie_persistence_disabled(isolated_client_cache):
|
|
"""create_a2a_client takes its client from the shared builder rather than building one,
|
|
and the builder is what refuses to persist cookies. This pins the join between those
|
|
two facts, so the A2A path cannot quietly start acquiring a client that keeps a jar.
|
|
|
|
test_callers_with_different_headers_reuse_one_pooled_client pins the other half, that
|
|
create_a2a_client hands back exactly this cached client."""
|
|
handler = get_async_httpx_client(
|
|
llm_provider=httpxSpecialProvider.A2AProvider,
|
|
params={"timeout": DEFAULT_A2A_AGENT_TIMEOUT},
|
|
)
|
|
request = httpx.Request("GET", "https://agent-a.example.com/")
|
|
handler.client.cookies.extract_cookies(
|
|
httpx.Response(200, headers={"set-cookie": "SESSION=only-agent-a-may-hold-this"}, request=request)
|
|
)
|
|
|
|
assert dict(handler.client.cookies) == {}, "the pooled A2A client kept an upstream's cookie"
|
|
await handler.close()
|
|
|
|
|
|
class _UsageRecorder(CustomLogger):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.logged = asyncio.Event()
|
|
self.payload = None
|
|
|
|
async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
|
|
self.payload = kwargs["standard_logging_object"]
|
|
self.logged.set()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_asend_message_counts_usage_off_the_event_loop(monkeypatch):
|
|
from tests.large_text import text
|
|
from tests.unit.litellm_core_utils.event_loop_lag import (
|
|
assert_loop_stayed_free,
|
|
timed_with_loop_lags,
|
|
warm_tokenizer,
|
|
)
|
|
|
|
warm_tokenizer("gpt-5.6-luna")
|
|
recorder = _UsageRecorder()
|
|
monkeypatch.setattr(litellm, "callbacks", [recorder])
|
|
monkeypatch.setattr(litellm, "success_callback", [recorder])
|
|
monkeypatch.setattr(litellm, "_async_success_callback", [recorder])
|
|
|
|
reply = _conv.pb2_v10.StreamResponse()
|
|
reply.message.message_id = "reply-1"
|
|
reply.message.role = _conv.pb2_v10.Role.ROLE_AGENT
|
|
reply.message.parts.add().text = text * 100
|
|
request = SendMessageRequest(
|
|
id="r1",
|
|
params=MessageSendParams(
|
|
message={"messageId": "m1", "role": "user", "parts": [{"kind": "text", "text": text * 100}]}
|
|
),
|
|
)
|
|
|
|
response, took, lags = await timed_with_loop_lags(
|
|
lambda: asend_message(a2a_client=_FakeClient(reply), request=request)
|
|
)
|
|
|
|
assert response.id == "r1"
|
|
await asyncio.wait_for(recorder.logged.wait(), timeout=10)
|
|
assert recorder.payload["prompt_tokens"] > 100_000
|
|
assert recorder.payload["completion_tokens"] > 100_000
|
|
assert_loop_stayed_free(took, lags)
|
|
|
|
|
|
def test_streaming_logging_obj_keeps_agent_credentials_out_of_logging_params():
|
|
"""Callbacks receive the streaming logging object's litellm_params as raw kwargs, so an agent's
|
|
Entra, Databricks, or static credentials must never be copied into it; only pricing keys are."""
|
|
from litellm.a2a_protocol.main import _build_streaming_logging_obj
|
|
|
|
request = SendStreamingMessageRequest(
|
|
id="rpc-secrets",
|
|
params=MessageSendParams(
|
|
message={"messageId": "m1", "role": "user", "parts": [{"kind": "text", "text": "hi"}]}
|
|
),
|
|
)
|
|
|
|
logging_obj = _build_streaming_logging_obj(
|
|
request=request,
|
|
agent_name="foundry-agent",
|
|
agent_id="agent-1",
|
|
litellm_params={
|
|
"client_secret": "sp-secret",
|
|
"azure_ad_token": "entra-token",
|
|
"tenant_id": "tenant",
|
|
"databricks_oauth": {"client_secret": "dbx-secret"},
|
|
"api_key": "static-key",
|
|
"cost_per_query": 0.25,
|
|
},
|
|
metadata={"user_api_key": "hashed"},
|
|
proxy_server_request={"url": "http://localhost:4000"},
|
|
)
|
|
|
|
expected = {
|
|
"cost_per_query": 0.25,
|
|
"metadata": {"user_api_key": "hashed"},
|
|
"proxy_server_request": {"url": "http://localhost:4000"},
|
|
}
|
|
assert logging_obj.litellm_params == expected
|
|
assert logging_obj.optional_params == expected
|
|
assert logging_obj.model_call_details["litellm_params"] == expected
|