Class: Candle::ToolCallParser
- Inherits:
-
Object
- Object
- Candle::ToolCallParser
- Defined in:
- lib/candle/tool_call_parser.rb
Defined Under Namespace
Classes: ParseResult
Constant Summary collapse
- DEFAULT_PATTERN =
/<tool_call>\s*(.*?)\s*<\/tool_call>/m
Instance Attribute Summary collapse
-
#pattern ⇒ Object
readonly
Returns the value of attribute pattern.
Class Method Summary collapse
-
.parse(text, available_tools: []) ⇒ Object
Convenience class method using the default pattern.
Instance Method Summary collapse
-
#initialize(pattern: DEFAULT_PATTERN) ⇒ ToolCallParser
constructor
A new instance of ToolCallParser.
- #parse(text, available_tools: []) ⇒ Object
Constructor Details
#initialize(pattern: DEFAULT_PATTERN) ⇒ ToolCallParser
Returns a new instance of ToolCallParser.
11 12 13 |
# File 'lib/candle/tool_call_parser.rb', line 11 def initialize(pattern: DEFAULT_PATTERN) @pattern = pattern end |
Instance Attribute Details
#pattern ⇒ Object (readonly)
Returns the value of attribute pattern.
9 10 11 |
# File 'lib/candle/tool_call_parser.rb', line 9 def pattern @pattern end |
Class Method Details
.parse(text, available_tools: []) ⇒ Object
Convenience class method using the default pattern
53 54 55 |
# File 'lib/candle/tool_call_parser.rb', line 53 def self.parse(text, available_tools: []) new.parse(text, available_tools: available_tools) end |
Instance Method Details
#parse(text, available_tools: []) ⇒ Object
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 |
# File 'lib/candle/tool_call_parser.rb', line 21 def parse(text, available_tools: []) tool_calls = [] text.scan(@pattern) do |match| json_str = match[0].strip begin parsed = JSON.parse(json_str) name = parsed["name"] arguments = parsed["arguments"] || parsed["parameters"] || {} next unless name if available_tools.empty? || available_tools.any? { |t| t.name == name } tool_calls << ToolCall.new(name: name, arguments: arguments) end rescue JSON::ParserError # Skip malformed tool calls end end # Deduplicate identical tool calls (models sometimes repeat the same call) tool_calls.uniq! { |tc| [tc.name, tc.arguments] } remaining_text = text.gsub(@pattern, "").strip remaining_text = nil if remaining_text.empty? ParseResult.new( text_response: remaining_text, tool_calls: tool_calls ) end |