llm bridge service
This commit is contained in:
1 parent
f21baa7ebd
commit
63c5fc9903
20 files changed
+725
-172
No files matched your search
@@ -14,6 +14,7 @@ import urllib.request
|
||||
|
||||
import pytest
|
||||
|
||||
from semif_agent.bridges.llm import LLMBridge
|
||||
from semif_agent.bridges.registry import describe_bridges, known_infos
|
||||
from semif_agent.bridges.simplex import SimplexBridge
|
||||
|
||||
@@ -442,6 +443,94 @@ def test_history_lookup_failure_is_reported():
|
||||
bridge.stop()
|
||||
|
||||
|
||||
# ---- LLM bridge ----
|
||||
|
||||
class FakeLLMClient:
|
||||
"""Stands in for the scheduler's configured `llm` client."""
|
||||
|
||||
def __init__(self, reply="ok", error=None):
|
||||
self.reply = reply
|
||||
self.error = error
|
||||
self.calls = []
|
||||
|
||||
def chat(self, messages, max_tokens=None):
|
||||
self.calls.append((messages, max_tokens))
|
||||
if self.error is not None:
|
||||
raise self.error
|
||||
return self.reply
|
||||
|
||||
|
||||
def start_llm_bridge(client=None, **config):
|
||||
bridge = LLMBridge(config, client=client)
|
||||
port = bridge.start()
|
||||
return bridge, f"http://127.0.0.1:{port}"
|
||||
|
||||
|
||||
def test_llm_bridge_chat_returns_model_text():
|
||||
client = FakeLLMClient(reply='{"title": "x", "description": ""}')
|
||||
bridge, base = start_llm_bridge(client)
|
||||
try:
|
||||
messages = [{"role": "user", "content": "add lunch tomorrow"}]
|
||||
assert post(f"{base}/chat", {"messages": messages}) == {
|
||||
"text": client.reply
|
||||
}
|
||||
assert client.calls == [(messages, None)]
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_llm_bridge_forwards_max_tokens():
|
||||
client = FakeLLMClient()
|
||||
bridge, base = start_llm_bridge(client)
|
||||
try:
|
||||
post(f"{base}/chat", {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 64})
|
||||
assert client.calls[0][1] == 64
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_llm_bridge_rejects_bad_body():
|
||||
bridge, base = start_llm_bridge(FakeLLMClient())
|
||||
try:
|
||||
for payload in ({"messages": []}, {"messages": [{"role": "user"}]}, {}):
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
post(f"{base}/chat", payload)
|
||||
assert exc.value.code == 400
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_llm_bridge_without_a_client_is_unavailable():
|
||||
bridge, base = start_llm_bridge(None)
|
||||
try:
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
post(f"{base}/chat", {"messages": [{"role": "user", "content": "hi"}]})
|
||||
assert exc.value.code == 502
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_llm_bridge_maps_client_error_to_502():
|
||||
bridge, base = start_llm_bridge(FakeLLMClient(error=RuntimeError("down")))
|
||||
try:
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
post(f"{base}/chat", {"messages": [{"role": "user", "content": "hi"}]})
|
||||
assert exc.value.code == 502
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_llm_bridge_health_and_token():
|
||||
bridge, base = start_llm_bridge(FakeLLMClient(), token="sekret")
|
||||
try:
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
get(f"{base}/health")
|
||||
assert exc.value.code == 401
|
||||
assert get(f"{base}/health", token="sekret") == {"ok": True, "platform": "llm"}
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
# ---- catalog / codegen surface ----
|
||||
|
||||
def test_known_infos_include_simplex():
|
||||
@@ -454,6 +543,17 @@ def test_known_infos_include_simplex():
|
||||
assert info.auth_config_var == "simplex_bridge_token"
|
||||
|
||||
|
||||
def test_known_infos_include_llm():
|
||||
infos = {info.name: info for info in known_infos()}
|
||||
assert "llm" in infos
|
||||
info = infos["llm"]
|
||||
assert info.service == "llm"
|
||||
assert info.url_config_var == "llm_bridge_url"
|
||||
assert info.auth_header == "X-Semif-Token"
|
||||
assert info.auth_config_var == "llm_bridge_token"
|
||||
assert any("/chat" in endpoint for endpoint in info.endpoints)
|
||||
|
||||
|
||||
def test_every_bridge_documents_its_config_vars_and_auth():
|
||||
for info in known_infos():
|
||||
docs = dict(info.config_var_docs)
|
||||
|
||||
@@ -318,6 +318,30 @@ def test_answer_roundtrip_via_api(tmp_path):
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
def test_answer_accepts_empty_via_api(tmp_path):
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
seen = []
|
||||
|
||||
def act(ctx, request):
|
||||
seen.append(request.user_input)
|
||||
if request.user_input is None:
|
||||
return ActionResult(
|
||||
action_log="ask", new_state=request.text, needs_input="Tracking number?"
|
||||
)
|
||||
return ActionResult(action_log="empty answer", new_state="unresolved")
|
||||
|
||||
skill = Skill(name="track.manual", category="tracking", description="", act=act)
|
||||
scheduler._run_skill(skill, Request("track my package"))
|
||||
server = Server(scheduler)
|
||||
try:
|
||||
status, payload = server.post("/api/answer", {"text": ""})
|
||||
assert status == 200
|
||||
assert payload["status"] == "ran"
|
||||
assert seen == [None, ""], "empty answer must be forwarded to act"
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
|
||||
def test_questions_endpoint_roundtrip(tmp_path):
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
scheduler.questions.append(
|
||||
|
||||
@@ -172,4 +172,34 @@ def test_resume_can_ask_again(tmp_path):
|
||||
status, detail = scheduler.answer("AB123")
|
||||
assert status == "ran"
|
||||
assert scheduler.pending is None
|
||||
assert scheduler.current is None
|
||||
assert scheduler.current is None
|
||||
|
||||
|
||||
def test_empty_answer_is_accepted_and_forwarded(tmp_path):
|
||||
"""An act-driven pause always accepts an empty answer: it is forwarded to
|
||||
`act` as user_input='' (never rejected). A body that cannot proceed without
|
||||
the info simply produces a failed run, which assessment handles."""
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
seen = []
|
||||
|
||||
def act(ctx, request):
|
||||
seen.append(request.user_input)
|
||||
if request.user_input is None:
|
||||
return ActionResult(
|
||||
action_log="ask",
|
||||
new_state=request.text,
|
||||
needs_input="What's the tracking number?",
|
||||
)
|
||||
return ActionResult(action_log="empty answer", new_state="unresolved")
|
||||
|
||||
skill = Skill(name="track.manual", category="tracking", description="", act=act)
|
||||
result = scheduler._run_skill(skill, Request("track my package"))
|
||||
assert result.kind == "needs_input"
|
||||
|
||||
status, detail = scheduler.answer("")
|
||||
assert status == "ran", detail
|
||||
assert seen == [None, ""], "the empty answer must reach act"
|
||||
assert scheduler.pending is None
|
||||
assert scheduler.current is None
|
||||
answered = [e for e in scheduler.trace.read() if e["kind"] == "answered"]
|
||||
assert answered and answered[-1]["skipped"] is True
|
||||
@@ -1318,6 +1318,77 @@ def test_skill_pre_act_contract_pause_and_resume(tmp_path):
|
||||
assert scheduler.pending is None
|
||||
|
||||
|
||||
def test_pre_act_skip_leaves_variable_unset_and_does_not_reask(tmp_path):
|
||||
"""An empty answer skips a contract variable: it is left unset, the run
|
||||
proceeds, and the same variable is never re-asked (regression: the old
|
||||
no-op skip re-asked the identical question forever)."""
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.tree["tracking"] = []
|
||||
scheduler.body_store.write_contract(
|
||||
"tracking", "track_live", {"token": "The tracking token."}
|
||||
)
|
||||
|
||||
seen = {}
|
||||
|
||||
def act(ctx, request):
|
||||
seen.update(ctx.config)
|
||||
return ActionResult(action_log="done", new_state="done")
|
||||
|
||||
skill = Skill(
|
||||
name="track_live",
|
||||
category="tracking",
|
||||
description="Follow a package.",
|
||||
act=act,
|
||||
contract={"token": "The tracking token."},
|
||||
)
|
||||
|
||||
result = scheduler._run_skill(skill, Request("track my package"))
|
||||
assert result.kind == "needs_input"
|
||||
assert scheduler.pending is not None and scheduler.pending.pre_act is True
|
||||
|
||||
status, detail = scheduler.answer("")
|
||||
assert status == "ran", detail
|
||||
assert scheduler.pending is None
|
||||
assert "token" not in seen, "a skipped variable must stay unset"
|
||||
|
||||
|
||||
def test_pre_act_skip_advances_to_next_missing_variable(tmp_path):
|
||||
"""Skipping one contract variable leaves just that one empty and moves on to
|
||||
the next missing variable, then runs."""
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.tree["tracking"] = []
|
||||
scheduler.body_store.write_contract(
|
||||
"tracking", "probe", {"alpha": "first", "beta": "second"}
|
||||
)
|
||||
|
||||
seen = {}
|
||||
|
||||
def act(ctx, request):
|
||||
seen.update(ctx.config)
|
||||
return ActionResult(action_log="done", new_state="done")
|
||||
|
||||
skill = Skill(
|
||||
name="probe",
|
||||
category="tracking",
|
||||
description="Probe.",
|
||||
act=act,
|
||||
contract={"alpha": "first", "beta": "second"},
|
||||
)
|
||||
|
||||
result = scheduler._run_skill(skill, Request("probe"))
|
||||
assert result.kind == "needs_input"
|
||||
assert "`alpha`" in result.summary
|
||||
|
||||
status, detail = scheduler.answer("")
|
||||
assert status == "needs_input"
|
||||
assert scheduler.pending is not None
|
||||
assert "`beta`" in scheduler.pending.question
|
||||
|
||||
status, detail = scheduler.answer("")
|
||||
assert status == "ran", detail
|
||||
assert "alpha" not in seen and "beta" not in seen
|
||||
|
||||
|
||||
def test_unresolved_variables_respects_tiered_config(tmp_path):
|
||||
"""Contract vars are satisfied by global config, category config, skill
|
||||
config, or per-fire answers — in that order of precedence."""
|
||||
|
||||
Reference in new issue
Block a user