Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

fix(examples): enforce distinct evidence steps

svonava74bcc5c1013e
diff --git a/examples/contract-review-agent/contract_review_agent/app.py b/examples/contract-review-agent/contract_review_agent/app.py
index 0655d5baf..9988a1406 100644
--- a/examples/contract-review-agent/contract_review_agent/app.py
+++ b/examples/contract-review-agent/contract_review_agent/app.py
@@ -63,16 +63,16 @@ field, use "unknown" (or false for `executed`). Make key_obligations and risk_fl
specific 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",
+ ("classify_document", None),
+ ("ocr_signature_page", None),
+ ("extract_entities", None),
+ ("read_signature_page", None),
+ ("search_clauses", "automatic renewal"),
+ ("search_clauses", "limitation of liability"),
+ ("search_clauses", "indemnification"),
+ ("search_clauses", "termination"),
+ ("analyze_clause_risks", None),
+ ("query_obligations_db", None),
)
diff --git a/examples/contract-review-agent/contract_review_agent/native_model.py b/examples/contract-review-agent/contract_review_agent/native_model.py
index 80dbb860a..3f4c9e013 100644
--- a/examples/contract-review-agent/contract_review_agent/native_model.py
+++ b/examples/contract-review-agent/contract_review_agent/native_model.py
@@ -29,6 +29,7 @@ from openai.types.responses import (
from sie_sdk import SIEAsyncClient
_DEFAULT_MAX_NEW_TOKENS = 1200
+type RequiredToolStep = tuple[str, str | None]
def _as_dict(item: Any) -> dict[str, Any]:
@@ -102,26 +103,46 @@ def _conversation(input_items: str | list[TResponseInputItem]) -> str:
return "\n\n".join(turns)
-def _called_tool_names(input_items: str | list[TResponseInputItem]) -> list[str]:
+def _called_tools(input_items: str | list[TResponseInputItem]) -> list[dict[str, Any]]:
if isinstance(input_items, str):
return []
rows = [_as_dict(item) for item in input_items]
return [
- row["name"]
+ row
for row in rows
if row.get("type") == "function_call" and isinstance(row.get("name"), str)
]
def _next_required_tool(
- required_sequence: tuple[str, ...],
+ required_sequence: tuple[RequiredToolStep, ...],
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
+ for call in _called_tools(input_items):
+ if progress >= len(required_sequence):
+ break
+ required_name, required_query = required_sequence[progress]
+ if call["name"] != required_name:
+ continue
+ if required_query is not None:
+ raw_arguments = call.get("arguments")
+ try:
+ arguments = (
+ json.loads(raw_arguments)
+ if isinstance(raw_arguments, str)
+ else raw_arguments
+ )
+ except json.JSONDecodeError:
+ continue
+ query = arguments.get("query") if isinstance(arguments, dict) else None
+ if (
+ not isinstance(query, str)
+ or query.strip().casefold() != required_query.casefold()
+ ):
+ continue
+ progress += 1
+ return required_sequence[progress][0] if progress < len(required_sequence) else None
def _function_tools(tools: list[Tool]) -> list[FunctionTool]:
@@ -328,7 +349,7 @@ class SIENativeModel(Model):
client: SIEAsyncClient,
*,
provision_timeout_s: float,
- required_tool_sequence: tuple[str, ...] = (),
+ required_tool_sequence: tuple[RequiredToolStep, ...] = (),
) -> None:
self.model = model
self._client = client
@@ -365,9 +386,13 @@ class SIENativeModel(Model):
)
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]
+ 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}")
+ raise ModelBehaviorError(
+ f"Required tool is unavailable: {required_tool}"
+ )
allow_final = False
schema = _turn_schema(selected_tools, output_schema, allow_final=allow_final)
result = await self._client.generate(
diff --git a/examples/contract-review-agent/contract_review_agent/runtime.py b/examples/contract-review-agent/contract_review_agent/runtime.py
index cd29adb61..2de9db791 100644
--- a/examples/contract-review-agent/contract_review_agent/runtime.py
+++ b/examples/contract-review-agent/contract_review_agent/runtime.py
@@ -10,7 +10,7 @@ from typing import Any
from sie_sdk import SIEAsyncClient
-from .native_model import SIENativeModel
+from .native_model import RequiredToolStep, SIENativeModel
def provision_timeout_from(cfg: dict[str, Any]) -> float:
@@ -23,7 +23,7 @@ def model_for(
client: SIEAsyncClient,
*,
provision_timeout_s: float,
- required_tool_sequence: tuple[str, ...] = (),
+ required_tool_sequence: tuple[RequiredToolStep, ...] = (),
) -> SIENativeModel:
"""Bind one SIE catalog model to the Agents SDK native model interface."""
return SIENativeModel(
diff --git a/examples/contract-review-agent/tests/test_native_model.py b/examples/contract-review-agent/tests/test_native_model.py
index e6478a456..2961786dd 100644
--- a/examples/contract-review-agent/tests/test_native_model.py
+++ b/examples/contract-review-agent/tests/test_native_model.py
@@ -18,7 +18,7 @@ from agents.tool_context import ToolContext
from pydantic import BaseModel
from contract_review_agent import tools as contract_tools
-from contract_review_agent.native_model import SIENativeModel
+from contract_review_agent.native_model import SIENativeModel, _next_required_tool
from contract_review_agent.runtime import AppContext, GenResult, Ledger, instruct_once
set_tracing_disabled(True)
@@ -89,7 +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",),
+ required_tool_sequence=(("echo", None),),
),
tools=[echo],
)
@@ -106,6 +106,37 @@ async def test_agents_runner_executes_native_tool_turn_then_finishes() -> None:
assert client.calls[1]["kwargs"]["wait_for_capacity"] is True
+def test_required_search_steps_only_advance_on_the_expected_query() -> None:
+ sequence = (
+ ("search_clauses", "automatic renewal"),
+ ("search_clauses", "termination"),
+ ("analyze_clause_risks", None),
+ )
+ repeated_query = [
+ {
+ "type": "function_call",
+ "name": "search_clauses",
+ "arguments": json.dumps({"query": "automatic renewal"}),
+ },
+ {
+ "type": "function_call",
+ "name": "search_clauses",
+ "arguments": json.dumps({"query": "automatic renewal"}),
+ },
+ ]
+ distinct_queries = [
+ repeated_query[0],
+ {
+ "type": "function_call",
+ "name": "search_clauses",
+ "arguments": json.dumps({"query": "termination"}),
+ },
+ ]
+
+ assert _next_required_tool(sequence, repeated_query) == "search_clauses"
+ assert _next_required_tool(sequence, distinct_queries) == "analyze_clause_risks"
+
+
class Risk(BaseModel):
clause: str
severity: str
diff --git a/examples/financial-filing-agent/financial_filing/review.py b/examples/financial-filing-agent/financial_filing/review.py
index 2d192503e..f39c982b5 100644
--- a/examples/financial-filing-agent/financial_filing/review.py
+++ b/examples/financial-filing-agent/financial_filing/review.py
@@ -201,7 +201,15 @@ def _table_row_context(text: str, row_label: str) -> str:
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()
+ separator = re.search(r"\|\s*\|\s*-{3,}", text)
+ if separator is None or header_end < 0 or separator.start() >= row_start:
+ raise RuntimeError(f"The source table omitted its header before the {row_label} row")
+ column_count = len(text[header_end : separator.start() + 1].split("|")) - 2
+ row_pipe_offsets = [match.start() for match in re.finditer(r"\|", text[row_start:])]
+ if column_count < 1 or len(row_pipe_offsets) <= column_count:
+ raise RuntimeError(f"The source table returned an incomplete {row_label} row")
+ row_end = row_start + row_pipe_offsets[column_count] + 1
+ return f"{header} {text[row_start:row_end]}".strip()
def _table_source_values(text: str, row_label: str) -> tuple[str, str]:
diff --git a/examples/financial-filing-agent/tests/test_review.py b/examples/financial-filing-agent/tests/test_review.py
index fe5ed1063..fb772239e 100644
--- a/examples/financial-filing-agent/tests/test_review.py
+++ b/examples/financial-filing-agent/tests/test_review.py
@@ -130,15 +130,18 @@ def test_gliner_gate_requires_all_primary_source_amounts() -> None:
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 |"
+ "| Metric | Original | Adjustment | Restated | | --- | --- | --- | --- | "
+ "| Net income | $45,096 | $(9,016) | $36,080 | | Diluted | $1.68 | | $1.34 | "
+ "| Basic | $1.60 | | $1.20 |"
)
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 "| Diluted | $1.68 | | $1.34 |" in context
assert "Net income" not in context
+ assert "Basic" not in context
def test_docling_line_breaks_do_not_split_source_sections() -> None: