File size: 6,855 Bytes
4b97c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
"""
TokioAI Engine -- Guided Generation
Forces the model to produce valid structured output using Ollama's format parameter.

Instead of hoping the model generates valid JSON, we CONSTRAIN it.
Ollama supports JSON mode natively, and we combine that with our tool schemas
to guarantee valid output.

For non-Ollama backends, we use post-processing + retry as fallback.
"""

import json
from typing import Any, Dict, List, Optional

from .schemas import TOOL_DEFINITIONS, TOOL_SCHEMAS, VALID_TOOL_NAMES


def get_tool_json_schema() -> Dict:
    """
    Generate a JSON schema that constrains model output to valid tool calls.
    This is used with Ollama's `format` parameter for structured output.
    """
    # Build a union schema: the model must output one of the valid tool call shapes
    tool_schemas = []
    
    for tool_def in TOOL_DEFINITIONS:
        func = tool_def["function"]
        tool_schemas.append({
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "const": func["name"],
                },
                "arguments": func["parameters"],
            },
            "required": ["name", "arguments"],
            "additionalProperties": False,
        })

    # anyOf: model can output any one of these tool call shapes
    return {
        "type": "object",
        "anyOf": tool_schemas,
    }


def get_simple_json_schema() -> Dict:
    """
    Simplified schema: just name (enum) + arguments (object).
    More compatible with Ollama's format support.
    """
    return {
        "type": "object",
        "properties": {
            "name": {
                "type": "string",
                "enum": sorted(VALID_TOOL_NAMES),
            },
            "arguments": {
                "type": "object",
            },
        },
        "required": ["name", "arguments"],
    }


def get_text_response_schema() -> Dict:
    """
    Schema for text-only responses (no tool calls).
    Forces the model to output a simple response object.
    """
    return {
        "type": "object",
        "properties": {
            "response": {
                "type": "string",
                "description": "Your text response to the user",
            },
            "needs_tool": {
                "type": "boolean",
                "description": "Set to true if you think a tool should be used instead",
            },
        },
        "required": ["response"],
    }


def get_decision_schema() -> Dict:
    """
    Schema for decision mode: model chooses between tool call or text response.
    """
    return {
        "type": "object",
        "properties": {
            "action": {
                "type": "string",
                "enum": ["tool_call", "text_response"],
                "description": "Whether to call a tool or respond with text",
            },
            "tool_call": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string",
                        "enum": sorted(VALID_TOOL_NAMES),
                    },
                    "arguments": {
                        "type": "object",
                    },
                },
                "description": "If action is tool_call, provide the tool call here",
            },
            "text_response": {
                "type": "string",
                "description": "If action is text_response, provide your response here",
            },
        },
        "required": ["action"],
    }


def build_ollama_request(
    model: str,
    messages: List[Dict],
    intent: str,
    force_json: bool = True,
    temperature: float = 0.3,
    max_tokens: int = 4096,
    stream: bool = False,
) -> Dict:
    """
    Build an Ollama /api/chat request with optional guided generation.
    
    Args:
        model: Ollama model name
        messages: Chat messages
        intent: Classified intent (determines schema)
        force_json: Whether to constrain output to JSON
        temperature: Sampling temperature
        max_tokens: Max tokens to generate
        stream: Whether to stream the response
        
    Returns:
        Request body dict ready for POST to /api/chat
    """
    request = {
        "model": model,
        "messages": messages,
        "stream": stream,
        "options": {
            "temperature": temperature,
            "num_predict": max_tokens,
        },
    }

    if force_json and intent in ("tool_call", "decision"):
        # Use Ollama's structured output
        if intent == "tool_call":
            request["format"] = get_simple_json_schema()
        elif intent == "decision":
            request["format"] = get_decision_schema()
    elif force_json and intent == "text":
        # For text, we DON'T force JSON -- let the model speak naturally
        pass

    # Add tools in OpenAI format (Ollama supports this)
    if intent in ("tool_call", "decision"):
        request["tools"] = TOOL_DEFINITIONS

    return request


def parse_guided_output(raw_output: str, intent: str) -> Dict:
    """
    Parse the guided (JSON-constrained) output from the model.
    
    Returns a normalized dict:
    - For tool_call: {"type": "tool_call", "name": str, "arguments": dict}
    - For text: {"type": "text", "response": str}
    - For decision: {"type": "tool_call"|"text", ...}
    """
    try:
        data = json.loads(raw_output)
    except json.JSONDecodeError:
        # Try to extract JSON from text
        import re
        match = re.search(r'\{.*\}', raw_output, re.DOTALL)
        if match:
            try:
                data = json.loads(match.group())
            except json.JSONDecodeError:
                return {"type": "text", "response": raw_output}
        else:
            return {"type": "text", "response": raw_output}

    # Decision format
    if "action" in data:
        if data["action"] == "tool_call" and "tool_call" in data:
            tc = data["tool_call"]
            return {
                "type": "tool_call",
                "name": tc.get("name", ""),
                "arguments": tc.get("arguments", {}),
            }
        elif data["action"] == "text_response":
            return {
                "type": "text",
                "response": data.get("text_response", ""),
            }

    # Direct tool call format
    if "name" in data and data["name"] in VALID_TOOL_NAMES:
        return {
            "type": "tool_call",
            "name": data["name"],
            "arguments": data.get("arguments", {}),
        }

    # Text response format
    if "response" in data:
        return {
            "type": "text",
            "response": data["response"],
        }

    # Unknown format -- return as text
    return {"type": "text", "response": json.dumps(data)}