File size: 6,250 Bytes
2b42456
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""System prompts and message rendering per calling protocol.

The protocol is a run-time axis, not a property of the data: the same case is
rendered in JSON, XML and plain-text form, so per-protocol scores are directly
comparable.
"""

from __future__ import annotations

from typing import Any, Mapping, Sequence

from .schema import Case, Message, Protocol
from .tools import ToolSpec, render_tools

IDENTITY_EN = (
    "You are a helpful assistant developed by Hardcore AI. You answer in the same "
    "language the user writes in. You are concise and precise."
)

IDENTITY_RU = (
    "Ты полезный ассистент, разработанный Hardcore AI. Отвечай на том же языке, "
    "на котором пишет пользователь. Будь кратким и точным."
)

_TOOL_HEADER = {
    "en": "You have access to the following tools:",
    "ru": "Тебе доступны следующие инструменты:",
}

_NO_TOOL_HEADER = {
    "en": "You have no tools available for this conversation.",
    "ru": "В этом диалоге у тебя нет доступных инструментов.",
}

_PROTOCOL_RULES = {
    "json": {
        "en": (
            "To call a tool, reply with a single JSON object and nothing else:\n"
            '{"name": "tool_name", "arguments": {"parameter": "value"}}\n'
            "Use only the parameter names declared for that tool. Do not wrap the JSON in "
            "markdown fences and do not add any prose around it."
        ),
        "ru": (
            "Чтобы вызвать инструмент, ответь одним JSON-объектом и больше ничем:\n"
            '{"name": "tool_name", "arguments": {"parameter": "value"}}\n'
            "Используй только те имена параметров, которые объявлены для этого инструмента. "
            "Не оборачивай JSON в markdown и не добавляй текст вокруг него."
        ),
    },
    "xml": {
        "en": (
            "To call a tool, reply with a single XML call block and nothing else:\n"
            "<tool_call>\n<function=tool_name>\n<parameter=parameter_name>\nvalue\n"
            "</parameter>\n</function>\n</tool_call>\n"
            "Use only the parameter names declared for that tool."
        ),
        "ru": (
            "Чтобы вызвать инструмент, ответь одним XML-блоком вызова и больше ничем:\n"
            "<tool_call>\n<function=tool_name>\n<parameter=parameter_name>\nvalue\n"
            "</parameter>\n</function>\n</tool_call>\n"
            "Используй только те имена параметров, которые объявлены для этого инструмента."
        ),
    },
    "plain": {
        "en": (
            "To call a tool, reply with a single line in this exact format and nothing else:\n"
            "TOOL tool_name | parameter=value | parameter2=value2\n"
            "Use one `|` separated `name=value` segment per parameter, in the order declared "
            "for that tool. Use only the parameter names declared for that tool."
        ),
        "ru": (
            "Чтобы вызвать инструмент, ответь одной строкой строго такого формата и больше ничем:\n"
            "TOOL tool_name | parameter=value | parameter2=value2\n"
            "Используй один сегмент `name=value`, разделённый `|`, на каждый параметр, в порядке "
            "объявления инструмента. Используй только объявленные имена параметров."
        ),
    },
}

_NO_CALL_RULE = {
    "en": (
        "If no tool applies to the user's request, do not emit a call. Answer the user "
        "directly from your own knowledge in plain prose."
    ),
    "ru": (
        "Если ни один инструмент не подходит к запросу, не вызывай его. Ответь "
        "пользователю напрямую обычным текстом, используя свои знания."
    ),
}


def system_prompt(tools: Sequence[ToolSpec], protocol: Protocol, lang: str = "en") -> str:
    language = lang if lang in ("en", "ru") else "en"
    parts: list[str] = [IDENTITY_EN if language == "en" else IDENTITY_RU]

    if tools:
        parts.append(_TOOL_HEADER[language])
        parts.append(render_tools(tools, protocol))
        parts.append(_PROTOCOL_RULES[protocol][language])
    else:
        parts.append(_NO_TOOL_HEADER[language])

    parts.append(_NO_CALL_RULE[language])
    return "\n\n".join(parts)


def render_message(message: Message, protocol: Protocol) -> dict[str, str]:
    if message.role == "assistant" and message.tool_name:
        return {"role": "assistant", "content": render_call(message.tool_name, message.tool_args or {}, protocol)}
    if message.role == "tool":
        return {"role": "user", "content": f"Tool result for {message.tool_name}: {message.content}"}
    return {"role": message.role, "content": message.content}


def render_call(name: str, args: Mapping[str, Any], protocol: Protocol) -> str:
    if protocol == "json":
        import json

        return json.dumps({"name": name, "arguments": dict(args)}, ensure_ascii=False)
    if protocol == "xml":
        body = "\n".join(f"<parameter={key}>\n{value}\n</parameter>" for key, value in args.items())
        return f"<tool_call>\n<function={name}>\n{body}\n</function>\n</tool_call>"
    segments = " | ".join(f"{key}={value}" for key, value in args.items())
    return f"TOOL {name} | {segments}" if segments else f"TOOL {name}"


def render_case(case: Case, protocol: Protocol, specs: Sequence[ToolSpec]) -> list[dict[str, str]]:
    messages: list[dict[str, str]] = [
        {"role": "system", "content": system_prompt(specs, protocol, case.lang)}
    ]
    messages.extend(render_message(message, protocol) for message in case.history)
    messages.append({"role": "user", "content": case.user})
    return messages