The short answer: when a raw HTTP request succeeds but the same call through the SDK fails (or behaves differently), stop changing the prompt. Capture the exact request the SDK is sending, compare it field-by-field with your working raw request, and look for differences in headers, body shape, model name, base URL, or hidden defaults. The bug is almost always in the translation layer, not in Grok itself.
I have lost more evenings than I care to admit to this exact situation. A curl or httpx call returns a clean 200. The identical-looking call through the SDK raises an exception or returns unexpected content. My first instinct used to be “the model must be broken” or “I need a better prompt.” The real problem was almost always a silent difference in what the SDK actually transmitted. This article is the checklist I now follow instead of guessing.
What This Solves
You have a working raw request and a failing (or mysteriously different) SDK call. You need a systematic way to find the gap without rewriting everything or blaming the model. By the end of this post you will know:
How to log or intercept the exact request the SDK sends
The most common differences that break otherwise identical calls
A practical comparison workflow that isolates the problem in minutes
When to stay with the SDK and when to drop to raw HTTP temporarily
This belongs in the Developer Tools and SDKs category because the friction lives in the client layer, not in the core API concepts.
Who Should Use This Approach
Developers who already know how to make both a raw HTTP request and an SDK request to Grok and have hit the frustrating case where one works and the other does not. If you have not yet made a successful request of either kind, start with the earlier Grok API Starting Point articles.
The Core Principle
Treat the SDK as a convenience layer that should produce the same HTTP traffic as your raw request, then prove it. When the results diverge, the evidence you need is the actual bytes (or the structured equivalent) that left the process. Everything else is speculation.
Step-by-Step Debugging Workflow

1. Freeze the working raw request
Save the exact raw request that succeeds. Include:
Full URL
Every header (especially Authorization and Content-Type)
The complete JSON body
The HTTP status and the full response body
Do not edit it while debugging. It is your ground truth.
2. Make the SDK call as similar as possible
Use the same model string, the same messages, and the same temperature / max_tokens / other parameters you care about. Turn off any SDK features you are not deliberately testing (streaming, automatic retries, extra middleware).
3. Capture what the SDK actually sends
You have several practical options depending on the client:
OpenAI-compatible client (openai package)
Enable debug logging or use a custom httpx transport that prints the request:
Python
import httpx
import logging
from openai import OpenAI
logging.basicConfig(level=logging.DEBUG)
# or, more targeted:
def log_request(request: httpx.Request):
print(">>> SDK REQUEST")
print(request.method, request.url)
print(dict(request.headers))
print(request.content.decode() if request.content else None)
transport = httpx.HTTPTransport()
# wrap or use an event hook in newer httpx
client = OpenAI(
api_key=os.getenv("XAI_API_KEY"),
base_url="https://api.x.ai/v1",
http_client=httpx.Client(event_hooks={"request": [log_request]}),
)Official xAI SDK
Check the current documentation for debug flags or logging configuration. If none exist, temporarily fall back to the OpenAI-compatible client or to raw HTTP for the comparison. The goal is visibility, not purity.
Nuclear option
Point both the SDK and your raw client at a local proxy (mitmproxy, Charles, or even a simple logging reverse proxy) and compare the captured traffic side by side.
4. Diff the two requests
Look for differences in this order:
Base URL — Is the SDK still pointed at https://api.x.ai/v1?
Authorization header — Is the key present, correctly formatted as Bearer ..., and the same key?
Model name — Exact string match? Hidden aliases or default model overrides?
Messages / input shape — Extra system messages, different role names, or unexpected wrapping?
Parameters — temperature, max_tokens, top_p, stop sequences, or reasoning-related flags that the SDK adds by default
Content-Type and body encoding — JSON vs form, unexpected nulls, or extra fields
Extra headers — User-Agent, x-request-id, or SDK-specific headers that the server might treat differently
Most of the time the difference appears in the first four items.
5. Capture the response side as well
Even when the request looks identical, compare:
HTTP status
finish_reason
usage numbers
presence or absence of tool_calls
any refusal or error fields
A request that is almost identical can still produce different behavior if one path triggers a different code path on the server (for example, a default parameter that changes sampling).
Common Culprits I Have Actually Hit
The OpenAI client was still using the default OpenAI base URL because base_url was set after the client was constructed or was overridden by an environment variable.
The SDK was sending a different model name because of a default or an alias that resolved differently.
An extra stream=True or an unexpected tools parameter was present in the SDK call and absent in the raw call.
The Authorization header was being set correctly in raw HTTP but the SDK was reading a different environment variable or an empty string.
A timeout or proxy setting present in one client and not the other caused the request to take a different network path.
The raw request used the /v1/chat/completions endpoint while the SDK was using a newer /v1/responses style endpoint (or vice versa) with a slightly different body schema.
None of these are model problems. All of them look like “the SDK is broken” until you compare the actual traffic.
A Minimal Comparison Script Pattern
Keep a small debug script that can run the same logical request both ways and print a side-by-side summary:
Python
# pseudocode structure – adapt to your preferred clients
raw_response = do_raw_http(model, messages)
sdk_response = do_sdk_call(model, messages)
print("RAW finish_reason:", raw_response["choices"][0]["finish_reason"])
print("SDK finish_reason:", sdk_response.choices[0].finish_reason)
print("RAW usage:", raw_response.get("usage"))
print("SDK usage:", sdk_response.usage)
# plus a full dump of both request bodies when they differRun it every time the two paths diverge. The script becomes institutional knowledge for your project.
When to Stay with the SDK vs. Drop to Raw HTTP
Stay with the SDK when the comparison shows the requests are truly identical and the difference is on the response side (or when the SDK simply provides better types and error handling for your use case).
Drop to raw HTTP temporarily when:
You cannot get the SDK to emit the request shape you need
You are isolating a bug to report upstream
You need to test a brand-new endpoint or parameter that the SDK does not yet expose
The SDK’s hidden retries or middleware are interfering with your observability
Once you understand the difference, you can usually go back to the SDK with an explicit parameter or a small wrapper. Permanent raw HTTP is rarely the best long-term answer for application code.
A Note from the Home Lab
One of my internal tools started failing after I upgraded the OpenAI client library. The raw httpx path I kept for debugging continued to work. The SDK path began returning unexpected finish reasons. The diff showed that the newer client was sending an extra parameter that the older one had omitted and that the server treated as significant. Pinning the parameter explicitly in the SDK call fixed it in five minutes. Without the side-by-side comparison I would have spent the evening changing prompts and model names.

Practical Checklist
I have a frozen, working raw request (URL, headers, body, response)
I can log or intercept the exact request the SDK sends
I have compared base URL, Authorization, model, messages, and key parameters
I have compared finish_reason and usage on both paths
I know whether the difference is in the request or only in the response
I have decided whether to fix the SDK call, wrap it, or temporarily use raw HTTP
When a Simpler Approach Is Better
If you are only making a few exploratory calls, pick one client and stay with it. The dual-path debugging workflow is for the moment when the two paths disagree. Do not maintain two permanent implementations “just in case.” That usually creates more drift than it prevents.
Closing
When the raw request works and the SDK does not, the model is rarely the problem. The translation layer is. Capture both requests, compare them field by field, and let the evidence tell you what changed.
The SDK is a tool. Visibility is the method.
Build the comparison.
Explain every difference you find.
Verify that the two paths produce the same request before you trust the SDK again.
Build it. Explain it. Verify it.
Next we will look at what to log when a Grok request fails before it even reaches the model—the network, authentication, and client-side errors that never produce a normal completion object.
Comments
No comments yet — be the first to share a thought.