isbondarev/giga3-github-issues
077
1{#--------TOOL RENDERING FUNCTIONS---------#}2 3{#---------------------------------------------------------------4 Converts JSON Schema (dict) to a TypeScript type definition5----------------------------------------------------------------#}6{%- macro json_schema_to_typescript(schema, indent="", indent_factor=2) -%}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'].splitlines() -%}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 + (' ' * indent_factor), 52 indent_factor53 ) -%}54 55 {{- indent + key + ('' if key in required else '?') + ': ' + type_str + ',' -}}56 57 {%- if "default" in val or "defalut_value" in val -%}58 {%- set default = val.get("default", val.get("defalut_value")) -%}59 {%- if default is string -%}60 {{- ' // default: "' + default + '"' -}}61 {%- else -%}62 {{- ' // default: ' ~ default -}}63 {%- endif -%}64 {%- endif -%}65 66 {{- "\n" -}}67 {%- endfor -%}68 69 {# Handle additionalProperties as index signature #}70 {%- if has_additional_props and additional_props_type is not none -%}71 {%- set additional_type_str = json_schema_to_typescript(72 additional_props_type,73 indent + (' ' * indent_factor),74 indent_factor75 ) -%}76 {{- indent + '[key: string]: ' + additional_type_str + '\n' -}}77 {%- endif -%}78 79 {{- indent[:-indent_factor] + '}' -}}80 81 {# ---------------- STRING ---------------- #}82 {%- elif ty == "string" -%}83 {%- if schema.get("enum") -%}84 {%- set ns = namespace(enum = []) -%}85 {%- for en in schema['enum'] -%}86 {%- set ns.enum = ns.enum + ['"' ~ en ~ '"'] -%}87 {%- endfor -%}88 {{- ns.enum | join(' | ') -}}89 {%- elif schema.get("format") in ['date-time', 'date'] -%}90 {{- 'Date' -}}91 {%- else -%}92 {{- 'string' -}}93 {%- endif -%}94 95 {# ---------------- NUMBER / INTEGER ---------------- #}96 {%- elif ty in ["number", "integer"] -%}97 {%- if schema.get("enum") -%}98 {{- schema.enum | join(' | ') -}}99 {%- else -%}100 {{- 'number' -}}101 {%- endif -%}102 103 {# ---------------- BOOLEAN ---------------- #}104 {%- elif ty == "boolean" -%}105 {{- 'boolean' -}}106 107 {# ---------------- ARRAY ---------------- #}108 {%- elif ty == "array" -%}109 {%- if "items" in schema -%}110 {{- json_schema_to_typescript(schema['items'], indent, indent_factor) + '[]' -}}111 {%- else -%}112 {{- 'Array<any>' -}}113 {%- endif -%}114 115 {# ---------------- FALLBACK ---------------- #}116 {%- else -%}117 {{- 'any' -}}118 {%- endif -%}119{%- endmacro -%}120 121{#---------------------------------------------------------------122 Renders a namespace and its tool definitions in TypeScript style123----------------------------------------------------------------#}124 125{%- macro render_tool_namespace(namespace_name, tools) -%}126 {%- set ns = namespace(sections = ['namespace ' ~ namespace_name ~ ' {']) -%}127 128 {%- for tool in tools -%}129 {%- if tool.function -%}130 {%- set tool = tool.function -%}131 {%- endif -%}132 133 {%- set ns_tool = namespace(content_lines=[]) -%}134 135 {# ---------- TOOL DESCRIPTION ---------- #}136 {%- if tool.get('description') -%}137 {%- for line in tool['description'].splitlines() -%}138 {%- if line.strip() -%}139 {%- set ns_tool.content_lines = ns_tool.content_lines + ['// ' ~ line] -%}140 {%- endif -%}141 {%- endfor -%}142 {%- endif -%}143 144 {# ---------- TOOL SIGNATURE ---------- #}145 {%- set main_body = "" -%}146 {%- set params = tool.get("parameters") -%}147 {%- if params and params.get("properties") -%}148 {%- set param_type = json_schema_to_typescript(params, " ") -%}149 {%- set main_body = 'type ' ~ tool.name ~ ' = (_: ' ~ param_type ~ ') => ' -%}150 {%- else -%}151 {%- set main_body = 'type ' ~ tool.name ~ ' = () => ' -%}152 {%- endif -%}153 154 {# ---------- RETURN TYPE ---------- #}155 {%- set return_params = tool.get("return_parameters") -%}156 {%- if return_params and return_params.get("properties") -%}157 {%- set return_type = json_schema_to_typescript(return_params, " ") -%}158 {%- set main_body = main_body ~ return_type -%}159 {%- else -%}160 {%- set main_body = main_body ~ 'any' -%}161 {%- endif -%}162 163 {%- set main_body = main_body ~ ';\n' -%}164 165 {%- set ns_tool.content_lines = ns_tool.content_lines + [main_body] -%}166 167 {# ---------- ADD TOOL TO SECTIONS ---------- #}168 {%- set ns.sections = ns.sections + [ns_tool.content_lines | join('\n')] -%}169 {%- endfor -%}170 171 {%- set ns.sections = ns.sections + ['} // namespace ' ~ namespace_name] -%}172 173 {{- ns.sections | join('\n') -}}174{%- endmacro -%}175 176 177{# ----------- MESSAGE RENDERING HELPER FUNCTIONS ------------ #}178 179{%- macro render_role_message(message, role=None) -%}180 {%- if not role -%}181 {%- set role = message["role"] -%}182 {%- endif -%}183 184 {%- set message_content = message['content'] or '' -%}185 {%- if message_content is not string -%}186 {%- set message_content = message_content | tojson(ensure_ascii=False) -%}187 {%- endif -%}188 189 {{- role + add_tokens.role_sep + message_content + add_tokens.message_sep -}}190 191{%- endmacro -%}192 193 194{%- macro render_function_call(message) -%}195 {%- set call = message['content'] -%}196 {%- if call.function -%}197 {%- set call = call.function -%}198 {%- endif -%}199 200 {%- set arguments = call['arguments'] -%}201 {%- if arguments is not string -%}202 {%- set arguments = arguments| tojson(ensure_ascii=False) -%}203 {%- endif -%}204 205 {{- render_role_message(206 {207 'role': 'function call',208 'content': '{"name": "' ~ call['name'] ~ '", "arguments": ' ~ arguments ~ '}'209 }210 ) -}}211{%- endmacro -%}212 213{# ----- SPECIAL TOKENS ----- #}214 215{%- set add_tokens = namespace(216 role_sep="<|role_sep|>\n", 217 message_sep="<|message_sep|>\n\n"218) -%}219 220{# ----- DEFAULT DEVSYSTEM ----- #}221 222{%- set DEVSYSTEM -%}223<role_description>224Description of the roles available in the dialog.225 226`developer system`227A 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.).228 229`system`230A 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.231 232`user`233A message or request from the user. The assistant follows it if it does not conflict with higher-priority instructions (see <instruction_priority>).234 235`user memory`236A 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.237 238`added files`239Metadata 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).240 241`assistant`242The 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>.243 244`function descriptions`245Function 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.246 247`function call`248The 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.249 250`function result`251The result of the last function call.252</role_description>253 254<available_modalities>255The assistant can work with the following modalities: text, available functions.256</available_modalities>257 258<instruction_priority>259If instructions from different roles conflict within the dialog context, observe the following priorities: 260`developer system` > `system` > `user` > `function descriptions` > `function result` > `user memory`261</instruction_priority>262 263<function_usage>264Basic instructions for working with functions.265 266Only call those functions that are described in `function descriptions`.267 268Call 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.269</function_usage>270 271<memory_guidelines>272Rules for using facts in long-term memory:273 274If 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.275</memory_guidelines>276 277<assistant_guidelines>278You are a helpful assistant.279 280# Instructions281- Strictly follow the instruction priority.282- Maintain a logical chain of reasoning when answering the user's question.283- For complex questions (for example, STEM), try to answer in detail unless the system message or dialog context limits the response length.284- Be helpful, truthful, and avoid unsafe or prohibited content in your responses.285- Try to reply in the language in which the user asked their question.286</assistant_guidelines>287 288A dialog will follow below.289The dialog may include various roles described in the <role_description> block.290Each 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.291Your task is to continue the dialog from the last specified role in accordance with the dialog context.292{%- endset -%}293 294 295{#- ---------------------- RENDERING STARTS HERE ---------------------- -#}296 297 298{# ----- RENDER BOS TOKEN ----- #}299{{- bos_token -}}300 301 302{# ----- RENDER DEVSYSTEM ----- #}303{{- render_role_message({"role": "developer system", "content": DEVSYSTEM}) -}}304 305{# ----- RENDER SYSTEM IF PRESENT ----- #}306{%- if messages and messages[0]['role'] == 'system' -%}307 {{- render_role_message(messages[0]) -}}308 {%- set messages = messages[1:] -%}309{%- endif -%}310 311{# ----- RENDER TOOLS ----- #}312{%- if tools -%}313 {%- set tools_content = (314 render_tool_namespace('functions', tools) 315 + "\n\n"316 ) -%}317 {{- render_role_message({'role': 'function descriptions', 'content': tools_content}) -}}318{%- endif -%}319 320{# ----- MAIN MESSAGE LOOP ----- #}321{%- for message in messages -%}322 323 {# ----- TOOL MESSAGE -------#}324 {%- if message['role'] == 'tool' -%}325 {{- render_role_message(message, role='function result') -}}326 327 328 {# ----- ASSISTANT MESSAGE ----- #}329 {%- elif message['role'] == 'assistant' -%}330 331 {# ----- FUNCTION CALL PART CHECKING: SINGLE CALL SETUP ----- #}332 {%- if message.tool_calls is defined and message.tool_calls -%}333 {%- set function_call = message.tool_calls[0] -%}334 {%- else -%}335 {%- set function_call = None -%}336 {%- endif -%}337 338 {# ----- MAIN ASSISTANT RENDERING ----- #}339 340 {{- render_role_message({'role': 'assistant', 'content': message.content}) -}}341 {%- if function_call -%}342 {{- render_function_call({'role': 'function call', 'content': function_call}) -}}343 {%- endif -%}344 345 346 {# ----- OTHER MESSAGES ----- #}347 {%- else -%}348 {{- render_role_message(message) -}}349 {%- endif -%}350 351 {# ----- ADDING GENERATION PROMPT ----- #}352 353 {%- if loop.last and add_generation_prompt and message['role'] != 'assistant' -%}354 {{- 'assistant' + add_tokens.role_sep -}}355 {%- endif -%}356 357{%- endfor -%}