Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .env.template
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,13 @@ SANDBOX=local # code execution backend: 'local' (default) or 'docke
# CHEAPERINFERENCE_API_BASE=https://api.cheaperinference.com/v1
# CHEAPERINFERENCE_MODELS=gpt-5.4-mini # comma separated list of models; use e.g. "gpt-5.4-mini" or "claude-sonnet-5"

# API Route (third-party OpenAI-compatible API service)
# Model IDs are passed through unchanged; choose a model available to your account.
# See: https://www.api-route.com/docs
# API_ROUTE_API_KEY=<your-api-route-api-key>
# API_ROUTE_API_BASE=https://global.api-route.com/v1
# API_ROUTE_MODELS=gpt-5.5 # comma separated list of models

# Add other LiteLLM-supported providers with PROVIDER_API_KEY, PROVIDER_MODELS, etc.
# (optionally PROVIDER_API_BASE and PROVIDER_ENDPOINT, which defaults to openai).

Expand All @@ -107,7 +114,7 @@ SANDBOX=local # code execution backend: 'local' (default) or 'docke
#
# Glob patterns use fnmatch syntax (* matches anything, case-insensitive).
# Empty api_base (provider defaults like OpenAI/Anthropic) is always allowed,
# except for third-party gateways (OpenRouter, OrcaRouter, Cheaper Inference),
# except for third-party gateways (OpenRouter, OrcaRouter, Cheaper Inference, API Route),
# whose default base URL must match a pattern.
# Global models (configured above via env vars) bypass this check.
#
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ Here are milestones that lead to the current design:
- **v0.2** ([Demos](https://github.com/microsoft/data-formulator/releases/tag/0.2)): Large data support with DuckDB integration
- **v0.1.7** ([Demos](https://github.com/microsoft/data-formulator/releases/tag/0.1.7)): Dataset anchoring for cleaner workflows
- **v0.1.6** ([Demo](https://github.com/microsoft/data-formulator/releases/tag/0.1.6)): Multi-table support with automatic joins
- **Model Support**: OpenAI, Azure, Ollama, Anthropic, [OrcaRouter](https://www.orcarouter.ai), [Cheaper Inference](https://cheaperinference.com) via [LiteLLM](https://github.com/BerriAI/litellm) ([feedback](https://github.com/microsoft/data-formulator/issues/49))
- **Model Support**: OpenAI, Azure, Ollama, Anthropic, [OrcaRouter](https://www.orcarouter.ai), [Cheaper Inference](https://cheaperinference.com), [API Route](https://www.api-route.com) via [LiteLLM](https://github.com/BerriAI/litellm) ([feedback](https://github.com/microsoft/data-formulator/issues/49))
- **Python Package**: Easy local installation ([try it](#get-started))
- **Visualization Challenges**: Test your skills ([challenges](https://github.com/microsoft/data-formulator/issues/53))
- **Data Extraction**: Parse data from images and text ([demo](https://github.com/microsoft/data-formulator/pull/31#issuecomment-2403652717))
Expand Down
5 changes: 5 additions & 0 deletions py-src/data_formulator/agents/client_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"openrouter": "https://openrouter.ai/api/v1",
"orcarouter": "https://api.orcarouter.ai/v1",
"cheaperinference": "https://api.cheaperinference.com/v1",
"api_route": "https://global.api-route.com/v1",
}


Expand Down Expand Up @@ -337,6 +338,10 @@ def __init__(self, endpoint, model, api_key=None, api_base=None, api_version=No
# the Cheaper Inference base URL.
self.params["api_base"] = effective_api_base(endpoint, api_base).rstrip("/")
self.params["custom_llm_provider"] = "openai"
elif self.endpoint == "api_route":
# API Route accepts bare OpenAI-compatible model IDs.
self.params["api_base"] = effective_api_base(endpoint, api_base).rstrip("/")
self.params["custom_llm_provider"] = "openai"

def _strip_image_blocks(self, content):
"""Remove image_url blocks from multimodal content arrays."""
Expand Down
4 changes: 2 additions & 2 deletions py-src/data_formulator/model_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@
import os
from typing import Optional, Dict, List

BUILTIN_PROVIDERS = {'openai', 'azure', 'anthropic', 'gemini', 'ollama', 'orcarouter', 'cheaperinference'}
BUILTIN_PROVIDERS = {'openai', 'azure', 'anthropic', 'gemini', 'ollama', 'orcarouter', 'cheaperinference', 'api_route'}


class ModelRegistry:
"""
Load global model configurations from environment variables.

Supports both built-in providers (openai / azure / anthropic / gemini /
ollama / orcarouter / cheaperinference) and arbitrary custom providers
ollama / orcarouter / cheaperinference / api_route) and arbitrary custom providers
(e.g. DEEPSEEK, QWEN).

A provider is enabled when {PROVIDER}_MODELS is set together with
Expand Down
2 changes: 1 addition & 1 deletion py-src/data_formulator/routes/configurations.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ def test_connection():
raise ValueError('Model provider cannot change during editing.')
if not definition.get('api_key') and definition.get('auth_mode') not in ('azure_identity', 'managed_identity'):
definition['api_key'] = previous_definition.get('api_key', '')
if definition.get('endpoint') not in ('openai', 'azure', 'anthropic', 'gemini', 'ollama', 'orcarouter', 'cheaperinference') or not definition.get('model', '').strip():
if definition.get('endpoint') not in ('openai', 'azure', 'anthropic', 'gemini', 'ollama', 'orcarouter', 'cheaperinference', 'api_route') or not definition.get('model', '').strip():
raise ValueError('Select an API provider and model.')
if definition.get('auth_mode') not in (None, 'key', 'azure_identity', 'managed_identity'):
raise ValueError('Interactive model authentication is not supported here.')
Expand Down
7 changes: 5 additions & 2 deletions src/views/ModelSelectionDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ const PROVIDERS: Record<string, { label: string; model: string; base: string; co
chatgpt: { label: 'ChatGPT', model: '', base: '', connectionMethod: 'account' },
orcarouter: { label: 'OrcaRouter', model: 'auto', base: 'https://api.orcarouter.ai/v1', connectionMethod: 'api' },
cheaperinference: { label: 'Cheaper Inference', model: 'gpt-5.4-mini', base: 'https://api.cheaperinference.com/v1', connectionMethod: 'api' },
api_route: { label: 'API Route', model: 'gpt-5.5', base: 'https://global.api-route.com/v1', connectionMethod: 'api' },
};

const connectionRequest = (provider: string, action: string, body: object = {}) => apiRequest(
Expand Down Expand Up @@ -189,7 +190,8 @@ export const ModelSelectionButton: React.FC<ModelSelectionButtonProps> = ({ appe
'gemini': [],
'ollama': [],
'orcarouter': [],
'cheaperinference': []
'cheaperinference': [],
'api_route': []
});
const serverConfig = useSelector((state: DataFormulatorState) => state.serverConfig);

Expand Down Expand Up @@ -568,7 +570,8 @@ export const ModelSelectionButton: React.FC<ModelSelectionButtonProps> = ({ appe
'gemini': [],
'ollama': [],
'orcarouter': [],
'cheaperinference': []
'cheaperinference': [],
'api_route': []
};

globalModels.forEach((modelConfig: any) => {
Expand Down
13 changes: 13 additions & 0 deletions tests/backend/agents/test_client_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,19 @@ def test_model_id_kept_bare(self):
assert c.model == "claude-sonnet-5"


class TestApiRoute:
def test_uses_openai_compatible_api_with_bare_model_id(self):
client = Client("api_route", "gpt-5.5", api_key="k")
assert client.model == "gpt-5.5"
assert client.params["api_base"] == "https://global.api-route.com/v1"
assert client.params["custom_llm_provider"] == "openai"

def test_custom_base_url_strips_trailing_slash(self):
client = Client("api_route", "gpt-5.5", api_key="k",
api_base="https://global.api-route.com/v1/")
assert client.params["api_base"] == "https://global.api-route.com/v1"


# ---------------------------------------------------------------------------
# Ollama api_base normalisation
# ---------------------------------------------------------------------------
Expand Down
28 changes: 21 additions & 7 deletions tests/backend/agents/test_model_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,16 @@ def _make_env(providers: dict[str, dict[str, str]]) -> dict[str, str]:
"api_base": "https://api.orcarouter.ai/v1",
"models": "auto",
},
"cheaperinference": {
"cheaperinference": {
"api_key": "sk-ci-secret-key",
"api_base": "https://api.cheaperinference.com/v1",
"models": "gpt-5.4-mini",
},
"models": "gpt-5.4-mini",
},
"api_route": {
"api_key": "sk-api-route-secret-key",
"api_base": "https://global.api-route.com/v1",
"models": "gpt-5.5",
},
})


Expand All @@ -76,12 +81,13 @@ def test_discovers_all_enabled_providers(self):
assert "global-ollama-qwen3:32b" in ids
assert "global-deepseek-deepseek-chat" in ids
assert "global-orcarouter-auto" in ids
assert "global-cheaperinference-gpt-5.4-mini" in ids
assert "global-cheaperinference-gpt-5.4-mini" in ids
assert "global-api_route-gpt-5.5" in ids

@patch.dict(os.environ, SAMPLE_ENV, clear=True)
def test_total_model_count(self):
registry = ModelRegistry()
assert len(registry.list_public()) == 6 # 2 openai + 1 ollama + 1 deepseek + 1 orcarouter + 1 cheaperinference
assert len(registry.list_public()) == 7

@patch.dict(os.environ, {}, clear=True)
def test_empty_env_yields_no_models(self):
Expand Down Expand Up @@ -166,13 +172,21 @@ def test_orcarouter_builtin_uses_own_name_as_endpoint(self):
assert config["api_base"] == "https://api.orcarouter.ai/v1"

@patch.dict(os.environ, SAMPLE_ENV, clear=True)
def test_cheaperinference_builtin_uses_own_name_as_endpoint(self):
def test_cheaperinference_builtin_uses_own_name_as_endpoint(self):
"""cheaperinference is in BUILTIN_PROVIDERS, so it uses itself as endpoint."""
registry = ModelRegistry()
config = registry.get_config("global-cheaperinference-gpt-5.4-mini")
assert config is not None
assert config["endpoint"] == "cheaperinference"
assert config["api_base"] == "https://api.cheaperinference.com/v1"
assert config["api_base"] == "https://api.cheaperinference.com/v1"

@patch.dict(os.environ, SAMPLE_ENV, clear=True)
def test_api_route_builtin_uses_own_name_as_endpoint(self):
registry = ModelRegistry()
config = registry.get_config("global-api_route-gpt-5.5")
assert config is not None
assert config["endpoint"] == "api_route"
assert config["api_base"] == "https://global.api-route.com/v1"

@patch.dict(os.environ, {
"MYVENDOR_API_KEY": "key123",
Expand Down
23 changes: 12 additions & 11 deletions tests/backend/security/test_global_model_security.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ def test_user_model_api_base_is_still_validated(self):

assert exc.value.get_http_status() == 403

@pytest.mark.parametrize("endpoint", ["orcarouter", "cheaperinference"])
@pytest.mark.parametrize("endpoint", ["orcarouter", "cheaperinference", "api_route"])
@patch.dict(
os.environ,
{**SAMPLE_ENV, "DF_ALLOWED_API_BASES": "https://api.openai.com/*"},
Expand All @@ -198,16 +198,17 @@ def test_blank_gateway_base_is_validated_as_its_default(self, endpoint):
get_client({"endpoint": endpoint, "model": "m", "api_key": "k", "api_base": ""})
assert exc.value.get_http_status() == 403

@patch.dict(
os.environ,
{**SAMPLE_ENV, "DF_ALLOWED_API_BASES": "https://api.cheaperinference.com/*"},
clear=True,
)
def test_blank_gateway_base_allowed_when_default_is_listed(self):
from data_formulator.routes.agents import get_client

client = get_client({"endpoint": "cheaperinference", "model": "m", "api_key": "k"})
assert client.params["api_base"] == "https://api.cheaperinference.com/v1"
@pytest.mark.parametrize("endpoint,base", [
("cheaperinference", "https://api.cheaperinference.com/v1"),
("api_route", "https://global.api-route.com/v1"),
])
@patch.dict(os.environ, SAMPLE_ENV, clear=True)
def test_blank_gateway_base_allowed_when_default_is_listed(self, endpoint, base):
from data_formulator.routes.agents import get_client

os.environ["DF_ALLOWED_API_BASES"] = base + "*"
client = get_client({"endpoint": endpoint, "model": "m", "api_key": "k"})
assert client.params["api_base"] == base

@patch.dict(
os.environ,
Expand Down
22 changes: 18 additions & 4 deletions tests/frontend/unit/views/ModelSelectionDialog.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -172,10 +172,10 @@ describe('Model connection form', () => {
fireEvent.mouseDown(screen.getByRole('combobox', { name: 'Provider' }));
const listbox = await screen.findByRole('listbox');
expect(Array.from(listbox.children).map(child => child.textContent)).toEqual([
'Sign in', 'OpenRouter', 'GitHub Copilot', 'ChatGPT', 'API', 'OpenAI', 'Azure', 'Anthropic', 'Google Gemini', 'Ollama', 'OrcaRouter', 'Cheaper Inference',
'Sign in', 'OpenRouter', 'GitHub Copilot', 'ChatGPT', 'API', 'OpenAI', 'Azure', 'Anthropic', 'Google Gemini', 'Ollama', 'OrcaRouter', 'Cheaper Inference', 'API Route',
]);
expect(screen.getAllByRole('option').map(option => option.textContent)).toEqual([
'OpenRouter', 'GitHub Copilot', 'ChatGPT', 'OpenAI', 'Azure', 'Anthropic', 'Google Gemini', 'Ollama', 'OrcaRouter', 'Cheaper Inference',
'OpenRouter', 'GitHub Copilot', 'ChatGPT', 'OpenAI', 'Azure', 'Anthropic', 'Google Gemini', 'Ollama', 'OrcaRouter', 'Cheaper Inference', 'API Route',
]);
const openRouter = screen.getByRole('option', { name: 'OpenRouter' });
act(() => openRouter.focus());
Expand Down Expand Up @@ -561,7 +561,7 @@ describe('Model connection form', () => {
expect(screen.queryByRole('button', { name: 'Use recent' })).not.toBeInTheDocument();
});

it.each(['OpenAI', 'Anthropic', 'Google Gemini', 'Azure', 'Ollama', 'OrcaRouter', 'Cheaper Inference'])(
it.each(['OpenAI', 'Anthropic', 'Google Gemini', 'Azure', 'Ollama', 'OrcaRouter', 'Cheaper Inference', 'API Route'])(
'%s does not treat a suggested model as a selected model', async provider => {
openForm();
await chooseProvider(provider);
Expand Down Expand Up @@ -686,7 +686,7 @@ describe('Model connection form', () => {
expect(store.getState().models[0]).toMatchObject({ endpoint: 'ollama', model: 'llama3.2', api_key: '', api_base: '' });
});

it.each(['OpenAI', 'Anthropic', 'Google Gemini', 'OrcaRouter', 'Cheaper Inference'])('%s keeps optional URL overrides under Advanced', async provider => {
it.each(['OpenAI', 'Anthropic', 'Google Gemini', 'OrcaRouter', 'Cheaper Inference', 'API Route'])('%s keeps optional URL overrides under Advanced', async provider => {
openForm();
await chooseProvider(provider);
expect(screen.getByLabelText('Base URL')).not.toBeVisible();
Expand All @@ -695,6 +695,20 @@ describe('Model connection form', () => {
expect(await screen.findByRole('textbox', { name: 'Base URL' })).toBeVisible();
});

it('offers the API Route URL and saves a model with its own provider ID', async () => {
const store = openForm();
await chooseProvider('API Route');
expect(screen.getByRole('textbox', { name: /^Model/ })).toHaveAttribute('placeholder', 'gpt-5.5');
fireEvent.click(screen.getByRole('button', { name: 'Advanced settings' }));
expect(screen.getByRole('textbox', { name: 'Base URL' })).toHaveAttribute('placeholder', 'https://global.api-route.com/v1');
fireEvent.change(screen.getByRole('textbox', { name: /^Model/ }), { target: { value: 'gpt-5.5' } });
fireEvent.change(screen.getByLabelText('API Key'), { target: { value: 'test-key' } });
fireEvent.click(screen.getByRole('button', { name: 'Test and save' }));
await waitFor(() => expect(store.getState().models[0]).toMatchObject({
endpoint: 'api_route', model: 'gpt-5.5', api_base: '', api_key: 'test-key',
}));
});

it('clears credentials and incompatible values when switching providers', async () => {
openForm();
await chooseProvider('OpenAI');
Expand Down