Class: ChatController

Inherits:
ApplicationController
  • Object
show all
Includes:
LangsmithrbRails::TracedController
Defined in:
lib/generators/langsmithrb_rails/demo/templates/chat_controller.rb

Overview

Controller for the chat demo

Instance Method Summary collapse

Instance Method Details

#createObject

POST /chat



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
# File 'lib/generators/langsmithrb_rails/demo/templates/chat_controller.rb', line 14

def create
  # Create trace for the entire request
  langsmith_trace("chat_request", run_type: "chain") do |run|
    @message = ChatMessage.new(message_params)
    @message.is_user = true
    
    if @message.save
      # Record the user message in the trace
      run.inputs = { user_message: @message.content }
      
      # Generate a response
      llm_service = LlmService.new
      context = ChatMessage.order(created_at: :asc).last(5).map do |msg|
        { is_user: msg.is_user, content: msg.content }
      end
      
      response = llm_service.generate(@message.content, context)
      
      # Create the assistant message
      @assistant_message = ChatMessage.create!(
        content: response,
        is_user: false
      )
      
      # Record the assistant response in the trace
      run.outputs = { assistant_message: @assistant_message.content }
      
      # Respond with both messages for AJAX updates
      render json: {
        user_message: render_to_string(partial: "message", locals: { message: @message }),
        assistant_message: render_to_string(partial: "message", locals: { message: @assistant_message })
      }
    else
      render json: { error: @message.errors.full_messages.join(", ") }, status: :unprocessable_entity
    end
  end
end

#indexObject

GET /chat



8
9
10
11
# File 'lib/generators/langsmithrb_rails/demo/templates/chat_controller.rb', line 8

def index
  @messages = ChatMessage.order(created_at: :asc).last(10)
  @message = ChatMessage.new
end