# Python

> Usa Jeimy desde Python con el SDK oficial de OpenAI.

Jeimy es compatible con el formato de OpenAI, así que se usa con su SDK oficial cambiando la URL base.

```bash
pip install openai
```

```python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["JEIMY_API_KEY"],
    base_url="https://api.jeimy.ai/v1",
)
```

## Una respuesta

```python
r = client.chat.completions.create(
    model="colibri",
    messages=[
        {"role": "system", "content": "Responde en español de Perú, breve."},
        {"role": "user", "content": "¿Qué es un RUC?"},
    ],
)
print(r.choices[0].message.content)
print(r.usage.total_tokens, "tokens")
```

## Streaming

```python
stream = client.chat.completions.create(
    model="colibri",
    messages=[{"role": "user", "content": "Escribe un poema corto sobre Lima"}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
```

## Una conversación

```python
historial = [{"role": "system", "content": "Eres un tutor de matemáticas."}]

while True:
    pregunta = input("Tú: ")
    historial.append({"role": "user", "content": pregunta})
    r = client.chat.completions.create(model="aguila", messages=historial)
    texto = r.choices[0].message.content
    historial.append({"role": "assistant", "content": texto})
    print("Jeimy:", texto)
```

## Errores

```python
from openai import APIStatusError

try:
    r = client.chat.completions.create(model="colibri", messages=[{"role": "user", "content": "Hola"}])
except APIStatusError as e:
    print(e.status_code, e.response.json()["error"]["code"])
```

Ver [Errores](https://docs.jeimy.ai/api/errores/) para la lista de códigos.
