1
0

chat-parser-xml-toolcall.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #pragma once
  2. #include "chat.h"
  3. #include <nlohmann/json.hpp>
  4. #include <optional>
  5. #include <string>
  6. #include <vector>
  7. // Sample config:
  8. // MiniMax-M2 (left): <minimax:tool_call>\n<invoke name="tool-name">\n<parameter name="key">value</parameter>\n...</invoke>\n...</minimax:tool_call>
  9. // GLM 4.5 (right): <tool_call>function_name\n<arg_key>key</arg_key>\n<arg_value>value</arg_value>\n</tool_call>
  10. struct xml_tool_call_format {
  11. std::string scope_start; // <minimax:tool_call>\n // \n // can be empty
  12. std::string tool_start; // <invoke name=\" // <tool_call>
  13. std::string tool_sep; // \">\n // \n // can be empty only for parse_xml_tool_calls
  14. std::string key_start; // <parameter name=\" // <arg_key>
  15. std::string key_val_sep; // \"> // </arg_key>\n<arg_value>
  16. std::string val_end; // </parameter>\n // </arg_value>\n
  17. std::string tool_end; // </invoke>\n // </tool_call>\n
  18. std::string scope_end; // </minimax:tool_call> // // can be empty
  19. // Set this if there can be dynamic spaces inside key_val_sep.
  20. // e.g. key_val_sep=</arg_key> key_val_sep2=<arg_value> for GLM4.5
  21. std::optional<std::string> key_val_sep2 = std::nullopt;
  22. // Set true if argval should only be raw string. e.g. Hello "world" hi
  23. // Set false if argval should only be json string. e.g. "Hello \"world\" hi"
  24. // Defaults to std::nullopt, both will be allowed.
  25. std::optional<bool> raw_argval = std::nullopt;
  26. std::optional<std::string> last_val_end = std::nullopt;
  27. std::optional<std::string> last_tool_end = std::nullopt;
  28. bool trim_raw_argval = false;
  29. bool allow_toolcall_in_think = false; // TODO: UNTESTED!!!
  30. };
  31. // make a GBNF that accept any strings except those containing any of the forbidden strings.
  32. std::string make_gbnf_excluding(std::vector<std::string> forbids);
  33. /**
  34. * Build grammar for xml-style tool call
  35. * form.scope_start and form.scope_end can be empty.
  36. * Requires data.format for model-specific hacks.
  37. */
  38. void build_grammar_xml_tool_call(common_chat_params & data, const nlohmann::ordered_json & tools, const struct xml_tool_call_format & form);