MrMoz33's picture
TokioAI-Coder IoT Package v1.0 -- Engine + IoT System Prompt + Tools
4b97c3b verified
Raw History Blame Contribute Delete
6.86 kB
"""
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)}