> ## Documentation Index
> Fetch the complete documentation index at: https://docs.muffinscorp.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Biblioteca Python

> Integre a Muffins AI em seus projetos Python com exemplos práticos e configurações detalhadas.

## Visão Geral

A biblioteca Python oficial da Muffins AI oferece integração simplificada com todos os recursos da plataforma. Compatível com Python 3.8+.

## Pré-requisitos

<Info>
  Python 3.8+ e pip atualizado
</Info>

1. **Conta Muffins AI**: [Crie uma conta](https://platform.muffinscorp.com/auth/sign-up)
2. **Chave de API**: Obtenha em [Painel de API](https://platform.muffinscorp.com/dashboard/api-keys)
3. **Ambiente virtual** (recomendado): [Guia de instalação](https://docs.python.org/3/tutorial/venv.html)

***

## Instalação

### Via pip

```bash theme={null}
pip install muffinscorp
# ou para instalação específica
pip install muffinscorp==1.0.3
```

***

## Configuração Inicial

### 1. Autenticação

```python theme={null}
from muffinscorp import MuffinsCorp

# Inicialização básica
client = MuffinsCorp(
    api_key="sua_chave_api",  # Recomendado usar variáveis de ambiente
    # base_url="<string>"  # Opcional para domínios personalizados
)
```

### 2. Variáveis de Ambiente

Crie um arquivo `.env`:

```env theme={null}
MUFFINS_AI_API_KEY=your_api_key_here
```

E carregue com python-dotenv:

```python theme={null}
from dotenv import load_dotenv
import os

load_dotenv()
client = MuffinsCorp(api_key=os.getenv("MUFFINS_AI_API_KEY"))
```

***

## Uso Básico

### Chat Completion

```python theme={null}
async def get_chat_response():
    try:
        response = await client.chat.create(
            model="chat-model-small",
            messages=[
                {"role": "system", "content": "You are a helpful assistant"},
                {"role": "user", "content": "Explain quantum computing"}
            ],
            temperature=0.7,
            max_tokens=500
        )
        print(response)
    except Exception as e:
        print(f"Error: {e}")

# Para executar
import asyncio
asyncio.run(get_chat_response())
```

### Streaming

```python theme={null}
async def stream_response():
    stream = await client.chat.create(
        model="chat-model-small",
        messages=[...],
        stream=True
    )
    
    async for chunk in stream:
        print(chunk.choices[0].delta.get("content", ""), end="")

asyncio.run(stream_response())
```

***

## Recursos Avançados

### 1. Gerenciamento de Modelos

```python theme={null}
# Listar modelos disponíveis
async def list_models():
    models = await client.models.list()
    print("Available AI Models:")
    print(models)

asyncio.run(list_models())
```

### 2. Gerenciamento de Assinaturas

```python theme={null}
# Listar planos de assinatura
async def list_subscriptions():
    subscriptions = await client.subscriptions.list()
    print("Available Subscription Plans:")
    print(subscriptions)

asyncio.run(list_subscriptions())
```

### 3. Verificar créditos disponíveis

```python theme={null}
async def check_balance():
    balance = await client.credits.get_balance()
    print("Current credit balance:")
    print(balance)

asyncio.run(check_balance())
```

***

## Boas Práticas

1. **Tratamento de Erros**

```python theme={null}
try:
    response = await client.chat.create(...)
except muffinscorp.APIError as e:
    print(f"API Error [{e.status_code}]: {e.message}")
    if e.status_code == 429:
        print(f"Retry after: {e.headers.get('retry-after')}")
except Exception as e:
    print(f"Unexpected error: {e}")
```

2. **Logging**

```python theme={null}
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("muffinscorp")

# Configuração opcional para logs detalhados
client.configure_logging(logger)
```

***

## Exemplo Completo (Aplicação CLI)

```python theme={null}
import asyncio
from muffinscorp import MuffinsCorp

async def chat_cli():
    client = MuffinsCorp(api_key="your_api_key")
    
    messages = [
        {"role": "system", "content": "You are a helpful assistant"}
    ]
    
    while True:
        user_input = input("You: ")
        if user_input.lower() in ["exit", "quit"]:
            break
            
        messages.append({"role": "user", "content": user_input})
        
        print("Assistant: ", end="", flush=True)
        response = await client.chat.create(
            model="chat-model-small",
            messages=messages,
            stream=True
        )
        
        full_response = ""
        async for chunk in response:
            content = chunk.choices[0].delta.get("content", "")
            print(content, end="", flush=True)
            full_response += content
        
        messages.append({"role": "assistant", "content": full_response})
        print("\n")

asyncio.run(chat_cli())
```

***

## Troubleshooting

| Erro                  | Solução                                  |
| --------------------- | ---------------------------------------- |
| 401 Unauthorized      | Verifique sua chave de API e permissões  |
| 429 Too Many Requests | Implemente retry com backoff exponencial |
| TimeoutError          | Aumente timeout ou verifique conexão     |

Para mais ajuda, visite nosso [Centro de Suporte](mailto:ai.support@muffinscorp.com).
