Metadata-Version: 2.4
Name: matrixllm
Version: 0.1.1
Summary: MatrixLLM: OpenAI-compatible multi-provider LLM router (OpenRouter-style) with optional relay nodes
Project-URL: Homepage, https://github.com/agent-matrix/matrix-llm
Project-URL: Documentation, https://github.com/agent-matrix/matrix-llm#readme
Project-URL: Repository, https://github.com/agent-matrix/matrix-llm
Project-URL: Issues, https://github.com/agent-matrix/matrix-llm/issues
Project-URL: Changelog, https://github.com/agent-matrix/matrix-llm/releases
Author-email: Ruslan Magana Vsevolodovna <contact@ruslanmv.com>
Maintainer-email: Ruslan Magana Vsevolodovna <contact@ruslanmv.com>
License: 
                                         Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
Keywords: ai,anthropic,api,chatgpt,deepseek,embeddings,gateway,gemini,langchain,llama,llm,machine-learning,multi-provider,ollama,openai,openrouter,router,self-hosted,watsonx
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: anyio
Requires-Dist: fastapi>=0.110
Requires-Dist: httpx>=0.26
Requires-Dist: itsdangerous>=2.1
Requires-Dist: pydantic-settings>=2.2
Requires-Dist: pydantic>=2.6
Requires-Dist: python-dotenv>=1.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: rich>=13.7
Requires-Dist: slowapi
Requires-Dist: sqlalchemy
Requires-Dist: sqlmodel
Requires-Dist: tenacity>=8.2
Requires-Dist: typer>=0.12
Requires-Dist: uvicorn[standard]>=0.27
Requires-Dist: websockets>=12.0
Provides-Extra: dev
Requires-Dist: black>=23.7; extra == 'dev'
Requires-Dist: mypy>=1.4; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
Requires-Dist: pytest-cov>=4.1; extra == 'dev'
Requires-Dist: pytest>=7.4; extra == 'dev'
Requires-Dist: ruff>=0.0.280; extra == 'dev'
Provides-Extra: notebook
Requires-Dist: ipykernel>=7.1.0; extra == 'notebook'
Requires-Dist: nbclient>=0.10.0; extra == 'notebook'
Requires-Dist: nbconvert>=7.0.0; extra == 'notebook'
Requires-Dist: openai>=1.14.0; extra == 'notebook'
Requires-Dist: python-dotenv>=1.0.1; extra == 'notebook'
Requires-Dist: requests>=2.32.0; extra == 'notebook'
Description-Content-Type: text/markdown

<div align="center">

<img src="assets/logo.svg" alt="MatrixLLM Logo" width="500"/>

# MatrixLLM

**OpenAI-compatible multi-provider LLM router with optional relay nodes.**

[![PyPI version](https://badge.fury.io/py/matrixllm.svg)](https://badge.fury.io/py/matrixllm)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-yellow.svg)](https://opensource.org/licenses/Apache-2.0)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

[Quick Start](#-quick-start-for-beginners) | [How It Works](#-how-it-works) | [Multi-Provider Routing](#-multi-provider-routing) | [OllaBridge Compatible](#-ollabridge-compatibility)

</div>

---

## What is MatrixLLM?

**MatrixLLM turns your computer into a private OpenAI-compatible API server.**

Instead of sending your data to OpenAI, you can:
- Run AI models **locally** on your own computer
- Connect to **multiple providers** (OpenAI, Anthropic, Google, IBM) through one API
- Use the **same code** you'd use with OpenAI

```
Your App (uses OpenAI SDK)
         |
         v
+------------------+
|    MatrixLLM     |  <-- Runs on localhost:11435
+------------------+
    /     |     \
   v      v      v
Ollama  OpenAI  Anthropic  (etc.)
(local) (cloud) (cloud)
```

---

## Quick Start for Beginners

### What You Need

- **Python 3.10 or newer** ([Download Python](https://www.python.org/downloads/))
- **5 minutes** of your time

### Step 1: Install MatrixLLM

Open your terminal (Command Prompt on Windows, Terminal on Mac/Linux) and run:

```bash
pip install matrixllm
```

### Step 2: Start the Server

```bash
matrixllm start
```

**That's it!** You'll see something like this:

```
╭─────────────────── Gateway Ready ───────────────────╮
│                                                      │
│ ✅ MatrixLLM is Online                              │
│                                                      │
│ Model:        deepseek-r1                           │
│ Local API:    http://localhost:11435/v1             │
│ Health:       http://localhost:11435/health         │
│ Key:          sk-matrixllm-xY9kL2mN8pQ4rT6v        │
│                                                      │
│ Ollabridge compatible:                              │
│   OLLAS_BASE_URL=http://localhost:11435/v1          │
│   OLLAS_API_KEY=sk-matrixllm-xY9kL2mN8pQ4rT6v      │
│   OLLAS_MODEL=deepseek-r1                           │
│                                                      │
╰──────────────────────────────────────────────────────╯
```

**Important:** Copy the API key shown (starts with `sk-matrixllm-`). You'll need it!

### Step 3: Use It in Your Code

```python
from openai import OpenAI

# Connect to your local MatrixLLM server
client = OpenAI(
    base_url="http://localhost:11435/v1",
    api_key="sk-matrixllm-YOUR-KEY-HERE"  # Use the key from Step 2
)

# Send a message to the AI
response = client.chat.completions.create(
    model="deepseek-r1",
    messages=[{"role": "user", "content": "Hello! What can you do?"}]
)

# Print the AI's response
print(response.choices[0].message.content)
```

### Step 4: Test with curl (Optional)

You can also test from the command line:

```bash
curl http://localhost:11435/v1/chat/completions \
  -H "Authorization: Bearer sk-matrixllm-YOUR-KEY-HERE" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-r1",
    "messages": [{"role": "user", "content": "Hello!"}]
  }'
```

---

## How It Works

### API Keys Explained

When you run `matrixllm start`, it automatically generates a secure API key:

```
sk-matrixllm-xY9kL2mN8pQ4rT6vW1zA...
```

**What does this mean?**
- `sk-` = "secret key" (standard prefix)
- `matrixllm-` = identifies this as a MatrixLLM key
- `xY9kL2mN...` = random secure characters

**You can set your own key** by creating a `.env` file:

```env
API_KEYS=my-custom-api-key
```

Or use multiple keys (comma-separated):

```env
API_KEYS=key-for-app-1,key-for-app-2,key-for-testing
```

### Authentication Methods

MatrixLLM accepts API keys in two ways:

```python
# Method 1: Authorization header (recommended)
headers = {"Authorization": "Bearer sk-matrixllm-xxx"}

# Method 2: X-API-Key header
headers = {"X-API-Key": "sk-matrixllm-xxx"}
```

Both work identically. The OpenAI SDK uses Method 1 automatically.

### Authentication Modes

MatrixLLM supports three authentication modes for different use cases:

| Mode | Flag | Description |
|------|------|-------------|
| `required` | `--auth required` | **Default.** API key required for all requests |
| `local-trust` | `--auth local-trust` | Localhost requests allowed without key; remote requires key |
| `pairing` | `--auth pairing` | For MatrixShell integration; uses short-lived pairing codes |

**Examples:**

```bash
# Default mode (API key required)
matrixllm start

# Trust localhost connections (no key needed from 127.0.0.1)
matrixllm start --auth local-trust

# Pairing mode for MatrixShell (displays pairing code)
matrixllm start --auth pairing --host 127.0.0.1
```

**Pairing mode** is designed for seamless local integration with [MatrixShell](https://github.com/agent-matrix/matrixshell):

```
╭─────────────────── Gateway Ready ───────────────────╮
│ ✅ MatrixLLM is Online                              │
│                                                      │
│ Auth:          pairing                              │
│ Pairing code:  483-921                              │
│ Enter this code in MatrixShell to pair.             │
╰──────────────────────────────────────────────────────╯
```

---

## OllaBridge Compatibility

MatrixLLM is **fully compatible** with [OllaBridge](https://github.com/ruslanmv/ollabridge). Both projects share the same API interface, making it easy to switch between them or migrate your applications.

### When to Use Each

| Feature | OllaBridge | MatrixLLM |
|---------|------------|-----------|
| **Use Case** | Simple local-only proxy | Multi-provider enterprise router |
| **Ollama Support** | Local only | Local + distributed nodes |
| **Cloud Providers** | No | OpenAI, Anthropic, Google, IBM |
| **Distributed Compute** | No | Yes (relay nodes) |
| **Complexity** | Minimal | Full-featured |

**Choose OllaBridge when:**
- You only need local Ollama models
- You want a lightweight, simple setup
- You don't need cloud provider integration

**Choose MatrixLLM when:**
- You need multi-provider routing (OpenAI, Anthropic, Google, IBM)
- You want distributed compute across multiple machines
- You need enterprise features like load balancing and failover

### Shared Configuration

Both projects use the same:
- Port: `11435`
- API structure: `/v1/chat/completions`, `/v1/embeddings`, `/v1/models`
- Environment variables: `API_KEYS`, `OLLAMA_BASE_URL`, `DEFAULT_MODEL`

### Using OLLAS_* Environment Variables

MatrixLLM supports OllaBridge-style environment variables for seamless migration:

| Variable | Description | Example |
|----------|-------------|---------|
| `OLLAS_API_KEY` | API key (alias for `API_KEYS`) | `sk-matrixllm-xxx` |
| `OLLAS_BASE_URL` | Server URL | `http://localhost:11435/v1` |
| `OLLAS_MODEL` | Default model (alias for `DEFAULT_MODEL`) | `deepseek-r1` |

**Example `.env` file:**

```env
# OllaBridge-compatible configuration
OLLAS_API_KEY=sk-matrixllm-your-key-here
OLLAS_BASE_URL=http://localhost:11435/v1
OLLAS_MODEL=deepseek-r1
```

**Example Python code:**

```python
import os
from openai import OpenAI

# Works with both MatrixLLM and OllaBridge
client = OpenAI(
    base_url=os.getenv("OLLAS_BASE_URL", "http://localhost:11435/v1"),
    api_key=os.getenv("OLLAS_API_KEY", "your-key-here"),
)

response = client.chat.completions.create(
    model=os.getenv("OLLAS_MODEL", "deepseek-r1"),
    messages=[{"role": "user", "content": "Hello!"}]
)
```

### Migration Path

Switch between OllaBridge and MatrixLLM without changing your application code:

```bash
# Start with OllaBridge (simple local setup)
pip install ollabridge
ollabridge start

# Upgrade to MatrixLLM (when you need more features)
pip install matrixllm
matrixllm start
```

Your application code stays exactly the same!

---

## Multi-Provider Routing

MatrixLLM can route requests to different AI providers based on the model name.

### Supported Providers

| Provider | Model Prefix | Example |
|----------|--------------|---------|
| Local Ollama | (no prefix) | `deepseek-r1`, `llama3` |
| OpenAI | `openai/` | `openai/gpt-4o-mini` |
| Anthropic | `anthropic/` | `anthropic/claude-3-5-sonnet-latest` |
| Google Gemini | `google/` | `google/gemini-1.5-pro` |
| IBM watsonx | `ibm/` | `ibm/granite-3-8b-instruct` |

### Setup Multi-Provider

Create a `.env` file with your API keys:

```env
# Your MatrixLLM API key
API_KEYS=my-secure-key

# OpenAI (optional)
OPENAI_COMPAT_BASE_URL=https://api.openai.com/v1
OPENAI_COMPAT_API_KEY=sk-...

# Anthropic (optional)
ANTHROPIC_API_KEY=sk-ant-...

# Google Gemini (optional)
GEMINI_API_KEY=AIza...

# IBM watsonx (optional)
WATSONX_BASE_URL=https://us-south.ml.cloud.ibm.com
WATSONX_API_KEY=...
WATSONX_PROJECT_ID=...
```

### Use Different Providers

```python
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:11435/v1",
    api_key="my-secure-key"
)

# Use local Ollama (default)
response = client.chat.completions.create(
    model="deepseek-r1",
    messages=[{"role": "user", "content": "Hello!"}]
)

# Use OpenAI
response = client.chat.completions.create(
    model="openai/gpt-4o-mini",
    messages=[{"role": "user", "content": "Hello!"}]
)

# Use Anthropic Claude
response = client.chat.completions.create(
    model="anthropic/claude-3-5-sonnet-latest",
    messages=[{"role": "user", "content": "Hello!"}]
)

# Use Google Gemini
response = client.chat.completions.create(
    model="google/gemini-1.5-pro",
    messages=[{"role": "user", "content": "Hello!"}]
)
```

---

## Distributed Compute (Relay Nodes)

Add GPUs from anywhere without port forwarding. Nodes **dial out** to your gateway.

### On Your Gateway (Control Plane)

```bash
matrixllm start
# Note the enrollment token shown
```

### On Remote GPU/Machine (Node)

```bash
pip install matrixllm

matrixllm-node join \
  --control http://YOUR_GATEWAY_IP:11435 \
  --token YOUR_ENROLLMENT_TOKEN
```

### Use Cases

- **Gaming PC at home**: Join your gateway from anywhere
- **Free Colab/Kaggle GPUs**: No port forwarding needed
- **Cloud instances**: Auto load balancing across nodes

---

## API Reference

### Endpoints

| Endpoint | Method | Auth Required | Description |
|----------|--------|---------------|-------------|
| `/health` | GET | No | Check if server is running |
| `/v1/models` | GET | Yes | List available models |
| `/v1/chat/completions` | POST | Yes | Generate chat responses |
| `/v1/embeddings` | POST | Yes | Generate text embeddings |
| `/pair/info` | GET | No* | Get pairing status (pairing mode only) |
| `/pair` | POST | No* | Submit pairing code for token (pairing mode only) |

*Pairing endpoints are only available in `--auth pairing` mode and restricted to localhost by default.

### Quick Examples

```bash
# Check health (no auth needed)
curl http://localhost:11435/health

# List models
curl -H "Authorization: Bearer YOUR-KEY" \
  http://localhost:11435/v1/models

# Chat completion
curl -X POST http://localhost:11435/v1/chat/completions \
  -H "Authorization: Bearer YOUR-KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "deepseek-r1", "messages": [{"role": "user", "content": "Hi!"}]}'
```

---

## CLI Commands

```bash
# Start the server
matrixllm start

# Start with options
matrixllm start --port 8080 --model llama3

# Start with different auth modes
matrixllm start --auth local-trust    # Trust localhost
matrixllm start --auth pairing        # Pairing mode for MatrixShell

# Show LAN URLs (for other devices on your network)
matrixllm start --lan

# Create public URL (via ngrok)
matrixllm start --share

# Check system health
matrixllm doctor

# List available models
matrixllm models --api-key YOUR-KEY

# Test chat
matrixllm test-chat "Hello!" --api-key YOUR-KEY
```

---

## Configuration Reference

### All Environment Variables

```env
# === Server ===
PORT=11435                    # Server port
HOST=0.0.0.0                  # Bind address
CORS_ORIGINS=http://localhost:5173,http://localhost:3000

# === Authentication ===
API_KEYS=dev-key-change-me    # Comma-separated API keys
AUTH_MODE=required            # required | local-trust | pairing

# === Pairing (for MatrixShell) ===
PAIRING_CODE_TTL_SECONDS=120  # Pairing code expiry time
PAIRING_LOCAL_ONLY=true       # Only allow pairing from localhost

# === Rate Limiting ===
RATE_LIMIT=60/minute          # Requests per minute

# === Local Ollama ===
OLLAMA_BASE_URL=http://localhost:11434
DEFAULT_MODEL=deepseek-r1
DEFAULT_EMBED_MODEL=nomic-embed-text

# === Routing ===
ROUTING_MODE=prefix           # prefix | fallback

# === Multi-Provider (Optional) ===
OPENAI_COMPAT_BASE_URL=https://api.openai.com/v1
OPENAI_COMPAT_API_KEY=

ANTHROPIC_API_KEY=

GEMINI_API_KEY=

WATSONX_BASE_URL=https://us-south.ml.cloud.ibm.com
WATSONX_API_KEY=
WATSONX_PROJECT_ID=

# === Relay Fabric ===
RELAY_ENABLED=true
ENROLLMENT_SECRET=dev-enroll-change-me
LOCAL_RUNTIME_ENABLED=true

# === OllaBridge Compatibility ===
# OLLAS_API_KEY=              # Alias for API_KEYS
# OLLAS_BASE_URL=             # Client base URL
# OLLAS_MODEL=                # Alias for DEFAULT_MODEL
```

---

## Troubleshooting

### "Connection refused" error

Make sure the server is running:
```bash
matrixllm start
```

### "Invalid API key" error

Check that you're using the correct key:
```bash
# The key is shown when you start the server
matrixllm start
# Look for: Key: sk-matrixllm-xxxxx
```

### "Model not found" error

1. Check available models:
   ```bash
   curl -H "Authorization: Bearer YOUR-KEY" http://localhost:11435/v1/models
   ```

2. For local models, make sure Ollama is running:
   ```bash
   ollama list
   ```

### Server won't start

Check if another service is using port 11435:
```bash
# Use a different port
matrixllm start --port 8080
```

---

## Development

```bash
# Install with dev dependencies
pip install -e ".[dev]"

# Run tests
make test

# Format code
make format

# Type check
make typecheck
```

---

## License

Apache License 2.0 - see [LICENSE](LICENSE)

---

## Built With

- [FastAPI](https://fastapi.tiangolo.com/) - Async web framework
- [httpx](https://www.python-httpx.org/) - Async HTTP client
- [Ollama](https://ollama.com/) - Local LLM runtime
- [Pydantic](https://pydantic.dev/) - Data validation

---

<div align="center">

**MatrixLLM - Your unified gateway to all LLM providers**

[Report Bug](https://github.com/agent-matrix/matrix-llm/issues) | [Request Feature](https://github.com/agent-matrix/matrix-llm/issues)

</div>
