# Grok API with Python

A working Grok 4.5 integration for Python using the OpenAI SDK and the Grok API Dev base URL. The examples cover a regular request, AsyncOpenAI, streaming, timeouts, and API errors.

## Install the Python SDK

```bash
python -m pip install --upgrade openai
```

```bash
export GROK_API_DEV_KEY="sk-lg-YOUR_API_KEY"
```

## Send the first request

```python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["GROK_API_DEV_KEY"],
    base_url="https://api.llm-gate.tech/v1",
    timeout=3600.0,
    max_retries=2,
)

response = client.responses.create(
    model="grok-4.5",
    input="Explain SSE in two sentences.",
)

print(response.output_text)
print(response.usage)
```

## Use AsyncOpenAI

```python
import asyncio
import os
from openai import AsyncOpenAI

client = AsyncOpenAI(
    api_key=os.environ["GROK_API_DEV_KEY"],
    base_url="https://api.llm-gate.tech/v1",
)

async def main() -> None:
    response = await client.responses.create(
        model="grok-4.5",
        input="Hello!",
    )
    print(response.output_text)

asyncio.run(main())
```

## Stream a Grok response

```python
stream = client.responses.create(
    model="grok-4.5",
    input="Write a short Python example.",
    stream=True,
)

for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="", flush=True)
```

## Timeouts, retries, and errors

The OpenAI SDK retries selected temporary failures. Set a finite timeout and max_retries so request behavior stays predictable.

```python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["GROK_API_DEV_KEY"],
    base_url="https://api.llm-gate.tech/v1",
    max_retries=2,
    timeout=3600.0,
)
```

- 401: check GROK_API_DEV_KEY and whether the key is active.
- 404: check the base URL and the grok-4.5 model ID.
- 429: reduce concurrency and retry after a delay.
- Temporary 5xx: use a limited retry with exponential backoff.

[Full API error reference](https://grok-api.dev/en/docs/errors)

## Related pages

- [Messages API](https://grok-api.dev/en/docs/messages)
- [Streaming API](https://grok-api.dev/en/docs/streaming)
- [TypeScript](https://grok-api.dev/en/docs/typescript)
- [cURL](https://grok-api.dev/en/docs/curl)
