Assistant node, and the Control tab as one conversation (openpanel V5)
run_turn takes its tools, system prompt and tool caller; the chat passes the MCP tools as before. The assistant node offers one tool per wired target, reads its other inputs as context, streams its reply a sentence at a time, warms the provider on `listening` and says so when the provider is not there. Completions share the per-server HTTP client. wren replies when nothing reads `unhandled`, stt shows a note when nothing was heard. /ai/control lists one conversation per entry node with the messages to watch.
This commit is contained in:
+78
-59
@@ -1,9 +1,11 @@
|
||||
"""The turn: the model, the tools, and the rounds between them.
|
||||
|
||||
The tools are the MCP server's own, called in-process rather than over the
|
||||
endpoint: same names, same schemas, same REST calls underneath. A tool added
|
||||
for external agents is there for the assistant the moment it exists, and the
|
||||
assistant can do nothing an external agent could not.
|
||||
The turn takes its tools, its system prompt and the function that calls a
|
||||
tool from whoever runs it. The chat passes the MCP server's own, called
|
||||
in-process rather than over the endpoint: same names, same schemas, same REST
|
||||
calls underneath. A tool added for external agents is there for the chat the
|
||||
moment it exists, and it can do nothing an external agent could not. The
|
||||
assistant node passes the targets wired to it, and nothing else.
|
||||
|
||||
The transcript is a list of chat-completion messages, mutated in place by
|
||||
:func:`run_turn` and persisted by the caller. It is also what the browser
|
||||
@@ -14,7 +16,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from collections.abc import AsyncIterator
|
||||
from collections.abc import AsyncIterator, Awaitable, Callable
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
@@ -83,6 +85,23 @@ def _arguments(raw: Any) -> dict[str, Any]:
|
||||
return parsed if isinstance(parsed, dict) else {}
|
||||
|
||||
|
||||
#: Runs one tool call and answers with what the model reads back.
|
||||
type ToolCaller = Callable[[str, dict[str, Any]], Awaitable[str]]
|
||||
|
||||
|
||||
def mcp_caller(authorization: str) -> ToolCaller:
|
||||
"""The MCP tools, each call made as the person chatting."""
|
||||
|
||||
async def call(name: str, arguments: dict[str, Any]) -> str:
|
||||
token = caller_authorization.set(authorization)
|
||||
try:
|
||||
return await _call_tool(name, arguments)
|
||||
finally:
|
||||
caller_authorization.reset(token)
|
||||
|
||||
return call
|
||||
|
||||
|
||||
async def _call_tool(name: str, arguments: dict[str, Any]) -> str:
|
||||
"""Run one tool; whatever goes wrong is text the model can read."""
|
||||
try:
|
||||
@@ -114,8 +133,11 @@ async def run_turn(
|
||||
messages: list[dict[str, Any]],
|
||||
text: str,
|
||||
*,
|
||||
flow: str | None,
|
||||
authorization: str,
|
||||
tools: list[dict[str, Any]],
|
||||
system: str,
|
||||
call_tool: ToolCaller,
|
||||
extra: dict[str, Any] | None = None,
|
||||
timeout: float | httpx.Timeout = 120.0,
|
||||
) -> AsyncIterator[dict[str, Any]]:
|
||||
"""One user turn, yielding progress events as it goes.
|
||||
|
||||
@@ -125,56 +147,53 @@ async def run_turn(
|
||||
part-way leaves a transcript the provider still accepts.
|
||||
"""
|
||||
messages.append({"role": "user", "content": text})
|
||||
tools = await tool_specs()
|
||||
system = {"role": "system", "content": system_prompt(flow)}
|
||||
token = caller_authorization.set(authorization)
|
||||
try:
|
||||
for _ in range(config.max_rounds):
|
||||
choice: dict[str, Any] = {}
|
||||
try:
|
||||
async for part in client.stream_completion(
|
||||
api_base=config.api_base,
|
||||
api_key=config.api_key,
|
||||
model=config.model,
|
||||
messages=[system, *messages],
|
||||
tools=tools,
|
||||
):
|
||||
if isinstance(part, str):
|
||||
yield {"type": "delta", "content": part}
|
||||
else:
|
||||
choice = part
|
||||
except (client.ProviderError, httpx.HTTPError) as exc:
|
||||
yield {"type": "error", "detail": f"The provider answered {exc}"}
|
||||
return
|
||||
content = choice.get("content") or ""
|
||||
calls = choice.get("tool_calls") or []
|
||||
assistant: dict[str, Any] = {"role": "assistant", "content": content}
|
||||
if content:
|
||||
yield {"type": "message", "content": content}
|
||||
if not calls:
|
||||
messages.append(assistant)
|
||||
return
|
||||
assistant["tool_calls"] = calls
|
||||
answers: list[dict[str, Any]] = []
|
||||
for call in calls:
|
||||
function = call.get("function") or {}
|
||||
name = str(function.get("name", ""))
|
||||
arguments = _arguments(function.get("arguments"))
|
||||
yield {"type": "tool_call", "name": name, "arguments": arguments}
|
||||
result = await _call_tool(name, arguments)
|
||||
answers.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": call.get("id", ""),
|
||||
"content": result,
|
||||
}
|
||||
)
|
||||
yield {"type": "tool_result", "name": name, **summarize(result)}
|
||||
head = {"role": "system", "content": system}
|
||||
for _ in range(config.max_rounds):
|
||||
choice: dict[str, Any] = {}
|
||||
try:
|
||||
async for part in client.stream_completion(
|
||||
api_base=config.api_base,
|
||||
api_key=config.api_key,
|
||||
model=config.model,
|
||||
messages=[head, *messages],
|
||||
tools=tools,
|
||||
timeout=timeout,
|
||||
extra=extra,
|
||||
):
|
||||
if isinstance(part, str):
|
||||
yield {"type": "delta", "content": part}
|
||||
else:
|
||||
choice = part
|
||||
except (client.ProviderError, httpx.HTTPError) as exc:
|
||||
yield {"type": "error", "detail": f"The provider answered {exc}"}
|
||||
return
|
||||
content = choice.get("content") or ""
|
||||
calls = choice.get("tool_calls") or []
|
||||
assistant: dict[str, Any] = {"role": "assistant", "content": content}
|
||||
if content:
|
||||
yield {"type": "message", "content": content}
|
||||
if not calls:
|
||||
messages.append(assistant)
|
||||
messages.extend(answers)
|
||||
yield {
|
||||
"type": "error",
|
||||
"detail": f"Stopped after {config.max_rounds} rounds of tool calls.",
|
||||
}
|
||||
finally:
|
||||
caller_authorization.reset(token)
|
||||
return
|
||||
assistant["tool_calls"] = calls
|
||||
answers: list[dict[str, Any]] = []
|
||||
for call in calls:
|
||||
function = call.get("function") or {}
|
||||
name = str(function.get("name", ""))
|
||||
arguments = _arguments(function.get("arguments"))
|
||||
yield {"type": "tool_call", "name": name, "arguments": arguments}
|
||||
result = await call_tool(name, arguments)
|
||||
answers.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": call.get("id", ""),
|
||||
"content": result,
|
||||
}
|
||||
)
|
||||
yield {"type": "tool_result", "name": name, **summarize(result)}
|
||||
messages.append(assistant)
|
||||
messages.extend(answers)
|
||||
yield {
|
||||
"type": "error",
|
||||
"detail": f"Stopped after {config.max_rounds} rounds of tool calls.",
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user