File size: 5,747 Bytes
66227f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
"""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