# Connect OpenAI Python SDK

https://modelportal.ai/docs/integrations/openai-python

> The official Python SDK; two arguments point it at our endpoint.

## Use cases

Good for calling models from your own Python services. The official SDK needs only base_url and api_key changed, and existing code mostly stays the same.

## Tips

Read the key from a server-side environment variable; never commit it or ship it in frontend bundles.

## If it cannot connect

1. Use `https://modelportal.ai/v1` as the API host, without `/chat/completions`.
2. The key starts with `mp-` (older keys: `key_`) and is not paused or revoked; `invalid_api_key` means the key cannot be used.
3. The model ID matches the [catalog](/catalog) and is in the key's allowed models.
4. `insufficient_balance` means the balance is too low; see [common errors](/docs/errors?lang=en) for more.

## Setup

1. Install the dependency: pip install openai.
2. Point base_url at the API host below and pass your own key.
3. Everything else matches the official SDK.

## Settings

- API host：`https://modelportal.ai/v1`
- API key：`YOUR_API_KEY`
- Model：`MODEL_ID`

```python
from openai import OpenAI

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://modelportal.ai/v1",
)
resp = client.chat.completions.create(
    model="MODEL_ID",
    messages=[{"role": "user", "content": "你好"}],
)
print(resp.choices[0].message.content)
```

## FAQ

### Does it support streaming?

Yes. Pass stream=True and iterate over the chunks as the SDK documents.

### How do I handle errors?

The SDK raises exceptions carrying the HTTP status and error code; see common errors. 429 and 503 can be retried with backoff.

