Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(examples): make industry agents production-safe
svonava308bc1829c6a
diff --git a/examples/contract-review-agent/README.md b/examples/contract-review-agent/README.mdindex 9a76a90a8..e81709d54 100644--- a/examples/contract-review-agent/README.md+++ b/examples/contract-review-agent/README.md@@ -19,7 +19,7 @@ Every value below is a real model in the [SIE catalog](https://superlinked.com/m| OCR: scanned page to markdown | `lightonai/LightOnOCR-2-1B` | extract || Clause search: dense embeddings | `BAAI/bge-m3` | encode || Clause rerank: cross-encoder | `Qwen/Qwen3-Reranker-4B` | score |-| Entity extraction: parties, dates, amounts | `urchade/gliner_large-v2.1` | extract |+| Entity extraction: parties, dates, amounts | `urchade/gliner_multi-v2.1` | extract |## How it works@@ -79,7 +79,7 @@ uv run review # uv run review --list to see availableuv run review --contract <slug> # review a specific one```-> **GPU sizing.** The brain (`orchestrator`, which also does the structured synthesis) runs on `Qwen/Qwen3.6-27B` (64K, non-thinking), so it needs an H100 or RTX PRO 6000. The shorter-context roles (`triage`, `vision`, `reasoning`, `sql`) run on `Qwen/Qwen3.5-4B`. A cold cluster pays a one-time load per model on first use; the agent retries the "still provisioning" responses under `cluster.provision_timeout_s`. Keep bundles warm (`minReplicas: 1`) to skip the wait. Any model the cluster can't serve degrades gracefully, logged in the ledger, instead of failing the run.+> **GPU sizing.** The brain (`orchestrator`, which also does the structured synthesis) runs on `Qwen/Qwen3.6-27B` (64K, non-thinking), so it needs an H100 or RTX PRO 6000. The shorter-context roles (`triage`, `vision`, `reasoning`, `sql`) run on `Qwen/Qwen3.5-4B`. A cold cluster pays a one-time load per model on first use; the agent retries the "still provisioning" responses under `cluster.provision_timeout_s`. Keep bundles warm (`minReplicas: 1`) to skip the wait. A required model or tool failure is printed with the partial ledger and exits nonzero.## What you'll seediff --git a/examples/contract-review-agent/config.yaml b/examples/contract-review-agent/config.yamlindex eeea0f0a4..962bfa397 100644--- a/examples/contract-review-agent/config.yaml+++ b/examples/contract-review-agent/config.yaml@@ -25,7 +25,7 @@ models:ocr: "lightonai/LightOnOCR-2-1B" # scanned PDF / image -> markdown (latest OCR model)embed: "BAAI/bge-m3" # dense embeddings for clause searchrerank: "Qwen/Qwen3-Reranker-4B" # cross-encoder rerank of retrieved clauses- entities: "urchade/gliner_large-v2.1" # zero-shot entity extraction (parties, dates, amounts)+ entities: "urchade/gliner_multi-v2.1" # zero-shot entity extraction (parties, dates, amounts)# Tunables for the SIE-backed tools.search:diff --git a/examples/contract-review-agent/contract_review_agent/app.py b/examples/contract-review-agent/contract_review_agent/app.pyindex 310cc250f..0655d5baf 100644--- a/examples/contract-review-agent/contract_review_agent/app.py+++ b/examples/contract-review-agent/contract_review_agent/app.py@@ -6,7 +6,7 @@ from __future__ import annotationsfrom typing import Any-from agents import Agent, Runner, RunResult+from agents import Agent, ModelSettings, Runner, RunResultfrom pydantic import BaseModelfrom .guardrails import safety_guardrail@@ -62,6 +62,19 @@ ONLY the findings provided — never add facts. If the findings don't establishfield, use "unknown" (or false for `executed`). Make key_obligations and risk_flagsspecific and grounded in the findings, and give a clear recommendation."""+_INVESTIGATOR_TOOL_SEQUENCE = (+ "classify_document",+ "ocr_signature_page",+ "extract_entities",+ "read_signature_page",+ "search_clauses",+ "search_clauses",+ "search_clauses",+ "search_clauses",+ "analyze_clause_risks",+ "query_obligations_db",+)+def build_reasoning_agent(cfg: dict[str, Any], client: Any) -> Agent:return Agent(@@ -76,6 +89,7 @@ def build_reasoning_agent(cfg: dict[str, Any], client: Any) -> Agent:client,provision_timeout_s=provision_timeout_from(cfg),),+ model_settings=ModelSettings(temperature=0, max_tokens=1200),)@@ -88,7 +102,9 @@ def build_investigator(cfg: dict[str, Any], client: Any) -> Agent:cfg["models"]["orchestrator"],client,provision_timeout_s=provision_timeout_from(cfg),+ required_tool_sequence=_INVESTIGATOR_TOOL_SEQUENCE,),+ model_settings=ModelSettings(temperature=0, max_tokens=2048),tools=ALL_TOOLS,input_guardrails=[safety_guardrail],)@@ -104,6 +120,7 @@ def build_synthesizer(cfg: dict[str, Any], client: Any) -> Agent:client,provision_timeout_s=provision_timeout_from(cfg),),+ model_settings=ModelSettings(temperature=0, max_tokens=2400),output_type=ContractReview,)diff --git a/examples/contract-review-agent/contract_review_agent/cli.py b/examples/contract-review-agent/contract_review_agent/cli.pyindex 7068760b4..9c7be3cd9 100644--- a/examples/contract-review-agent/contract_review_agent/cli.py+++ b/examples/contract-review-agent/contract_review_agent/cli.py@@ -24,7 +24,7 @@ from .app import (from .config import load_configfrom .data import make_samplefrom .data.paths import CUAD_DIR, GENERATED_DIR, MANIFEST_PATH-from .runtime import AppContext, Ledger, instruct_once+from .runtime import AppContext, Ledger, instruct_once, provision_timeout_fromconsole = Console()@@ -213,7 +213,9 @@ async def _run(args) -> None:)async with SIEAsyncClient(- cfg["cluster"]["url"], api_key=cfg["cluster"]["api_key"] or None+ cfg["cluster"]["url"],+ api_key=cfg["cluster"]["api_key"] or None,+ timeout_s=provision_timeout_from(cfg),) as sie:ledger = Ledger()app = AppContext(@@ -244,7 +246,7 @@ async def _run(args) -> None:)_print_ledger(ledger)return- except Exception as exc: # noqa: BLE001 - report the model boundary failure.+ except Exception as exc:console.print(Panel(f"{type(exc).__name__}: {exc}",@@ -253,7 +255,7 @@ async def _run(args) -> None:))_print_ledger(ledger)- return+ raisewall = time.monotonic() - t0try:diff --git a/examples/contract-review-agent/contract_review_agent/native_model.py b/examples/contract-review-agent/contract_review_agent/native_model.pyindex ccbf7d822..80dbb860a 100644--- a/examples/contract-review-agent/contract_review_agent/native_model.py+++ b/examples/contract-review-agent/contract_review_agent/native_model.py@@ -102,6 +102,28 @@ def _conversation(input_items: str | list[TResponseInputItem]) -> str:return "\n\n".join(turns)+def _called_tool_names(input_items: str | list[TResponseInputItem]) -> list[str]:+ if isinstance(input_items, str):+ return []+ rows = [_as_dict(item) for item in input_items]+ return [+ row["name"]+ for row in rows+ if row.get("type") == "function_call" and isinstance(row.get("name"), str)+ ]+++def _next_required_tool(+ required_sequence: tuple[str, ...],+ input_items: str | list[TResponseInputItem],+) -> str | None:+ progress = 0+ for name in _called_tool_names(input_items):+ if progress < len(required_sequence) and name == required_sequence[progress]:+ progress += 1+ return required_sequence[progress] if progress < len(required_sequence) else None++def _function_tools(tools: list[Tool]) -> list[FunctionTool]:function_tools: list[FunctionTool] = []for tool in tools:@@ -306,10 +328,12 @@ class SIENativeModel(Model):client: SIEAsyncClient,*,provision_timeout_s: float,+ required_tool_sequence: tuple[str, ...] = (),) -> None:self.model = modelself._client = clientself._provision_timeout_s = provision_timeout_s+ self._required_tool_sequence = required_tool_sequenceasync def get_response(self,@@ -339,6 +363,12 @@ class SIENativeModel(Model):_function_tools(tools),model_settings,)+ required_tool = _next_required_tool(self._required_tool_sequence, input)+ if required_tool is not None:+ selected_tools = [tool for tool in selected_tools if tool.name == required_tool]+ if not selected_tools:+ raise ModelBehaviorError(f"Required tool is unavailable: {required_tool}")+ allow_final = Falseschema = _turn_schema(selected_tools, output_schema, allow_final=allow_final)result = await self._client.generate(self.model,diff --git a/examples/contract-review-agent/contract_review_agent/runtime.py b/examples/contract-review-agent/contract_review_agent/runtime.pyindex 102060621..cd29adb61 100644--- a/examples/contract-review-agent/contract_review_agent/runtime.py+++ b/examples/contract-review-agent/contract_review_agent/runtime.py@@ -23,12 +23,14 @@ def model_for(client: SIEAsyncClient,*,provision_timeout_s: float,+ required_tool_sequence: tuple[str, ...] = (),) -> SIENativeModel:"""Bind one SIE catalog model to the Agents SDK native model interface."""return SIENativeModel(model_id,client,provision_timeout_s=provision_timeout_s,+ required_tool_sequence=required_tool_sequence,)diff --git a/examples/contract-review-agent/contract_review_agent/tools.py b/examples/contract-review-agent/contract_review_agent/tools.pyindex 66b93f098..245974149 100644--- a/examples/contract-review-agent/contract_review_agent/tools.py+++ b/examples/contract-review-agent/contract_review_agent/tools.py@@ -96,7 +96,7 @@ async def _clause_index(# ──────────────────────────────────────────────────────────────────────────# Generative-LLM tools# ──────────────────────────────────────────────────────────────────────────-@function_tool+@function_tool(failure_error_function=None)async def classify_document(ctx: RunContextWrapper[AppContext]) -> str:"""Classify the contract under review as MSA, NDA, SOW, or Other, with aone-line reason. A fast first-pass triage over the loaded contract."""@@ -128,7 +128,7 @@ async def classify_document(ctx: RunContextWrapper[AppContext]) -> str:return res.text.strip()-@function_tool+@function_tool(failure_error_function=None)async def read_signature_page(ctx: RunContextWrapper[AppContext], question: str) -> str:"""Ask a vision model a question about the scanned signature-page image(e.g. 'Are both parties' signatures present and dated?'). Use this for@@ -170,7 +170,7 @@ async def read_signature_page(ctx: RunContextWrapper[AppContext], question: str)return res.text.strip()-@function_tool+@function_tool(failure_error_function=None)async def analyze_clause_risks(ctx: RunContextWrapper[AppContext], clauses: str) -> str:"""Delegate deep legal risk analysis of specific clauses to a specialistreasoning agent (the largest model). Pass the clause text to analyze; get@@ -203,7 +203,7 @@ async def analyze_clause_risks(ctx: RunContextWrapper[AppContext], clauses: str)# ──────────────────────────────────────────────────────────────────────────# Retrieval / extraction tools (encode · score · extract)# ──────────────────────────────────────────────────────────────────────────-@function_tool+@function_tool(failure_error_function=None)async def ocr_signature_page(ctx: RunContextWrapper[AppContext]) -> str:"""OCR the executed signature page (a scanned image) into markdown text.Use this to recover who signed, their titles, and the execution date —@@ -232,7 +232,7 @@ async def ocr_signature_page(ctx: RunContextWrapper[AppContext]) -> str:return markdown-@function_tool+@function_tool(failure_error_function=None)async def extract_entities(ctx: RunContextWrapper[AppContext]) -> str:"""Extract structured entities (parties, dates, monetary amounts, governinglaw, notice periods) from the loaded contract using zero-shot NER."""@@ -273,7 +273,7 @@ async def extract_entities(ctx: RunContextWrapper[AppContext]) -> str:return "\n".join(lines) if lines else "(no entities found)"-@function_tool+@function_tool(failure_error_function=None)async def search_clauses(ctx: RunContextWrapper[AppContext], query: str) -> str:"""Find the clauses most relevant to a topic (e.g. 'automatic renewal','limitation of liability', 'indemnification'). Dense-embedding retrieval@@ -377,7 +377,7 @@ def _run_select(db_path: str, sql: str) -> tuple[list[str], list[tuple]]:conn.close()-@function_tool+@function_tool(failure_error_function=None)async def query_obligations_db(ctx: RunContextWrapper[AppContext], question: str) -> str:diff --git a/examples/contract-review-agent/tests/test_native_model.py b/examples/contract-review-agent/tests/test_native_model.pyindex d68d66692..e6478a456 100644--- a/examples/contract-review-agent/tests/test_native_model.py+++ b/examples/contract-review-agent/tests/test_native_model.py@@ -89,6 +89,7 @@ async def test_agents_runner_executes_native_tool_turn_then_finishes() -> None:"Qwen/Qwen3.5-4B",client, # type: ignore[arg-type]provision_timeout_s=30,+ required_tool_sequence=("echo",),),tools=[echo],)@@ -98,8 +99,9 @@ async def test_agents_runner_executes_native_tool_turn_then_finishes() -> None:assert result.final_output == "Grounded result: CLAUSE"assert len(client.calls) == 2first_schema = client.calls[0]["kwargs"]["grammar"]["json_schema"]- assert len(first_schema["oneOf"]) == 2- assert first_schema["oneOf"][0]["properties"]["name"]["const"] == "echo"+ assert first_schema["properties"]["name"]["const"] == "echo"+ second_schema = client.calls[1]["kwargs"]["grammar"]["json_schema"]+ assert len(second_schema["oneOf"]) == 2assert "[tool echo]\nCLAUSE" in client.calls[1]["prompt"]assert client.calls[1]["kwargs"]["wait_for_capacity"] is True@@ -384,17 +386,13 @@ async def test_query_obligations_db_rejects_unknown_generation_mode() -> None:db_path="obligations.db",)- result = await contract_tools.query_obligations_db.on_invoke_tool(- ToolContext(- app,- tool_name="query_obligations_db",- tool_call_id="call-invalid",- tool_arguments=json.dumps({"question": "Show one value"}),- ),- json.dumps({"question": "Show one value"}),- )-- assert result == (- "An error occurred while running the tool. Please try again. "- "Error: sql.mode must be 'instruct' or 'prompt'"- )+ with pytest.raises(ValueError, match="sql.mode must be 'instruct' or 'prompt'"):+ await contract_tools.query_obligations_db.on_invoke_tool(+ ToolContext(+ app,+ tool_name="query_obligations_db",+ tool_call_id="call-invalid",+ tool_arguments=json.dumps({"question": "Show one value"}),+ ),+ json.dumps({"question": "Show one value"}),+ )diff --git a/examples/financial-filing-agent/README.md b/examples/financial-filing-agent/README.mdindex ab60f7d5e..e654e562c 100644--- a/examples/financial-filing-agent/README.md+++ b/examples/financial-filing-agent/README.md@@ -69,6 +69,7 @@ runs/<run-id>/raw/rerank.json complete reranker responseruns/<run-id>/raw/entities.json combined entity spansruns/<run-id>/raw/entities-original-10q.json original Form 10-Q entity spansruns/<run-id>/raw/entities-restated-10ka.json restated Form 10-K/A entity spans+runs/<run-id>/raw/entities-restated-10ka-diluted.json isolated diluted-EPS row spansruns/<run-id>/raw/entities-status.json reliance-status entity spansruns/<run-id>/raw/gliner2-*.json raw GLiNER2 source-span responsesruns/<run-id>/raw/mapped.json validated record mapped from Docling table coordinatesdiff --git a/examples/financial-filing-agent/financial_filing/review.py b/examples/financial-filing-agent/financial_filing/review.pyindex 854f5d8a7..2d192503e 100644--- a/examples/financial-filing-agent/financial_filing/review.py+++ b/examples/financial-filing-agent/financial_filing/review.py@@ -194,6 +194,16 @@ def _single_source_row(ranked: list[dict[str, Any]], term: str, stage: str) -> sreturn min(exact_rows, key=len)+def _table_row_context(text: str, row_label: str) -> str:+ marker = f"| {row_label}"+ row_start = text.casefold().find(marker.casefold())+ if row_start < 0:+ raise RuntimeError(f"The source table omitted the {row_label} row")+ header_end = text.find("|")+ header = text[:header_end].strip() if 0 <= header_end < row_start else ""+ return f"{header} {text[row_start:]}".strip()++def _table_source_values(text: str, row_label: str) -> tuple[str, str]:marker = f"| {row_label}"start = text.casefold().find(marker.casefold())@@ -427,6 +437,11 @@ def run(run_id: str) -> Path:entity_inputs = [("entities_original_10q", original_table_text, FIGURE_ENTITY_LABELS),("entities_restated_10ka", restated_table_text, FIGURE_ENTITY_LABELS),+ (+ "entities_restated_10ka_diluted",+ _table_row_context(restated_table_text, "Diluted"),+ FIGURE_ENTITY_LABELS,+ ),]entity_inputs.append(("entities_status", status_model_text, STATUS_ENTITY_LABELS))for stage, text, labels in entity_inputs:@@ -565,6 +580,7 @@ def run(run_id: str) -> Path:"rerank","entities_original_10q","entities_restated_10ka",+ "entities_restated_10ka_diluted","entities_status","gliner2_original_10q","gliner2_restated_10ka",diff --git a/examples/financial-filing-agent/tests/test_review.py b/examples/financial-filing-agent/tests/test_review.pyindex d4b065714..fe5ed1063 100644--- a/examples/financial-filing-agent/tests/test_review.py+++ b/examples/financial-filing-agent/tests/test_review.py@@ -8,6 +8,7 @@ from financial_filing.review import (_original_table_source_value,_require_entity_evidence,_require_matching_source_values,+ _table_row_context,_table_source_values,build_review,load_config,@@ -126,6 +127,20 @@ def test_gliner_gate_requires_all_primary_source_amounts() -> None:raise AssertionError("GLiNER gate accepted evidence without the restated amount")+def test_table_row_context_keeps_heading_and_isolates_requested_row() -> None:+ source = (+ "## Restated Form 10-K/A. Three Months Ended June 30, 2023 "+ "| Net income | $45,096 | $36,080 | | Diluted | $1.68 | $1.34 |"+ )++ context = _table_row_context(source, "Diluted")++ assert "Restated Form 10-K/A" in context+ assert "Three Months Ended June 30, 2023" in context+ assert "| Diluted | $1.68 | $1.34 |" in context+ assert "Net income" not in context++def test_docling_line_breaks_do_not_split_source_sections() -> None:markdown = """# Pathward Q3 FY2023 source packetdiff --git a/examples/insurance-claims-agent/README.md b/examples/insurance-claims-agent/README.mdindex 4add1fa2f..287220958 100644--- a/examples/insurance-claims-agent/README.md+++ b/examples/insurance-claims-agent/README.md@@ -16,8 +16,8 @@ and debris removal from the yard remain outside that covered scope.|---|---|---|| Parse the appeal and policy | `docling` | Markdown with the record, amounts, rules, analysis, and conclusion || Extract claim facts | `fastino/gliner2-large-v1` | Amounts, debris volume, loss date, and coverage terms |-| Retrieve controlling policy language | `BAAI/bge-reranker-v2-m3` | Ranked passages about non-owned debris removal |-| Produce the cited review | `Qwen/Qwen3.5-4B:no-spec` | JSON separating covered work, excluded costs, and evidence still needed |+| Retrieve controlling policy language | `Qwen/Qwen3-Reranker-4B` | Ranked passages about non-owned debris removal |+| Produce the cited review | `Qwen/Qwen3.5-4B` | JSON separating covered work, excluded costs, and evidence still needed |Every model call goes through SIE.diff --git a/examples/insurance-claims-agent/config.yaml b/examples/insurance-claims-agent/config.yamlindex 3f6b8e9cc..bded941db 100644--- a/examples/insurance-claims-agent/config.yaml+++ b/examples/insurance-claims-agent/config.yaml@@ -8,8 +8,8 @@ cluster:models:parse: "docling"extract: "fastino/gliner2-large-v1"- rerank: "BAAI/bge-reranker-v2-m3"- review: "Qwen/Qwen3.5-4B:no-spec"+ rerank: "Qwen/Qwen3-Reranker-4B"+ review: "Qwen/Qwen3.5-4B"retrieval:candidate_chunks: 16diff --git a/examples/insurance-claims-agent/insurance_claims/review.py b/examples/insurance-claims-agent/insurance_claims/review.pyindex 9048683c6..cb0f80f15 100644--- a/examples/insurance-claims-agent/insurance_claims/review.py+++ b/examples/insurance-claims-agent/insurance_claims/review.py@@ -331,6 +331,11 @@ schema.<|im_end|>max_new_tokens=1800,temperature=0,top_p=1,+ grammar={+ "json_schema": REVIEW_SCHEMA,+ "label": "insurance_appeal_review",+ "strict": True,+ },wait_for_capacity=True,provision_timeout_s=provision_timeout_s,)diff --git a/examples/insurance-claims-agent/tests/test_config.py b/examples/insurance-claims-agent/tests/test_config.pyindex bbdc6fd60..b1cdb69ac 100644--- a/examples/insurance-claims-agent/tests/test_config.py+++ b/examples/insurance-claims-agent/tests/test_config.py@@ -16,8 +16,8 @@ def test_source_set_uses_public_fema_documents() -> None:assert all(source.rights.startswith("U.S. federal government work") for source in config.sources)assert config.models.parse == "docling"assert config.models.extract == "fastino/gliner2-large-v1"- assert config.models.rerank == "BAAI/bge-reranker-v2-m3"- assert config.models.review == "Qwen/Qwen3.5-4B:no-spec"+ assert config.models.rerank == "Qwen/Qwen3-Reranker-4B"+ assert config.models.review == "Qwen/Qwen3.5-4B"def test_bundled_sources_match_the_verified_source_manifest() -> None:diff --git a/examples/insurance-claims-agent/tests/test_review.py b/examples/insurance-claims-agent/tests/test_review.pyindex 8b614d9d9..5b33589d2 100644--- a/examples/insurance-claims-agent/tests/test_review.py+++ b/examples/insurance-claims-agent/tests/test_review.py@@ -11,7 +11,9 @@ import pytestimport insurance_claims.review as review_modulefrom insurance_claims.evaluate import ARTIFACT_EXCLUDED_PATHS, evaluate_review, evaluate_runfrom insurance_claims.review import (+ REVIEW_SCHEMA,_extract_claim_facts,+ _final_review,_json_object_from_text,_require_sources,chunk_markdown,@@ -36,6 +38,15 @@ class FakeExtractClient:return {"data": {"entities": []}}+class FakeGenerateClient:+ def __init__(self) -> None:+ self.kwargs: dict[str, object] = {}++ def generate(self, _model: str, _prompt: str, **kwargs: object) -> dict[str, object]:+ self.kwargs = kwargs+ return {"text": '{"route":"scope_review_required"}'}++def test_chunk_markdown_keeps_all_paragraphs() -> None:markdown = "first paragraph\n\nsecond paragraph is longer\n\nthird"@@ -72,6 +83,26 @@ def test_review_json_accepts_fenced_model_output() -> None:}+def test_final_review_uses_native_strict_json_schema() -> None:+ client = FakeGenerateClient()++ _, parsed, _ = _final_review(+ client,+ "Qwen/Qwen3.5-4B",+ appeal_markdown="appeal",+ claim_facts={},+ policy_chunks=[],+ provision_timeout_s=60,+ )++ assert parsed == {"route": "scope_review_required"}+ assert client.kwargs["grammar"] == {+ "json_schema": REVIEW_SCHEMA,+ "label": "insurance_appeal_review",+ "strict": True,+ }++def test_evaluation_accepts_published_appeal_result() -> None:review = {"route": "scope_review_required",