Repository navigation
fix(snowflake): normalize Cortex Claude request shapes - #39453
Conversation
|
PR #39453 labeled |
Greptile SummaryThe PR normalizes Snowflake Cortex Claude request, response, and streaming shapes using shared Anthropic conversion logic.
Confidence Score: 5/5The PR appears safe to merge because no blocking failure remains. No blocking failure remains.
|
| Filename | Overview |
|---|---|
| litellm/llms/snowflake/chat/transformation.py | Adds Cortex Claude normalization and shared Anthropic parsing. |
| tests/test_litellm/llms/snowflake/chat/test_snowflake_chat_transformation.py | Adds request, response, cache, media, thinking, and streaming transformation coverage. |
| tests/test_litellm/llms/snowflake/test_snowflake_native_endpoints.py | Extends native Snowflake endpoint coverage for the normalized Claude behavior. |
Reviews (4): Last reviewed commit: "fix(snowflake): surface Cortex prompt-ca..." | Re-trigger Greptile
| def _extract_system_and_messages(self, messages: list[AllMessageValues]) -> tuple[str | None, list[dict]]: | ||
| def _extract_system_and_messages( # mutable-ok: JSON wire messages | ||
| self, messages: list[AllMessageValues] | ||
| ) -> tuple[list[dict] | None, list[dict]]: |
There was a problem hiding this comment.
Inconsistent Python type discipline
The new normalization code uses coarse list[dict] types, mutates optional_params without the required suppression, and adds lines beyond 120 characters, weakening type checking and maintainability across this adapter
Context Used: CLAUDE.md (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
There was a problem hiding this comment.
Fixed on 4eb7ba3. The new path now delegates to the shared Anthropic converters, removing the coarse hand-rolled conversion; lint and type-budget gates pass.
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
|
@greptileai Please re-review the latest commit and provide a confidence score. |
9085678 to
49ea24c
Compare
Co-authored-by: Kamron Javaherpour <kamron@kargo.com> Co-authored-by: Oleksandr Kononov <oleks.konov@kargo.com>
49ea24c to
b536eeb
Compare
|
@greptileai can you reply here with score and why |
|
bugbot run |
|
Confidence score: 5/5. The latest revision correctly addresses the requested Cortex Claude translation issues: structured system blocks and cache controls are preserved and normalized, bridged images/tool results are converted back to Anthropic-native blocks, thinking support is gated by the model capability catalog, and streamed tool identity is emitted only on |
| if not isinstance(image_url_value, str) or not image_url_value: | ||
| return dict(block) # mutable-ok: JSON wire block | ||
|
|
||
| image: Final = convert_to_anthropic_image_obj(openai_image_url=image_url_value, format=image_format) |
There was a problem hiding this comment.
Low: Unbounded image downloads block request workers
An authenticated user can submit many image_url blocks pointing to slow public servers, and each URL is downloaded synchronously here before the asynchronous provider call. Although each image is size-limited, there is no limit on the number or cumulative size of downloads, so one request can tie up a worker and consume substantial outbound bandwidth; enforce per-request image/count and cumulative-byte limits and use asynchronous fetching with a dedicated short timeout, or require data URIs for this provider.
There was a problem hiding this comment.
Fixed holistically at the seam: this path now delegates to the shared Anthropic converters instead of calling the low-level base64 helper, so it inherits any download budget added there. Cortex documents base64 sources only, so remote URLs must still be inlined exactly as Bedrock invoke and Vertex inline them. Capping per-request image count and cumulative bytes belongs in that shared helper, not one provider; filing it separately.
There was a problem hiding this comment.
Thanks for the detail. I can't automatically confirm this is safe to dismiss, so I'm leaving the thread open for a maintainer to make the call.
There was a problem hiding this comment.
Follow-up: the concern is valid for the shared remote-image fetch primitive. This PR now uses that shared primitive; a cross-provider budget and timeout change needs separate scope, so the maintainer decision remains open.
PR overviewThis PR normalizes Claude request payload shapes for Snowflake Cortex chat, including transforming image URL content into provider-compatible input. One security concern remains in image handling: an authenticated user can submit many slow image URLs, tying up synchronous request workers and consuming outbound bandwidth. No security issues have yet been addressed, and per-request download limits or safer fetching controls are still needed. Open issues (1)
Fixed/addressed: 0 · PR risk: 5/10 |
|
@greptileai Please re-review the latest commit and provide a confidence score. |
|
@veria-ai Please re-review the latest commit. |
|
@cursor Bugbot Please re-review the latest commit. |
|
You need to increase your spend limit or enable usage-based billing to run background agents. Go to Cursor |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 4eb7ba3. Configure here.
mateo-berri
left a comment
There was a problem hiding this comment.
Snowflake documents extended thinking (budget_tokens) for the Messages API; only adaptive thinking is 4.6-gated. Two thinking findings below block merge.
| "tool_choice", | ||
| ] | ||
| if _is_claude_model(model): | ||
| if _is_claude_model(model) and AnthropicModelInfo._is_adaptive_thinking_model(model, "snowflake"): |
There was a problem hiding this comment.
Snowflake's Messages API docs list extended thinking (budget_tokens) alongside adaptive; only adaptive is 4.6-gated. This silently drops thinking for sonnet-4-5, 4-sonnet, haiku-4-5.
There was a problem hiding this comment.
Agreed, fixed on 0f01333. The 4.6 gate is gone; thinking is advertised for every Claude model again, since only adaptive thinking is 4.6-gated. Test asserts sonnet-4-5, 4-opus and 3-7-sonnet all keep it.
| "supports_response_schema": true, | ||
| "prompt_cache_min_tokens": 1024 | ||
| "prompt_cache_min_tokens": 1024, | ||
| "supports_reasoning": false |
There was a problem hiding this comment.
Every other provider keeps claude-sonnet-4-5 reasoning-capable, and Snowflake's own reasoning example uses this model. These flips make supports_reasoning wrong for five entries.
There was a problem hiding this comment.
Agreed, reverted on 0f01333. Both model-price maps are now byte-identical to staging, so the five supports_reasoning flips are gone entirely and the capability question stays out of this PR.
Parse Cortex's Anthropic-dialect responses and SSE with Anthropic's own parser so cache_creation/cache_read counts, thinking blocks and signatures reach the caller. Restore thinking for every Claude model: Cortex documents extended thinking broadly and only adaptive thinking is 4.6-gated.
|
Latest commit 0f01333 fixes the two E2E response-side gaps and both blocking review findings.
Cortex responses and SSE are now parsed by Anthropic own parser rather than a hand-rolled one, which is what closes these as a class. Open item: I could not reproduce the extra empty tool-arguments chunk. Same synthetic stream is clean before and after the change, so I would need the raw SSE from that run to chase it. |
|
@greptileai Please re-review the latest commit and provide a confidence score. |
|
@cursor Bugbot Please re-review the latest commit. |
|
You need to increase your spend limit or enable usage-based billing to run background agents. Go to Cursor |
Live QA against Snowflake CortexLive run against a paid Snowflake account (Cortex REST API, real Claude calls) through a local proxy on Setup model_list:
- model_name: snowflake-sonnet-4-6
litellm_params:
model: snowflake/claude-sonnet-4-6
api_key: os.environ/SNOWFLAKE_API_KEY # pat/<programmatic access token>
api_base: os.environ/SNOWFLAKE_API_BASE # https://<org>-<account>.snowflakecomputing.com/api/v2
- model_name: snowflake-sonnet-4-5
litellm_params:
model: snowflake/claude-sonnet-4-5
api_key: os.environ/SNOWFLAKE_API_KEY
api_base: os.environ/SNOWFLAKE_API_BASEP=http://localhost:4000
A=(-H "Authorization: Bearer sk-1234" -H "content-type: application/json")
IMG=$(base64 -w0 red_64x64.png) # a solid red 64x64 PNG
LONG=$(python3 -c "print('The secret code word is PINEAPPLE. ' * 120)")After (0f01333)System cache_control with unsupported ttl, /v1/messages
Cache usage on /chat/completions
Base64 image, /chat/completions image_url
Base64 image, /v1/messages native block
Remote URL image, /chat/completions (captured at 4eb7ba3, request path unchanged since)
Image tool_result with cache_control and $schema in the tool, /v1/messages (captured at 4eb7ba3)
Streamed tool call, /v1/messages (captured at 4eb7ba3)
Streamed tool call, /chat/completions (captured at 4eb7ba3)
Thinking on claude-sonnet-4-6, /v1/messages (captured at 4eb7ba3)
|
|
bugbot run |
The reference converter extends signed thinking blocks on each assistant turn, not just tool-call turns, so a replayed thinking-plus-text response keeps its signed block. Content-less thinking turns send no empty text block.
|
bugbot run |
|
@greptileai can you reply here with score pls and why |
|
Confidence score: 4/5. The changes directly address the reported Cortex issues: Anthropic-shaped system/cache blocks are preserved and normalized, images and tool results are converted to native blocks, adaptive thinking is capability-gated, signed thinking blocks round-trip, and the shared Anthropic response/SSE parsers now preserve cache usage, reasoning, and one-time streamed tool identity. The added tests cover these request, response, and streaming cases, and the live Cortex checks provide additional evidence. I’m not giving 5/5 because this changes the wire format and parsing path for all Snowflake Claude traffic, while most automated coverage is unit-level rather than full end-to-end coverage across less common content combinations, multiple tool calls, and all streaming event sequences. |
|
@greptileai can you reply here with score & why |
|
bugbot run |
|
Confidence score: 4/5 The fix is well-scoped and addresses the reported behaviors end to end: Anthropic system/cache blocks are preserved, images and tool results are normalized, adaptive thinking is capability-gated, streamed tool identity is emitted only once, and Cortex responses/SSE are parsed through the Anthropic implementations. The targeted tests plus live Snowflake validation provide strong evidence for caching, vision, tool calls, thinking, and usage fields. I’m reserving 5/5 because this touches shared conversion, streaming, and billing-related parsing paths, so the remaining risk is regression in less common multi-turn/mixed-content cases or provider-wide behavior not covered by the shown evidence. |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 74c7bb5. Configure here.
TLDR
Problem this solves:
How it solves it:
User Flow
Before: a developer sends a Claude-compatible request through the gateway to Snowflake Cortex, but some valid Anthropic inputs arrive in a shape Cortex cannot use
usagehas onlyinput_tokensandoutput_tokens, and anythinkingblock Cortex produced is goneAfter: the same request keeps the Anthropic structure Cortex expects
usagecarriescache_creation_input_tokens/cache_read_input_tokens, andthinkingblocks come back with their signatureRelevant issues
Ports and corrects the functional changes from a customer's fork of LiteLLM
Linear ticket
Pre-Submission checklist
Screenshots / Proof of Fix
Live run against a paid Snowflake account (Cortex REST API, real Claude calls) through a local proxy on
localhost:4000. Requests hitting Cortex were checked against the outgoing wire body in the--detailed_debugproxy logSetup
After (0f01333)
System cache_control with unsupported ttl, /v1/messages
Command (run twice)
Output, first call
{"text":"PINEAPPLE","stop_reason":"end_turn","usage":{"input_tokens":18,"output_tokens":8,"cache_creation_input_tokens":1323}}Output, second call
{"text":"PINEAPPLE","stop_reason":"end_turn","usage":{"input_tokens":18,"output_tokens":8,"cache_read_input_tokens":1323}}Wire body to
/cortex/v1/messages(proxy log):systemis a list of text blocks withcache_control: {'type': 'ephemeral'},ttlstrippedCache usage on /chat/completions
Command
Output
{"completion_tokens":12,"prompt_tokens":12,"total_tokens":24,"completion_tokens_details":{"reasoning_tokens":0,"text_tokens":12},"prompt_tokens_details":{"cached_tokens":0,"text_tokens":12,"cache_write_tokens":0,"cache_creation_tokens":0,"cache_creation_token_details":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}},"cache_creation_input_tokens":0,"cache_read_input_tokens":0}Base64 image, /chat/completions image_url
Command
Output
{"content":"**Red**"}Wire body:
{'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/png', ...}}Base64 image, /v1/messages native block
Command
Output
{"text":"**Red**","usage":{"input_tokens":28,"output_tokens":6}}Remote URL image, /chat/completions (captured at 4eb7ba3, request path unchanged since)
Command
Output
{"content":"Here are five words describing the image:\n\n**Cute, pink, cartoon pig face**"}Wire body: the URL was fetched and sent as a base64
imageblockImage tool_result with cache_control and $schema in the tool, /v1/messages (captured at 4eb7ba3)
Command
Output
{"text":"**Red.**","stop_reason":"end_turn","usage":{"input_tokens":626,"output_tokens":6}}Wire body:
input_schemahas no$schemakey,tool_result.contentis a nativeimageblockStreamed tool call, /v1/messages (captured at 4eb7ba3)
Command
Output (id and name only on
content_block_start){"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_bdrk_01Ecbti1FXaXwm6VFDYeRgcS","name":"get_weather","input":{}}} {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"city\": \"Pa"}} {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"ris\""}} {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":", \""}} {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"unit\""}} {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":": \"c"}} {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"elsius\"}"}} {"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"input_tokens":670,"output_tokens":50}}Streamed tool call, /chat/completions (captured at 4eb7ba3)
Command
Output
{"id":"toolu_bdrk_012RHaaqLtGfMxKyBzUVVp7Z","function":{"arguments":"","name":"get_weather"},"type":"function","index":0} {"function":{"arguments":""},"type":"function","index":0} {"function":{"arguments":"{\"city\": \"P"},"type":"function","index":0} {"function":{"arguments":"aris\""},"type":"function","index":0} {"function":{"arguments":", \"uni"},"type":"function","index":0} {"function":{"arguments":"t\""},"type":"function","index":0} {"function":{"arguments":": \"ce"},"type":"function","index":0} {"function":{"arguments":"lsius\"}"},"type":"function","index":0}Thinking on claude-sonnet-4-6, /v1/messages (captured at 4eb7ba3)
Command
Output
{"text":["391"],"usage":{"input_tokens":49,"output_tokens":13}}Raw Cortex response in the proxy log:
content=[{"type":"thinking","thinking":"391","signature":"Eto..."},{"type":"text","text":"391"}]Type
Bug Fix
Caveats (if any)
Low
thinkingis allowed on every Cortex Claude model, onlytype: adaptiveis 4.6-gatedLink to Devin session: https://app.devin.ai/sessions/49ef770df35a4bbf990a167166f399cf
Open in Devin Desktop: https://app.devin.ai/desktop/session/49ef770df35a4bbf990a167166f399cf?variant=devin
Note
Medium Risk
Touches message transformation, tool/streaming behavior, and usage accounting on a provider path; regressions could break Claude-on-Cortex or billing visibility, but changes reuse well-tested Anthropic shared code and are heavily covered by new tests.
Overview
Aligns Snowflake Cortex Claude (
/cortex/v1/messages) with the rest of LiteLLM’s Anthropic dialects so bridged OpenAI/Anthropic clients send wire shapes Cortex accepts and get full responses back.Outgoing requests now emit Anthropic-style system as text blocks (with cache_control normalized and unsupported
ttlstripped), convertimage_urland multipart tool results to native image/document blocks (base64 inlining), preserve signed thinking blocks on follow-up turns, strip top-level$schemafrom tool schemas, and honor an explicitsystemoptional param when provided.Responses and streaming delegate to shared
AnthropicConfig/AnthropicStreamParserinstead of bespoke parsers, so thinking / reasoning, prompt-cache usage inprompt_tokens_details, and streamed tool-call chunks (id/name only oncontent_block_start) match other Anthropic providers.thinkingis advertised in supported params for all Cortex Claude models.Reviewed by Cursor Bugbot for commit 74c7bb5. Bugbot is set up for automated code reviews on this repo. Configure here.