Class: SmartAgent::AgentContext

Inherits:
Object
  • Object
show all
Defined in:
lib/smart_agent/agent.rb

Instance Method Summary collapse

Constructor Details

#initialize(agent) ⇒ AgentContext

Returns a new instance of AgentContext.



74
75
76
# File 'lib/smart_agent/agent.rb', line 74

def initialize(agent)
  @agent = agent
end

Instance Method Details

#call_tool(name, params = {}) ⇒ Object



187
188
189
190
191
192
193
194
# File 'lib/smart_agent/agent.rb', line 187

def call_tool(name, params = {})
  if Tool.find_tool(name)
    return Tool.find_tool(name).call(params, @agent)
  end
  if server_name = MCPClient.find_server_by_tool_name(name)
    return MCPClient.new(server_name).call(name, params, @agent)
  end
end

#call_tools(result) ⇒ Object



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/smart_agent/agent.rb', line 155

def call_tools(result)
  @agent.processor(:tool).call({ :status => :start }) if @agent.processor(:tool)
  SmartAgent.logger.info("call tools: " + result.to_s)
  results = []
  result.call_tools.each do |tool|
    tool_call_id = tool["id"]
    tool_name = tool["function"]["name"].to_sym
    params = safe_parse(tool["function"]["arguments"])
    if Tool.find_tool(tool_name)
      tool_result = Tool.find_tool(tool_name).call(params, @agent)
      if tool_result
        @agent.processor(:tool).call({ :content => tool_result })
        SmartAgent.prompt_engine.history_messages << { "role" => "assistant", "content" => "", "tool_calls" => [tool] } #result.response.dig("choices", 0, "message")
        SmartAgent.prompt_engine.history_messages << { "role" => "tool", "tool_call_id" => tool_call_id, "content" => tool_result.to_s.force_encoding("UTF-8") }
        results << tool_result
      end
    end
    if server_name = MCPClient.find_server_by_tool_name(tool_name)
      tool_result = MCPClient.new(server_name).call(tool_name, params, @agent)
      if tool_result
        @agent.processor(:tool).call({ :content => tool_result })
        SmartAgent.prompt_engine.history_messages << { "role" => "assistant", "content" => "", "tool_calls" => [tool] } # result.response.dig("choices", 0, "message")
        SmartAgent.prompt_engine.history_messages << { "role" => "tool", "tool_call_id" => tool_call_id, "content" => tool_result.to_s }
        results << tool_result
      end
    end
    @agent.processor(:tool).call({ :content => " ... done\n" }) if @agent.processor(:tool)
  end
  @agent.processor(:tool).call({ :status => :end }) if @agent.processor(:tool)
  return results
end

#call_worker(name, params, with_tools: true, with_history: false) ⇒ Object



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/smart_agent/agent.rb', line 82

def call_worker(name, params, with_tools: true, with_history: false)
  SmartAgent.logger.info("Call Worker name is: #{name}")
  SmartAgent.logger.info("Call Worker params is: #{params}")
  if with_tools
    simple_tools = []
    if @agent.tools
      simple_tools = @agent.tools.map { |tool_name| Tool.find_tool(tool_name).to_json }
    end
    if @agent.servers
      mcp_tools = @agent.servers.map { |mcp_name| MCPClient.new(mcp_name).to_json }
      mcp_tools.each do |tools|
        tools["tools"].each do |tool|
          simple_tools << tool
        end
      end
    end
    params[:tools] = simple_tools
  end
  params[:with_history] = with_history
  ret = nil
  if @agent.on_event
    SmartAgent.prompt_engine.call_worker_by_stream(name, params) do |chunk, _bytesize|
      if chunk.dig("choices", 0, "delta", "reasoning_content")
        @agent.processor(:reasoning).call(chunk) if @agent.processor(:reasoning)
      end
      if chunk.dig("choices", 0, "delta", "content")
        @agent.processor(:content).call(chunk) if @agent.processor(:content)
      end
    end
    result = SmartAgent.prompt_engine.stream_response
  else
    result = SmartAgent.prompt_engine.call_worker(name, params)
  end
  ret = Result.new(result)
  return ret
end

#paramsObject



196
197
198
# File 'lib/smart_agent/agent.rb', line 196

def params
  @params ||= {}
end

#safe_parse(input) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/smart_agent/agent.rb', line 119

def safe_parse(input)
  # 保存原始输入用于调试
  original_input = input.dup

  # 步骤1: 清理输入
  cleaned = input.strip

  # 步骤2: 处理外层引号(如果存在)
  if cleaned.start_with?('"') && cleaned.end_with?('"')
    cleaned = cleaned[1...-1]
  end

  # 步骤3: 反转义双重转义字符
  # 关键:只处理需要反转义的字符,保持JSON合法性
  cleaned = cleaned
    .gsub(/\\"/, '"') # 反转义引号
    .gsub(/\\\\/, '\\')    # 反转义反斜杠
  # 不反转义\n, \t, \r等,因为它们是JSON合法的转义序列

  # 步骤4: 尝试解析
  begin
    return JSON.parse(cleaned)
  rescue JSON::ParserError => e
    # 如果清理后失败,尝试原始输入
    begin
      return JSON.parse(original_input)
    rescue JSON::ParserError
      puts "Failed to parse JSON: #{e.message}"
      puts "Original: #{original_input}"
      puts "Cleaned: #{cleaned}"
      # 返回原始字符串以便后续处理
      return original_input
    end
  end
end

#show_log(msg) ⇒ Object



78
79
80
# File 'lib/smart_agent/agent.rb', line 78

def show_log(msg)
  @agent.processor(:logging).call(msg) if @agent.processor(:logging)
end