Class: SmartPrompt::Engine

Inherits:
Object
  • Object
show all
Defined in:
lib/smart_prompt/engine.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config_file) ⇒ Engine

Returns a new instance of Engine.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
51
# File 'lib/smart_prompt/engine.rb', line 6

def initialize(config_file)
  @config_file = config_file
  @adapters = {}
  @llms = {}
  @templates = {}
  @current_workers = {}
  @history_messages = []
  @history_manager = nil
  load_config(config_file)
  SmartPrompt.logger.info "Started create the SmartPrompt engine."
  @stream_proc = Proc.new do |chunk, _bytesize|
    if @stream_response.empty?
      @stream_response["id"] = chunk["id"]
      @stream_response["object"] = chunk["object"]
      @stream_response["created"] = chunk["created"]
      @stream_response["model"] = chunk["model"]
      @stream_response["choices"] = [{
        "index" => 0,
        "message" => {
          "role" => "assistant",
          "content" => "",
          "reasoning_content" => "",
          "tool_calls" => [],
        },
      }]
      @stream_response["usage"] = chunk["usage"]
      @stream_response["system_fingerprint"] = chunk["system_fingerprint"]
    end
    if chunk.dig("choices", 0, "delta", "reasoning_content")
      @stream_response["choices"][0]["message"]["reasoning_content"] += chunk.dig("choices", 0, "delta", "reasoning_content")
    end
    if chunk.dig("choices", 0, "delta", "content")
      @stream_response["choices"][0]["message"]["content"] += chunk.dig("choices", 0, "delta", "content")
    end
    if chunk_tool_calls = chunk.dig("choices", 0, "delta", "tool_calls")
      chunk_tool_calls.each do |tool_call|
        if @stream_response["choices"][0]["message"]["tool_calls"].size > tool_call["index"]
          @stream_response["choices"][0]["message"]["tool_calls"][tool_call["index"]]["function"]["arguments"] += tool_call["function"]["arguments"]
        else
          @stream_response["choices"][0]["message"]["tool_calls"] << tool_call
        end
      end
    end
    @origin_proc.call(chunk, _bytesize)
  end
end

Instance Attribute Details

#adaptersObject (readonly)

Returns the value of attribute adapters.



3
4
5
# File 'lib/smart_prompt/engine.rb', line 3

def adapters
  @adapters
end

#configObject (readonly)

Returns the value of attribute config.



3
4
5
# File 'lib/smart_prompt/engine.rb', line 3

def config
  @config
end

#config_fileObject (readonly)

Returns the value of attribute config_file.



3
4
5
# File 'lib/smart_prompt/engine.rb', line 3

def config_file
  @config_file
end

#current_adapterObject (readonly)

Returns the value of attribute current_adapter.



3
4
5
# File 'lib/smart_prompt/engine.rb', line 3

def current_adapter
  @current_adapter
end

#history_managerObject (readonly)

Returns the value of attribute history_manager.



4
5
6
# File 'lib/smart_prompt/engine.rb', line 4

def history_manager
  @history_manager
end

#llmsObject (readonly)

Returns the value of attribute llms.



3
4
5
# File 'lib/smart_prompt/engine.rb', line 3

def llms
  @llms
end

#stream_responseObject (readonly)

Returns the value of attribute stream_response.



4
5
6
# File 'lib/smart_prompt/engine.rb', line 4

def stream_response
  @stream_response
end

#templatesObject (readonly)

Returns the value of attribute templates.



3
4
5
# File 'lib/smart_prompt/engine.rb', line 3

def templates
  @templates
end

Instance Method Details

#call_worker(worker_name, params = {}) ⇒ Object



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
154
155
# File 'lib/smart_prompt/engine.rb', line 123

def call_worker(worker_name, params = {})
  SmartPrompt.logger.info "Calling worker: #{worker_name} with params: #{params}"
  worker = get_worker(worker_name)
  begin
    unless params[:with_history]
      if worker.conversation
        worker.conversation.messages.clear
      end
    end
    result = worker.execute(params)
    SmartPrompt.logger.info "Worker #{worker_name} executed successfully"
    if result.class == String
      recive_message = {
        "role": "assistant",
        "content": result,
      }
    elsif result.class == Array
      recive_message = nil
    else
      recive_message = {
        "role": result.dig("choices", 0, "message", "role"),
        "content": result.dig("choices", 0, "message", "content").to_s + result.dig("choices", 0, "message", "tool_calls").to_s,
      }
    end
    worker.conversation.add_message(recive_message) if recive_message
    SmartPrompt.logger.info "Worker result is: #{result}"
    result
  rescue => e
    SmartPrompt.logger.error "Error executing worker #{worker_name}: #{e.message}"
    SmartPrompt.logger.debug e.backtrace.join("\n")
    raise
  end
end

#call_worker_by_stream(worker_name, params = {}, &proc) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/smart_prompt/engine.rb', line 157

def call_worker_by_stream(worker_name, params = {}, &proc)
  SmartPrompt.logger.info "Calling worker: #{worker_name} with params: #{params}"
  worker = get_worker(worker_name)
  begin
    @origin_proc = proc
    @stream_response = {}
    ret = worker.execute_by_stream(params, &@stream_proc)
    @stream_response = ret if @stream_response.empty?
    SmartPrompt.logger.info "Worker #{worker_name} executed(stream) successfully"
    SmartPrompt.logger.info "Worker #{worker_name} stream response is: #{@stream_response}"
  rescue => e
    SmartPrompt.logger.error "Error executing worker #{worker_name}: #{e.message}"
    SmartPrompt.logger.debug e.backtrace.join("\n")
    raise
  end
end

#check_worker(worker_name) ⇒ Object



114
115
116
117
118
119
120
121
# File 'lib/smart_prompt/engine.rb', line 114

def check_worker(worker_name)
  if SmartPrompt::Worker.workers[worker_name]
    return true
  else
    SmartPrompt.logger.warn "Invalid worker: #{worker_name}"
    return false
  end
end

#clear_history_messagesObject



190
191
192
193
194
195
# File 'lib/smart_prompt/engine.rb', line 190

def clear_history_messages
  if @history_manager
    SmartPrompt.logger.warn "[DEPRECATED] Engine#clear_history_messages is deprecated. Use history_manager.clear_session(session_id) instead."
  end
  @history_messages = []
end

#create_dir(filename) ⇒ Object



53
54
55
56
57
# File 'lib/smart_prompt/engine.rb', line 53

def create_dir(filename)
  path = File::path(filename).to_s
  parent_dir = File::dirname(path)
  Dir.mkdir(parent_dir, 0755) unless File.directory?(parent_dir)
end

#get_worker(worker_name) ⇒ Object



174
175
176
177
178
179
180
181
# File 'lib/smart_prompt/engine.rb', line 174

def get_worker(worker_name)
  SmartPrompt.logger.info "Creating worker instance for: #{worker_name}"
  unless worker = @current_workers[worker_name]
    worker = Worker.new(worker_name, self)
    @current_workers[worker_name] = worker
  end
  return worker
end

#history_messagesObject



183
184
185
186
187
188
# File 'lib/smart_prompt/engine.rb', line 183

def history_messages
  if @history_manager
    SmartPrompt.logger.warn "[DEPRECATED] Engine#history_messages is deprecated. Use history_manager.get_context(session_id) instead."
  end
  @history_messages
end

#load_config(config_file) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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
# File 'lib/smart_prompt/engine.rb', line 59

def load_config(config_file)
  begin
    @config_file = config_file
    @config = YAML.load_file(config_file)
    if @config["logger_file"]
      create_dir(@config["logger_file"])
      SmartPrompt.logger = Logger.new(@config["logger_file"])
    end
    SmartPrompt.logger.info "Loading configuration from file: #{config_file}"
    if @config["better_prompt_db"]
      require "better_prompt"
      BetterPrompt.setup(db_path: @config["better_prompt_db"])
    end
    @config["adapters"].each do |adapter_name, adapter_class|
      adapter_class = SmartPrompt.const_get(adapter_class)
      @adapters[adapter_name] = adapter_class
    end
    @config["llms"].each do |llm_name, llm_config|
      adapter_class = @adapters[llm_config["adapter"]]
      @llms[llm_name] = adapter_class.new(llm_config)
    end
    @current_llm = @config["default_llm"] if @config["default_llm"]
    Dir.glob(File.join(@config["template_path"], "*.erb")).each do |file|
      template_name = file.gsub(@config["template_path"] + "/", "").gsub("\.erb", "")
      @templates[template_name] = PromptTemplate.new(file)
    end

    # Initialize HistoryManager if configured
    if @config["history"]
      history_config = symbolize_keys(@config["history"])
      @history_manager = HistoryManager.new(history_config)
      SmartPrompt.logger.info "HistoryManager initialized with configuration"
    end

    load_workers
  rescue Psych::SyntaxError => ex
    SmartPrompt.logger.error "YAML syntax error in config file: #{ex.message}"
    raise ConfigurationError, "Invalid YAML syntax in config file: #{ex.message}"
  rescue Errno::ENOENT => ex
    SmartPrompt.logger.error "Config file not found: #{ex.message}"
    raise ConfigurationError, "Config file not found: #{ex.message}"
  rescue StandardError => ex
    SmartPrompt.logger.error "Error loading configuration: #{ex.message}"
    raise ConfigurationError, "Error loading configuration: #{ex.message}"
  ensure
    SmartPrompt.logger.info "Configuration loaded successfully"
  end
end

#load_workersObject



108
109
110
111
112
# File 'lib/smart_prompt/engine.rb', line 108

def load_workers
  Dir.glob(File.join(@config["worker_path"], "*.rb")).each do |file|
    require(file)
  end
end