-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrails_controller.rb
More file actions
256 lines (218 loc) · 6.49 KB
/
rails_controller.rb
File metadata and controls
256 lines (218 loc) · 6.49 KB
1
2
3
4
5
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
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
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
107
108
109
110
111
112
113
114
115
116
117
118
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
154
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# frozen_string_literal: true
=begin
doredore + Rails Integration Example
This example shows how to integrate doredore with a Rails application.
File location: app/controllers/rag_controller.rb
Installation:
1. Add to Gemfile:
gem 'ffi'
gem 'doredore', path: 'path/to/doredore-rb'
2. Add to config/initializers/doredore.rb:
require 'doredore'
RAG = Doredore::Client.new(
Rails.root.join('db', 'knowledge.db').to_s,
model: 'bge-small-en-v1.5'
)
3. Add routes:
post '/api/search', to: 'rag#search'
post '/api/enrich', to: 'rag#enrich'
post '/api/chat', to: 'rag#chat'
resources :documents, only: [:index, :create, :destroy]
=end
class RagController < ApplicationController
# Skip CSRF for API endpoints (if using as API)
skip_before_action :verify_authenticity_token, only: [:search, :enrich, :chat]
# POST /api/search
# Search for similar documents
#
# Parameters:
# query: string (required)
# collection: string (optional)
# top_k: integer (optional, default: 5)
# threshold: float (optional, default: 0.0)
def search
query = params.require(:query)
collection = params[:collection]
top_k = params[:top_k]&.to_i || 5
threshold = params[:threshold]&.to_f || 0.0
results = RAG.search(
query,
collection: collection,
top_k: top_k,
threshold: threshold
)
render json: {
success: true,
query: query,
results: results.map(&:to_h),
count: results.length
}
rescue StandardError => e
render json: {
success: false,
error: e.message
}, status: :internal_server_error
end
# POST /api/enrich
# Get enriched context for a query
#
# Parameters:
# query: string (required)
# collection: string (optional)
# top_k: integer (optional, default: 3)
def enrich
query = params.require(:query)
collection = params[:collection]
top_k = params[:top_k]&.to_i || 3
result = RAG.enrich(
query,
collection: collection,
top_k: top_k
)
render json: {
success: true,
query: result[:query],
context: result[:context],
sources: result[:sources].map(&:to_h),
source_count: result[:sources].length
}
rescue StandardError => e
render json: {
success: false,
error: e.message
}, status: :internal_server_error
end
# POST /api/chat
# RAG + OpenAI integration for question answering
#
# Parameters:
# message: string (required)
# collection: string (optional, default: 'faq')
# top_k: integer (optional, default: 3)
#
# Requires: gem 'ruby-openai'
def chat
require 'openai'
message = params.require(:message)
collection = params[:collection] || 'faq'
top_k = params[:top_k]&.to_i || 3
# Step 1: Get relevant context using RAG
enrich_result = RAG.enrich(message, collection: collection, top_k: top_k, threshold: 0.3)
Rails.logger.info "📚 Retrieved #{enrich_result[:sources].length} relevant documents"
# Step 2: Call OpenAI with context
client = OpenAI::Client.new(access_token: ENV['OPENAI_API_KEY'])
system_prompt = <<~PROMPT
あなたは質問に正確に答えるアシスタントです。
以下の参考情報を基に回答してください。
参考情報:
#{enrich_result[:context]}
参考情報に基づいて、簡潔かつ正確に回答してください。
PROMPT
response = client.chat(
parameters: {
model: 'gpt-4o-mini',
messages: [
{ role: 'system', content: system_prompt },
{ role: 'user', content: message }
],
temperature: 0.7,
max_tokens: 500
}
)
answer = response.dig('choices', 0, 'message', 'content')
render json: {
success: true,
message: message,
answer: answer,
sources: enrich_result[:sources].map(&:to_h),
tokens_used: response.dig('usage', 'total_tokens')
}
rescue StandardError => e
render json: {
success: false,
error: e.message
}, status: :internal_server_error
end
end
# ==============================================================================
# Documents Controller
# ==============================================================================
class DocumentsController < ApplicationController
skip_before_action :verify_authenticity_token
# GET /documents
# List all documents
#
# Parameters:
# collection: string (optional)
def index
# Note: You'll need to implement list_documents in the Ruby binding
# or use the database directly
# For now, return a placeholder
render json: {
success: true,
documents: [],
message: 'List documents - to be implemented'
}
end
# POST /documents
# Add a new document
#
# Parameters:
# content: string (required)
# collection: string (optional, default: 'default')
# metadata: hash (optional)
def create
content = params.require(:content)
collection = params[:collection] || 'default'
metadata = params[:metadata]
doc_id = RAG.add_document(
content,
collection: collection,
metadata: metadata
)
render json: {
success: true,
document_id: doc_id,
message: 'Document added successfully'
}
rescue StandardError => e
render json: {
success: false,
error: e.message
}, status: :internal_server_error
end
# DELETE /documents/:id
# Delete a document
def destroy
id = params.require(:id).to_i
RAG.delete_document(id)
render json: {
success: true,
message: "Document #{id} deleted successfully"
}
rescue StandardError => e
render json: {
success: false,
error: e.message
}, status: :internal_server_error
end
end
# ==============================================================================
# Background Job Example (Sidekiq)
# ==============================================================================
class ImportCsvJob
include Sidekiq::Worker
def perform(file_path, collection = 'default')
# Initialize RAG (or use global instance)
rag = Doredore::Client.new(
Rails.root.join('db', 'knowledge.db').to_s,
model: 'bge-small-en-v1.5'
)
# Import CSV
count = rag.import_csv(file_path, collection: collection, content_column: 'content')
Rails.logger.info "✅ Imported #{count} documents from #{file_path}"
rescue StandardError => e
Rails.logger.error "❌ CSV import failed: #{e.message}"
raise
end
end