feat: resolve agent LLM per role at client construction
This commit is contained in:
@@ -38,6 +38,16 @@ def _default_max_iterations() -> int:
|
||||
except (TypeError, ValueError):
|
||||
return MAX_ITERATIONS
|
||||
|
||||
|
||||
def _llm_for_role(role: str) -> LLMClient:
|
||||
# Tests patch loop.LLMClient with zero-arg fakes that lack for_role;
|
||||
# prefer role resolution, fall back to a bare instance.
|
||||
factory = LLMClient
|
||||
for_role = getattr(factory, "for_role", None)
|
||||
if callable(for_role):
|
||||
return for_role(role)
|
||||
return factory()
|
||||
|
||||
# Async callback that persists + broadcasts one harness message.
|
||||
MessageSink = Callable[[dict[str, Any]], Awaitable[None]]
|
||||
|
||||
@@ -77,7 +87,7 @@ async def run_turn(
|
||||
turn_no = _next_turn_number(ctx.session_id)
|
||||
log_append(session_log.TURN_START, {"turn": turn_no})
|
||||
|
||||
client = LLMClient()
|
||||
client = _llm_for_role("main")
|
||||
final_text = ""
|
||||
turn_status = "completed"
|
||||
try:
|
||||
|
||||
@@ -24,6 +24,16 @@ from calliope.events.bus import event_bus
|
||||
|
||||
logger = logging.getLogger("calliope.harness.orchestrator")
|
||||
|
||||
|
||||
def _llm_for_role(role: str) -> LLMClient:
|
||||
# Tests patch orch.LLMClient with zero-arg fakes that lack for_role;
|
||||
# prefer role resolution, fall back to a bare instance.
|
||||
factory = LLMClient
|
||||
for_role = getattr(factory, "for_role", None)
|
||||
if callable(for_role):
|
||||
return for_role(role)
|
||||
return factory()
|
||||
|
||||
# LLM context window bound: the last N user turns are replayed into each
|
||||
# request. Tool exchanges never span user turns, so tool_call/result pairs
|
||||
# always survive the trim intact.
|
||||
@@ -125,7 +135,7 @@ def _scoped_payload(ctx: ToolContext, allowed: list[str]) -> list[dict[str, Any]
|
||||
|
||||
|
||||
async def _plan(goal: str, workspace_summary: str) -> dict[str, Any]:
|
||||
client = LLMClient()
|
||||
client = _llm_for_role("planner")
|
||||
try:
|
||||
text = await client.chat(
|
||||
[
|
||||
@@ -337,7 +347,7 @@ async def orchestrate(
|
||||
+ "\n\nWrite a concise final summary for the user: what was done, "
|
||||
"job ids enqueued, and any failures. Plain text."
|
||||
)
|
||||
client = LLMClient()
|
||||
client = _llm_for_role("planner")
|
||||
try:
|
||||
final = await client.chat(
|
||||
[
|
||||
@@ -390,7 +400,8 @@ async def _run_sub_agent(
|
||||
else:
|
||||
await event_bus.publish("agent.message", {"session_id": ctx.session_id, **message})
|
||||
|
||||
client = LLMClient()
|
||||
role = agent_name.removesuffix("-agent")
|
||||
client = _llm_for_role(role)
|
||||
messages = list(sub_history)
|
||||
system = (
|
||||
"You are a specialized sub-agent in Calliope's production swarm. "
|
||||
|
||||
@@ -17,10 +17,15 @@ _STREAM_UNSUPPORTED_STATUS = frozenset({400, 404, 405, 501})
|
||||
|
||||
|
||||
class LLMClient:
|
||||
def __init__(self) -> None:
|
||||
self.base_url = settings.llm_base_url.rstrip("/")
|
||||
self.model = settings.llm_model
|
||||
self.api_key = settings.llm_api_key
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
model: str | None = None,
|
||||
api_key: str | None = None,
|
||||
) -> None:
|
||||
self.base_url = (base_url or settings.llm_base_url).rstrip("/")
|
||||
self.model = model or settings.llm_model
|
||||
self.api_key = api_key if api_key is not None else settings.llm_api_key
|
||||
# With every completion streamed (chat/chat_with_tools consume
|
||||
# chat_stream), 120 s bounds the gap BETWEEN chunks, not total
|
||||
# generation time: a thinking model streaming reasoning_content keeps
|
||||
@@ -28,6 +33,16 @@ class LLMClient:
|
||||
# server still fails fast.
|
||||
self.client = httpx.AsyncClient(timeout=120.0)
|
||||
|
||||
@classmethod
|
||||
def for_role(cls, role: str) -> LLMClient:
|
||||
"""Client for an agent role's assigned profile (active fallback)."""
|
||||
profile = settings.resolve_llm_for_role(role)
|
||||
return cls(
|
||||
base_url=profile.get("base_url"),
|
||||
model=profile.get("model"),
|
||||
api_key=profile.get("api_key") if isinstance(profile.get("api_key"), str) else None,
|
||||
)
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if self.api_key:
|
||||
|
||||
@@ -69,7 +69,7 @@ def _h3_subjects(
|
||||
|
||||
async def _h3_rewrite(scene: dict[str, Any], subjects: list[dict[str, Any]]) -> str:
|
||||
"""LLM rewrite into H3's six-section format, deterministic template on failure."""
|
||||
client = LLMClient()
|
||||
client = LLMClient.for_role("video")
|
||||
try:
|
||||
return await client.chat(
|
||||
build_minimax_h3_ref_messages(scene, subjects), temperature=0.4
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
"""LLMClient.for_role resolves assignments → active fallback."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from calliope.agent.llm import LLMClient
|
||||
from calliope.config import settings
|
||||
|
||||
|
||||
def test_for_role_uses_assignment_and_fallback(client):
|
||||
a_id = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
b_id = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
|
||||
prev_profiles = [dict(p) for p in settings.llm_profiles]
|
||||
prev_active = settings.llm_active_id
|
||||
prev_assign = dict(settings.agent_llm_assignments or {})
|
||||
try:
|
||||
settings.llm_profiles = [
|
||||
{"id": a_id, "name": "Local", "base_url": "http://x/a/v1", "model": "m-a", "api_key": "k-a"},
|
||||
{"id": b_id, "name": "Cloud", "base_url": "https://x/b/v1", "model": "m-b", "api_key": "k-b"},
|
||||
]
|
||||
settings.llm_active_id = a_id
|
||||
settings.agent_llm_assignments = {"video": b_id}
|
||||
|
||||
video = LLMClient.for_role("video")
|
||||
assert video.model == "m-b"
|
||||
assert video.base_url == "https://x/b/v1"
|
||||
assert video.api_key == "k-b"
|
||||
|
||||
story = LLMClient.for_role("story") # unassigned → active
|
||||
assert story.model == "m-a"
|
||||
|
||||
ghost = LLMClient.for_role("not-a-role") # unknown → active, no raise
|
||||
assert ghost.model == "m-a"
|
||||
finally:
|
||||
settings.llm_profiles = prev_profiles
|
||||
settings.llm_active_id = prev_active
|
||||
settings.agent_llm_assignments = prev_assign
|
||||
settings.apply_active_llm()
|
||||
Reference in New Issue
Block a user