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
12 changes: 10 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
# -----------------------------------------------------------------------------
# Provider selection
# -----------------------------------------------------------------------------
# Two HTTP wire formats and two CLI shell-outs are supported:
# Three HTTP wire formats and two CLI shell-outs are supported:
# responses - OpenAI Responses API (default; alias `openai` accepted)
# anthropic - Anthropic Messages API
# atlas - Atlas Cloud Chat Completions API
# codex - shells out to `codex exec` (only --model is honored)
# claude - shells out to `claude --print` (only --model is honored)
#
Expand All @@ -18,7 +19,7 @@
# Model is free-form: gpt-5.5, gpt-5.4, gpt-5.3-codex, deepseek-v4,
# claude-opus-4-7, claude-opus-4-6, etc. Semia does not validate it.

# SEMIA_LLM_PROVIDER=responses # responses | anthropic | codex | claude (alias: openai)
# SEMIA_LLM_PROVIDER=responses # responses | anthropic | atlas | codex | claude (alias: openai)
# SEMIA_LLM_MODEL=gpt-5.5
# SEMIA_LLM_TIMEOUT=600 # request timeout (seconds)
# SEMIA_LLM_MAX_RETRIES=2 # transient-error retries per provider call
Expand Down Expand Up @@ -46,6 +47,13 @@
# SEMIA_ANTHROPIC_MAX_TOKENS=16384
# SEMIA_ANTHROPIC_THINKING_BUDGET=0 # >0 enables extended thinking

# -----------------------------------------------------------------------------
# Atlas Cloud Chat Completions API
# -----------------------------------------------------------------------------
# ATLASCLOUD_API_KEY=your-key-here
# ATLASCLOUD_BASE_URL=https://api.atlascloud.ai/v1
# ATLASCLOUD_MODEL=openai/gpt-5.5

# -----------------------------------------------------------------------------
# Detector backend
# -----------------------------------------------------------------------------
Expand Down
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ All notable changes to Semia are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/).

## [Unreleased]

### Added

- Added an optional `atlas` synthesis provider using Atlas Cloud's
OpenAI-compatible Chat Completions API.

## [0.1.3] - 2026-05-27

### Fixed
Expand Down
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ stages are deterministic, no key required). If you run Semia via a host
plugin (Codex / Claude Code / OpenClaw) skip this — the host agent already
does synthesize for you.

Four providers are supported. Pick one and export its credentials:
Five providers are supported. Pick one and export its credentials:

```bash
# OpenAI Responses API — default; also works for DeepSeek / OpenRouter / vLLM
Expand All @@ -149,6 +149,11 @@ export SEMIA_LLM_PROVIDER=anthropic
export ANTHROPIC_API_KEY=sk-ant-...
# optional: export ANTHROPIC_BASE_URL=https://api.anthropic.com

# Atlas Cloud Chat Completions API
export SEMIA_LLM_PROVIDER=atlas
export ATLASCLOUD_API_KEY=your-key-here
# optional: export ATLASCLOUD_MODEL=openai/gpt-5.5

# Locally-installed Claude Code CLI (uses your Claude Code login)
export SEMIA_LLM_PROVIDER=claude

Expand Down
6 changes: 6 additions & 0 deletions packages/semia-cli/src/semia_cli/llm_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@

from .llm_config import (
DEFAULT_ANTHROPIC_BASE_URL,
DEFAULT_ATLAS_BASE_URL,
DEFAULT_MODEL,
DEFAULT_MODEL_ANTHROPIC,
DEFAULT_MODEL_ATLAS,
DEFAULT_MODEL_CLAUDE,
DEFAULT_MODEL_CODEX,
DEFAULT_MODEL_RESPONSES,
Expand All @@ -16,6 +18,7 @@
DEFAULT_RESPONSES_BASE_URL,
HTTP_PROVIDERS,
PROVIDER_ANTHROPIC,
PROVIDER_ATLAS,
PROVIDER_CLAUDE,
PROVIDER_CODEX,
PROVIDER_RESPONSES,
Expand All @@ -32,6 +35,8 @@

__all__ = [
"DEFAULT_ANTHROPIC_BASE_URL",
"DEFAULT_ATLAS_BASE_URL",
"DEFAULT_MODEL_ATLAS",
"DEFAULT_MODEL",
"DEFAULT_MODEL_ANTHROPIC",
"DEFAULT_MODEL_CLAUDE",
Expand All @@ -44,6 +49,7 @@
"LlmSynthesisConfigError",
"LlmSynthesisError",
"PROVIDER_ANTHROPIC",
"PROVIDER_ATLAS",
"PROVIDER_CLAUDE",
"PROVIDER_CODEX",
"PROVIDER_RESPONSES",
Expand Down
13 changes: 11 additions & 2 deletions packages/semia-cli/src/semia_cli/llm_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# Copyright 2026 RiemaLabs
"""Configuration shared by Semia LLM synthesis modules.

Semia routes synthesis through one of four **providers**:
Semia routes synthesis through one of five **providers**:

HTTP wire formats (use ``--base-url`` and the matching ``*_API_KEY``):

Expand All @@ -12,6 +12,8 @@
- ``anthropic`` — Anthropic Messages API
(``POST {ANTHROPIC_BASE_URL}/v1/messages``). Works against
api.anthropic.com and Anthropic-compatible relays.
- ``atlas`` — Atlas Cloud's OpenAI-compatible Chat Completions API
(``POST {ATLASCLOUD_BASE_URL}/chat/completions``).

Local CLI shell-outs (only ``--model`` is effective; auth is inherited from
the host CLI's config):
Expand Down Expand Up @@ -51,10 +53,11 @@ class LlmSynthesisConfigError(LlmSynthesisError):
# Providers fall into two transport classes.
PROVIDER_RESPONSES = "responses"
PROVIDER_ANTHROPIC = "anthropic"
PROVIDER_ATLAS = "atlas"
PROVIDER_CODEX = "codex"
PROVIDER_CLAUDE = "claude"

HTTP_PROVIDERS = (PROVIDER_RESPONSES, PROVIDER_ANTHROPIC)
HTTP_PROVIDERS = (PROVIDER_RESPONSES, PROVIDER_ANTHROPIC, PROVIDER_ATLAS)
CLI_PROVIDERS = (PROVIDER_CODEX, PROVIDER_CLAUDE)
SUPPORTED_PROVIDERS = HTTP_PROVIDERS + CLI_PROVIDERS

Expand All @@ -65,6 +68,7 @@ class LlmSynthesisConfigError(LlmSynthesisError):
# ``codex`` has no default — when omitted, the host CLI picks.
DEFAULT_MODEL_RESPONSES = "gpt-5.5"
DEFAULT_MODEL_ANTHROPIC = "claude-opus-4-7"
DEFAULT_MODEL_ATLAS = "openai/gpt-5.5"
DEFAULT_MODEL_CLAUDE = "claude-opus-4-7"
DEFAULT_MODEL_CODEX: str | None = None

Expand All @@ -75,6 +79,7 @@ class LlmSynthesisConfigError(LlmSynthesisError):
# for ``codex``/``claude``. Override via env or ``--base-url``.
DEFAULT_RESPONSES_BASE_URL = "https://api.openai.com/v1"
DEFAULT_ANTHROPIC_BASE_URL = "https://api.anthropic.com"
DEFAULT_ATLAS_BASE_URL = "https://api.atlascloud.ai/v1"

DEFAULT_TIMEOUT_SECONDS = 600
DEFAULT_SYNTHESIS_ITERATIONS = 5
Expand Down Expand Up @@ -185,6 +190,8 @@ def default_model(value: str | None = None, provider: str | None = None) -> str
return os.environ.get("OPENAI_MODEL") or DEFAULT_MODEL_RESPONSES
if provider == PROVIDER_ANTHROPIC:
return os.environ.get("ANTHROPIC_MODEL") or DEFAULT_MODEL_ANTHROPIC
if provider == PROVIDER_ATLAS:
return os.environ.get("ATLASCLOUD_MODEL") or DEFAULT_MODEL_ATLAS
if provider == PROVIDER_CLAUDE:
return os.environ.get("ANTHROPIC_MODEL") or DEFAULT_MODEL_CLAUDE
if provider == PROVIDER_CODEX:
Expand All @@ -210,6 +217,8 @@ def default_base_url(value: str | None = None, provider: str = DEFAULT_PROVIDER)
return value.rstrip("/")
if provider == PROVIDER_ANTHROPIC:
return (os.environ.get("ANTHROPIC_BASE_URL") or DEFAULT_ANTHROPIC_BASE_URL).rstrip("/")
if provider == PROVIDER_ATLAS:
return (os.environ.get("ATLASCLOUD_BASE_URL") or DEFAULT_ATLAS_BASE_URL).rstrip("/")
return (os.environ.get("OPENAI_BASE_URL") or DEFAULT_RESPONSES_BASE_URL).rstrip("/")


Expand Down
86 changes: 84 additions & 2 deletions packages/semia-cli/src/semia_cli/llm_providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,18 @@
# Copyright 2026 RiemaLabs
"""Transport-layer IO for Semia synthesis.

Four providers are supported. The HTTP pair talks raw HTTP (no third-party
Five providers are supported. The HTTP providers talk raw HTTP (no third-party
SDK); the CLI pair shells out to a locally-installed agent CLI.

HTTP providers honor ``--model``, ``--base-url`` and the matching env-var
auth (``OPENAI_API_KEY`` / ``ANTHROPIC_API_KEY``):
auth (``OPENAI_API_KEY`` / ``ANTHROPIC_API_KEY`` / ``ATLASCLOUD_API_KEY``):

- :data:`~.llm_config.PROVIDER_RESPONSES` — OpenAI Responses API, streamed
via Server-Sent Events.
- :data:`~.llm_config.PROVIDER_ANTHROPIC` — Anthropic Messages API, also
streamed via SSE.
- :data:`~.llm_config.PROVIDER_ATLAS` — Atlas Cloud's OpenAI-compatible Chat
Completions API, streamed via SSE.

CLI providers only honor ``--model``; auth is inherited from the host CLI's
config:
Expand Down Expand Up @@ -40,6 +42,7 @@
from .llm_config import (
DEFAULT_MODEL_CLAUDE,
PROVIDER_ANTHROPIC,
PROVIDER_ATLAS,
PROVIDER_CLAUDE,
PROVIDER_CODEX,
PROVIDER_RESPONSES,
Expand Down Expand Up @@ -74,6 +77,12 @@ def call_provider(
lambda: _run_anthropic_messages(prompt, config.model, base_url),
settings.provider_retries,
)
if config.provider == PROVIDER_ATLAS:
base_url = default_base_url(config.base_url, PROVIDER_ATLAS) or ""
return _run_with_retries(
lambda: _run_atlas_chat_completions(prompt, config.model, base_url),
settings.provider_retries,
)
if config.provider == PROVIDER_CODEX:
return _run_with_retries(
lambda: _run_codex(root, prompt, config.model),
Expand Down Expand Up @@ -349,6 +358,79 @@ def _extract_anthropic_text(payload: dict[str, Any]) -> str:
raise LlmSynthesisError("Anthropic response did not include text output")


# ---------------------------------------------------------------------------
# Atlas Cloud Chat Completions API
# ---------------------------------------------------------------------------


def _run_atlas_chat_completions(prompt: str, model: str | None, base_url: str) -> str:
if not model:
raise LlmSynthesisConfigError("atlas provider requires a model name")
api_key = _first_env("SEMIA_ATLASCLOUD_API_KEY", "ATLASCLOUD_API_KEY")
if not api_key:
raise LlmSynthesisConfigError("atlas provider selected, but ATLASCLOUD_API_KEY is not set")
payload: dict[str, Any] = {
"model": model,
"messages": [{"role": "user", "content": prompt}],
"stream": True,
}
req = request.Request(
f"{base_url}/chat/completions",
data=json.dumps(payload).encode("utf-8"),
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"Accept": "text/event-stream",
},
method="POST",
)
try:
with request.urlopen(req, timeout=timeout_seconds()) as response:
return _read_atlas_chat_payload(response)
except error.HTTPError as exc:
detail = exc.read().decode("utf-8", errors="replace")
raise LlmSynthesisError(f"Atlas Cloud API failed ({exc.code}): {detail}") from exc
except (OSError, json.JSONDecodeError) as exc:
raise LlmSynthesisError(f"Atlas Cloud API failed: {exc}") from exc


def _read_atlas_chat_payload(response: Any) -> str:
content_type = response.headers.get("Content-Type", "")
if "text/event-stream" not in content_type:
return _extract_chat_completion_text(json.loads(response.read().decode("utf-8")))

text_parts: list[str] = []
for _event_type, data in _iter_sse_events(_iter_response_lines(response)):
if data == "[DONE]":
break
payload = json.loads(data)
if payload.get("error"):
raise LlmSynthesisError(f"Atlas Cloud API failed: {payload['error']}")
for choice in payload.get("choices", []):
delta = choice.get("delta") if isinstance(choice, dict) else None
content = delta.get("content") if isinstance(delta, dict) else None
if isinstance(content, str):
text_parts.append(content)
content = "".join(text_parts)
if not content:
raise LlmSynthesisError("Atlas Cloud response did not include streamed text output")
return content


def _extract_chat_completion_text(payload: dict[str, Any]) -> str:
pieces: list[str] = []
for choice in payload.get("choices", []):
if not isinstance(choice, dict):
continue
message = choice.get("message")
content = message.get("content") if isinstance(message, dict) else None
if isinstance(content, str):
pieces.append(content)
if pieces:
return "\n".join(pieces)
raise LlmSynthesisError("Atlas Cloud response did not include text output")


# ---------------------------------------------------------------------------
# Codex CLI (subprocess)
# ---------------------------------------------------------------------------
Expand Down
5 changes: 3 additions & 2 deletions packages/semia-cli/src/semia_cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,9 +467,10 @@ def _atomic_write_text(path: Path, content: str) -> None:
def _add_llm_options(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"--provider",
choices=("responses", "anthropic", "codex", "claude", "openai"),
choices=("responses", "anthropic", "atlas", "codex", "claude", "openai"),
help="LLM provider for synthesize; one of: responses (OpenAI Responses "
"API, default), anthropic (Anthropic Messages API), codex (codex CLI), "
"API, default), anthropic (Anthropic Messages API), atlas (Atlas Cloud "
"Chat Completions API), codex (codex CLI), "
"claude (Claude Code CLI). `openai` is an alias for `responses`. "
"Default: SEMIA_LLM_PROVIDER or responses.",
)
Expand Down
67 changes: 66 additions & 1 deletion tests/cli/test_llm_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
sys.path.insert(0, str(CLI_SRC))

from semia_cli import llm_adapter, synthesis_loop # noqa: E402
from semia_cli.llm_config import LlmSynthesisError # noqa: E402
from semia_cli.llm_config import LlmSynthesisConfigError, LlmSynthesisError # noqa: E402
from semia_cli.synthesis_patch import ( # noqa: E402
_looks_like_fact,
apply_incremental_patch,
Expand Down Expand Up @@ -198,6 +198,71 @@ def headers(self) -> dict[str, str]:
body = json_body(urlopen.call_args.args[0].data)
self.assertEqual(body["model"], "deepseek-v4")

def test_atlas_provider_reads_streamed_chat_completion(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
run_dir = Path(tmp)
(run_dir / "synthesis_prompt.md").write_text("Emit facts.", encoding="utf-8")
(run_dir / "prepared_skill.md").write_text("# Demo\n", encoding="utf-8")

class FakeStream:
def __init__(self) -> None:
self._chunks = iter(
[
b'data: {"choices":[{"delta":{"content":"skill(\\"demo\\")."}}]}\n\n',
b"data: [DONE]\n\n",
]
)

def __enter__(self):
return self

def __exit__(self, exc_type, exc, traceback):
return False

@property
def headers(self) -> dict[str, str]:
return {"Content-Type": "text/event-stream"}

def read(self, _size: int = -1) -> bytes:
return next(self._chunks, b"")

with (
mock.patch.dict(
"os.environ",
{"ATLASCLOUD_API_KEY": "test-key", "SEMIA_SYNTHESIS_N_ITERATIONS": "1"},
clear=True,
),
mock.patch(
"semia_cli.llm_providers.request.urlopen", return_value=FakeStream()
) as urlopen,
):
result = llm_adapter.synthesize_facts(
run_dir, provider="atlas", validator=_perfect_validator
)

self.assertEqual(result["provider"], "atlas")
self.assertEqual(result["model"], "openai/gpt-5.5")
self.assertEqual(result["base_url"], "https://api.atlascloud.ai/v1")
self.assertEqual(
(run_dir / "synthesized_facts.dl").read_text(encoding="utf-8"), 'skill("demo").\n'
)
req = urlopen.call_args.args[0]
self.assertEqual(req.full_url, "https://api.atlascloud.ai/v1/chat/completions")
self.assertEqual(
json_body(req.data)["messages"], [{"role": "user", "content": mock.ANY}]
)

def test_atlas_provider_requires_api_key(self) -> None:
from semia_cli import llm_providers

with (
mock.patch.dict("os.environ", {}, clear=True),
self.assertRaisesRegex(LlmSynthesisConfigError, "ATLASCLOUD_API_KEY"),
):
llm_providers._run_atlas_chat_completions(
"Emit facts.", "openai/gpt-5.5", "https://api.atlascloud.ai/v1"
)

def test_claude_default_model_reads_anthropic_model(self) -> None:
with mock.patch.dict("os.environ", {"ANTHROPIC_MODEL": "sonnet"}, clear=True):
model = llm_adapter.default_model(provider="claude")
Expand Down