Class: DSPy::LM::Strategies::AnthropicToolUseStrategy
- Inherits:
-
BaseStrategy
- Object
- BaseStrategy
- DSPy::LM::Strategies::AnthropicToolUseStrategy
show all
- Extended by:
- T::Sig
- Defined in:
- lib/dspy/lm/strategies/anthropic_tool_use_strategy.rb
Overview
Strategy for using Anthropic’s tool use feature for guaranteed JSON output
Instance Method Summary
collapse
#initialize
Instance Method Details
#available? ⇒ Boolean
13
14
15
16
|
# File 'lib/dspy/lm/strategies/anthropic_tool_use_strategy.rb', line 13
def available?
adapter.is_a?(DSPy::LM::AnthropicAdapter) && supports_tool_use?
end
|
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
|
# File 'lib/dspy/lm/strategies/anthropic_tool_use_strategy.rb', line 49
def (response)
begin
if response.metadata.respond_to?(:tool_calls) && response.metadata.tool_calls
tool_calls = response.metadata.tool_calls
if tool_calls.is_a?(Array) && !tool_calls.empty?
first_call = tool_calls.first
if first_call[:name] == "json_output" && first_call[:input]
json_result = JSON.generate(first_call[:input])
return json_result
end
end
end
content = response.content
if content && !content.empty? && content.include?("<tool_use>")
tool_content = content[/<tool_use>.*?<\/tool_use>/m]
if tool_content
json_match = tool_content[/<input>(.*?)<\/input>/m, 1]
return json_match.strip if json_match
end
end
nil
rescue => e
DSPy.logger.debug("Failed to extract tool use JSON: #{e.message}")
nil
end
end
|
#handle_error(error) ⇒ Object
82
83
84
85
86
87
88
89
90
|
# File 'lib/dspy/lm/strategies/anthropic_tool_use_strategy.rb', line 82
def handle_error(error)
if error.message.include?("tool") || error.message.include?("invalid_request_error")
DSPy.logger.warn("Anthropic tool use failed: #{error.message}")
true else
false end
end
|
#name ⇒ Object
24
25
26
|
# File 'lib/dspy/lm/strategies/anthropic_tool_use_strategy.rb', line 24
def name
"anthropic_tool_use"
end
|
#prepare_request(messages, request_params) ⇒ Object
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
# File 'lib/dspy/lm/strategies/anthropic_tool_use_strategy.rb', line 29
def prepare_request(messages, request_params)
tool_schema = convert_to_tool_schema
request_params[:tools] = [tool_schema]
request_params[:tool_choice] = {
type: "tool",
name: "json_output"
}
if messages.any? && messages.last[:role] == "user"
messages.last[:content] += "\n\nPlease use the json_output tool to provide your response."
end
end
|
#priority ⇒ Object
19
20
21
|
# File 'lib/dspy/lm/strategies/anthropic_tool_use_strategy.rb', line 19
def priority
95 end
|