DocMorph / docmorph /agent.py
Shoufa Zhang
Deploy DocMorph & SeekMorph interactive Studio and 5-layer production benchmark
66227f0
Raw History Blame Contribute Delete
5.75 kB
"""Agent function-calling schema, RAG tool executor, and parallel tool-call message normalizer."""
from __future__ import annotations
import copy
import json
from typing import Any
from docmorph.index import HybridIndex
class DocMorphAgentToolkit:
"""Exposes a HybridIndex as an OpenAI / Qwen / MCP compatible function-calling tool."""
def __init__(self, index: HybridIndex, default_namespace: str | None = None) -> None:
self.index = index
self.default_namespace = default_namespace
@staticmethod
def tool_schema(name: str = "search_knowledge_base") -> dict[str, Any]:
"""Return an OpenAI-compatible function tool schema for searching the DocMorph index."""
return {
"type": "function",
"function": {
"name": name,
"description": (
"Search structured technical documents, tables, and code blocks in the DocMorph knowledge base "
"and return section-cited passages."
),
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Search query keywords or natural-language question.",
},
"top_k": {
"type": "integer",
"description": "Maximum number of chunks to return (default: 5).",
"default": 5,
},
"namespace": {
"type": "string",
"description": "Optional project/tenant namespace filter.",
},
"expand_window": {
"type": "integer",
"description": "Number of neighboring chunks in the same section to include (default: 0).",
"default": 0,
},
},
"required": ["query"],
},
},
}
def execute_tool_call(self, arguments: str | dict[str, Any]) -> str:
"""Execute a search tool call and format the results with section breadcrumbs."""
if isinstance(arguments, str):
try:
args = json.loads(arguments) if arguments.strip() else {}
except json.JSONDecodeError as exc:
return f"(invalid JSON arguments: {exc.msg})"
else:
args = dict(arguments)
query = str(args.get("query") or "").strip()
if not query:
return "(missing required argument: 'query')"
top_k = int(args.get("top_k", 5))
namespace = args.get("namespace") or self.default_namespace
expand_window = int(args.get("expand_window", 0))
hits = self.index.search(
query,
top_k=top_k,
namespace=namespace,
expand_window=expand_window,
)
if not hits:
return f"No matching documents found for query: {query!r}"
return "\n\n---\n\n".join(hit.format_citation(rank=i + 1) for i, hit in enumerate(hits))
def normalize_parallel_tool_calls(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Ensure every parallel tool call in an OpenAI-formatted conversation has a unique ID and bound response."""
normalized: list[dict[str, Any]] = []
used_ids: set[str] = set()
counter = 1
pending_calls: list[dict[str, str]] = []
for raw in messages:
msg = copy.deepcopy(raw)
role = msg.get("role")
if role == "assistant" and isinstance(msg.get("tool_calls"), list):
pending_calls = []
for tc in msg["tool_calls"]:
raw_id = str(tc.get("id") or "").strip()
fn_name = str((tc.get("function") or {}).get("name") or "")
if not raw_id or raw_id in used_ids:
while f"call_{counter}" in used_ids:
counter += 1
assigned_id = f"call_{counter}"
counter += 1
else:
assigned_id = raw_id
used_ids.add(assigned_id)
tc["id"] = assigned_id
pending_calls.append({"raw_id": raw_id, "assigned_id": assigned_id, "name": fn_name})
normalized.append(msg)
elif role in ("tool", "function"):
raw_id = str(msg.get("tool_call_id") or msg.get("id") or "").strip()
fn_name = str(msg.get("name") or "")
matched_idx: int | None = None
if raw_id:
for i, item in enumerate(pending_calls):
if item["assigned_id"] == raw_id or item["raw_id"] == raw_id:
matched_idx = i
break
if matched_idx is None and fn_name:
for i, item in enumerate(pending_calls):
if item["name"] == fn_name:
matched_idx = i
break
if matched_idx is None and pending_calls:
matched_idx = 0
if matched_idx is not None:
bound = pending_calls.pop(matched_idx)["assigned_id"]
else:
while f"call_{counter}" in used_ids:
counter += 1
bound = f"call_{counter}"
counter += 1
used_ids.add(bound)
msg["tool_call_id"] = bound
normalized.append(msg)
else:
normalized.append(msg)
return normalized