char-fork/llama.cpp

git clone https://git.t4t.associates/char-fork/llama.cpp

Mishushacommon/parser: add GigaChatV3/3.1 models support (#19931)a8304b4d2

char/aliceai-t5-moe
13.6 KiB355 linesraw
1{#--------TOOL RENDERING FUNCTIONS---------#}
2
3{#---------------------------------------------------------------
4  Converts JSON Schema (dict) to a TypeScript type definition
5----------------------------------------------------------------#}
6{%- macro json_schema_to_typescript(schema, indent="") -%}
7	{%- set ADDITIONAL_JSON_KEYS = ['format', 'maxItems', 'maximum', 'minItems', 'minimum', 'pattern'] -%}
8	{%- set ty = schema.get("type") -%}
9
10	{# ---------------- OBJECT ---------------- #}
11	{%- if ty == "object" -%}
12		{{- "{\n" -}}
13
14		{# Start building property list #}
15		{%- set props = schema.get("properties", {}) -%}
16		{%- set required = schema.get("required", []) -%}
17		{%- set has_additional_props = schema.get("additionalProperties") is defined -%}
18		{%- set additional_props_type = none -%}
19		{%- if has_additional_props -%}
20			{%- if schema.additionalProperties == true -%}
21				{%- set additional_props_type = {'type': 'any'} -%}
22			{%- elif schema.additionalProperties is mapping -%}
23				{%- set additional_props_type = schema.additionalProperties -%}
24			{%- endif -%}
25		{%- endif -%}
26
27		{%- for key, val in props.items() -%}
28			{# ---------- Description Comments ---------- #}
29			{%- if "description" in val -%}
30				{%- for line in val['description'].split('\n') -%}
31					{%- if line.strip() -%}
32						{{- indent + '// ' + line + '\n' -}}
33					{%- endif -%}
34				{%- endfor -%}
35			{%- endif -%}
36
37			{# ---------- Additional JSON Keys ---------- #}
38			{%- for add_key, add_val in val.items() -%}
39				{%- if add_key in ADDITIONAL_JSON_KEYS -%}
40					{%- if add_val is string -%}
41						{{- indent + '// ' + add_key + ': "' + add_val + '"' + '\n'  -}}
42					{%- else -%}
43						{{- indent + '// ' + add_key + ': ' ~ add_val ~ '\n' -}}
44					{%- endif -%}
45				{%- endif -%}
46			{%- endfor -%}
47
48			{# ---------- Property Definition ---------- #}
49            {%- set type_str = json_schema_to_typescript(
50                val, 
51                indent + "  "
52            ) -%}
53
54			{{- indent + key + ('' if key in required else '?') + ': ' + type_str + ',' -}}
55
56			{%- if "default" in val or "defalut_value" in val -%}
57				{%- set default = val.get("default", val.get("defalut_value")) -%}
58				{%- if default is string -%}
59					{{- ' // default: "' + default + '"' -}}
60				{%- else -%}
61					{{- ' // default: ' ~ default -}}
62				{%- endif -%}
63			{%- endif -%}
64
65			{{- "\n" -}}
66		{%- endfor -%}
67
68		{# Handle additionalProperties as index signature #}
69		{%- if has_additional_props and additional_props_type is not none -%}
70			{%- set additional_type_str = json_schema_to_typescript(
71				additional_props_type,
72				indent + "  "
73			) -%}
74			{{- indent + '[key: string]: ' + additional_type_str + '\n' -}}
75		{%- endif -%}
76
77		{{- indent[: (indent|length - "  "|length) ] + '}' -}}
78
79	{# ---------------- STRING ---------------- #}
80	{%- elif ty == "string" -%}
81		{%- if schema.get("enum") -%}
82            {%- set ns = namespace(enum = []) -%}
83            {%- for en in schema['enum'] -%}
84                {%- set ns.enum = ns.enum + ['"' ~ en ~ '"'] -%}
85            {%- endfor -%}
86			{{- ns.enum | join(' | ') -}}
87		{%- elif schema.get("format", "none") in ['date-time', 'date'] -%}
88			{{- 'Date' -}}
89		{%- else -%}
90			{{- 'string' -}}
91		{%- endif -%}
92
93	{# ---------------- NUMBER / INTEGER ---------------- #}
94	{%- elif ty in ["number", "integer"] -%}
95		{%- if schema.get("enum") -%}
96			{{- schema.enum | join(' | ') -}}
97		{%- else -%}
98			{{- 'number' -}}
99		{%- endif -%}
100
101	{# ---------------- BOOLEAN ---------------- #}
102	{%- elif ty == "boolean" -%}
103		{{- 'boolean' -}}
104
105	{# ---------------- ARRAY ---------------- #}
106	{%- elif ty == "array" -%}
107		{%- if "items" in schema -%}
108			{{- json_schema_to_typescript(schema['items'], indent) + '[]' -}}
109		{%- else -%}
110			{{- 'Array<any>' -}}
111		{%- endif -%}
112
113	{# ---------------- FALLBACK ---------------- #}
114	{%- else -%}
115		{{- 'any' -}}
116	{%- endif -%}
117{%- endmacro -%}
118
119{#---------------------------------------------------------------
120  Renders a namespace and its tool definitions in TypeScript style
121----------------------------------------------------------------#}
122
123{%- macro render_tool_namespace(namespace_name, tools) -%}
124	{%- set ns = namespace(sections = ['namespace ' ~ namespace_name ~ ' {']) -%}
125
126	{%- for tool in tools -%}
127		{%- if tool.function -%}
128			{%- set tool = tool.function -%}
129		{%- endif -%}
130
131		{%- set ns_tool = namespace(content_lines=[]) -%}
132
133		{# ---------- TOOL DESCRIPTION ---------- #}
134		{%- if tool.get('description') -%}
135			{%- for line in tool['description'].split('\n') -%}
136				{%- if line.strip() -%}
137					{%- set ns_tool.content_lines = ns_tool.content_lines + ['// ' ~ line] -%}
138				{%- endif -%}
139			{%- endfor -%}
140		{%- endif -%}
141
142		{# ---------- TOOL SIGNATURE ---------- #}
143		{%- set main_body = "" -%}
144		{%- set params = tool.get("parameters") -%}
145		{%- if params and params.get("properties") -%}
146			{%- set param_type = json_schema_to_typescript(params, "  ") -%}
147			{%- set main_body = 'type ' ~ tool.name ~ ' = (_: ' ~ param_type ~ ') => ' -%}
148		{%- else -%}
149			{%- set main_body = 'type ' ~ tool.name ~ ' = () => ' -%}
150		{%- endif -%}
151
152		{# ---------- RETURN TYPE ---------- #}
153		{%- set return_params = tool.get("return_parameters") -%}
154		{%- if return_params and return_params.get("properties") -%}
155			{%- set return_type = json_schema_to_typescript(return_params, "  ") -%}
156			{%- set main_body = main_body ~ return_type -%}
157		{%- else -%}
158			{%- set main_body = main_body ~ 'any' -%}
159		{%- endif -%}
160
161		{%- set main_body = main_body ~ ';\n' -%}
162
163		{%- set ns_tool.content_lines = ns_tool.content_lines + [main_body] -%}
164
165		{# ---------- ADD TOOL TO SECTIONS ---------- #}
166		{%- set ns.sections = ns.sections + [ns_tool.content_lines | join('\n')] -%}
167	{%- endfor -%}
168
169	{%- set ns.sections = ns.sections + ['} // namespace ' ~ namespace_name] -%}
170
171	{{- ns.sections | join('\n') -}}
172{%- endmacro -%}
173
174
175{# ----------- MESSAGE RENDERING HELPER FUNCTIONS ------------ #}
176
177{%- macro render_role_message(message, role=None) -%}
178    {%- if not role -%}
179        {%- set role = message["role"] -%}
180    {%- endif -%}
181
182    {%- set message_content = message['content'] or '' -%}
183    {%- if message_content is not string -%}
184        {%- set message_content = message_content | tojson(ensure_ascii=False) -%}
185    {%- endif -%}
186
187    {{- role + add_tokens.role_sep + message_content + add_tokens.message_sep -}}
188
189{%- endmacro -%}
190
191
192{%- macro render_function_call(message) -%}
193    {%- set call = message['content'] -%}
194    {%- if call.function -%}
195        {%- set call = call.function -%}
196    {%- endif -%}
197
198    {%- set arguments = call['arguments'] -%}
199	{%- if arguments is not string -%}
200		{%- set arguments = arguments| tojson(ensure_ascii=False) -%}
201	{%- endif -%}
202
203    {{- render_role_message(
204        {
205            'role': 'function call',
206            'content': '{"name": "' ~ call['name'] ~ '", "arguments": ' ~ arguments ~ '}'
207        }
208    ) -}}
209{%- endmacro -%}
210
211{# ----- SPECIAL TOKENS ----- #}
212
213{%- set add_tokens = namespace(
214    role_sep="<|role_sep|>\n", 
215    message_sep="<|message_sep|>\n\n"
216) -%}
217
218{# ----- DEFAULT DEVSYSTEM ----- #}
219
220{%- set DEVSYSTEM -%}
221<role_description>
222Description of the roles available in the dialog.
223
224`developer system`
225A message added by Sber before the main dialog. It has the highest priority and sets global, non-overridable conditions (for example, conversation rules, the safety policy, the assistant's overall response style, etc.).
226
227`system`
228A system instruction added by developers or by the user, but with a lower priority than `developer system`. It usually describes the assistant's instructions, a specific response style, and other conditions for this particular dialog.
229
230`user`
231A message or request from the user. The assistant follows it if it does not conflict with higher-priority instructions (see <instruction_priority>).
232
233`user memory`
234A sequence of the most up-to-date long-term facts about the user at the time of their request, presented as a JSON list of strings. Facts are listed in chronological order, meaning newer facts are appended to the end of the sequence. When facts are changed or deleted, records of previous facts remain in the sequence. The assistant saves facts using a function and uses them in accordance with the <memory_guidelines> block below.
235
236`added files`
237Metadata about files available for use in the dialog, presented in JSON format. It contains the following keys: id (a unique file identifier), name (file name), type (file type).
238
239`assistant`
240The assistant's reply to the user's request. If the system instruction or the user does not set additional rules for `assistant`, this reply must comply with the instructions in the <assistant_guidelines> block below. The list of functions available to call is contained in `function descriptions`. The name of the required function and its arguments will be generated next by the `function call` role. In its replies, the assistant follows the instructions in accordance with <instruction_priority>.
241
242`function descriptions`
243Function descriptions in TypeScript format. A function is a special tool (or a set of instructions) that the assistant can call to perform specific actions, computations, or obtain data needed to solve the user's task. Each function description contains blocks with the name, description, and arguments. Sometimes the description contains separate blocks with return parameters and usage examples that illustrate the correct call and arguments.
244
245`function call`
246The function that `assistant` calls based on the dialog context, and its arguments. The function is invoked in strict accordance with the instructions in the <function_usage> block.
247
248`function result`
249The result of the last function call.
250</role_description>
251
252<available_modalities>
253The assistant can work with the following modalities: text, available functions.
254</available_modalities>
255
256<instruction_priority>
257If instructions from different roles conflict within the dialog context, observe the following priorities:  
258`developer system` > `system` > `user` > `function descriptions` > `function result` > `user memory`
259</instruction_priority>
260
261<function_usage>
262Basic instructions for working with functions.
263
264Only call those functions that are described in `function descriptions`.
265
266Call available functions when, according to their description, such a call will help provide a more complete and/or accurate answer to the user's request. Fill in function arguments using information from the dialog context. If a function could help answer the request but a required argument is missing from the context, ask the user for the missing data before calling the function. If a necessary function is unavailable or an error occurs, briefly inform the user and, if possible, suggest an alternative.
267</function_usage>
268
269<memory_guidelines>
270Rules for using facts in long-term memory:
271
272If there is no message under the `user memory` role in the dialog, this is equivalent to the absence of long-term facts about the user in memory. In that case, information about the user is limited to the current dialog, and no new facts should be saved.
273</memory_guidelines>
274
275<assistant_guidelines>
276You are a helpful assistant.
277
278# Instructions
279- Strictly follow the instruction priority.
280- Maintain a logical chain of reasoning when answering the user's question.
281- For complex questions (for example, STEM), try to answer in detail unless the system message or dialog context limits the response length.
282- Be helpful, truthful, and avoid unsafe or prohibited content in your responses.
283- Try to reply in the language in which the user asked their question.
284</assistant_guidelines>
285
286A dialog will follow below.
287The dialog may include various roles described in the <role_description> block.
288Each turn begins with the role name and a special token that marks the end of the role's full name, and ends with a special end-of-turn token.
289Your task is to continue the dialog from the last specified role in accordance with the dialog context.
290{%- endset -%}
291
292
293{#- ---------------------- RENDERING STARTS HERE ---------------------- -#}
294
295
296{# ----- RENDER BOS TOKEN ----- #}
297{{- bos_token -}}
298
299
300{# ----- RENDER DEVSYSTEM ----- #}
301{{- render_role_message({"role": "developer system", "content": DEVSYSTEM}) -}}
302
303{# ----- RENDER SYSTEM IF PRESENT ----- #}
304{%- if messages and messages[0]['role'] == 'system' -%}
305    {{- render_role_message(messages[0]) -}}
306    {%- set messages = messages[1:] -%}
307{%- endif -%}
308
309{# ----- RENDER TOOLS ----- #}
310{%- if tools -%}
311    {%- set tools_content = (
312        render_tool_namespace('functions', tools) 
313        + "\n\n"
314    ) -%}
315    {{- render_role_message({'role': 'function descriptions', 'content': tools_content}) -}}
316{%- endif -%}
317
318{# ----- MAIN MESSAGE LOOP ----- #}
319{%- for message in messages -%}
320
321    {# ----- TOOL MESSAGE -------#}
322    {%- if message['role'] == 'tool' -%}
323        {{- render_role_message(message, 'function result') -}}
324
325
326    {# ----- ASSISTANT MESSAGE ----- #}
327    {%- elif message['role'] == 'assistant' -%}
328
329        {# ----- FUNCTION CALL PART CHECKING: SINGLE CALL SETUP ----- #}
330        {%- if message.tool_calls is defined and message.tool_calls -%}
331            {%- set function_call = message.tool_calls[0] -%}
332        {%- else -%}
333            {%- set function_call = None -%}
334        {%- endif -%}
335
336        {# ----- MAIN ASSISTANT RENDERING ----- #}
337
338        {{- render_role_message({'role': 'assistant', 'content': message.content}) -}}
339        {%- if function_call -%}
340            {{- render_function_call({'role': 'function call', 'content': function_call}) -}}
341        {%- endif -%}
342
343        
344    {# ----- OTHER MESSAGES ----- #}
345    {%- else -%}
346        {{- render_role_message(message) -}}
347    {%- endif -%}
348
349    {# ----- ADDING GENERATION PROMPT ----- #}
350
351    {%- if loop.last and add_generation_prompt and message['role'] != 'assistant' -%}
352        {{- 'assistant' + add_tokens.role_sep -}}
353    {%- endif -%}
354
355{%- endfor -%}