forked from icereed/paperless-gpt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_llm_test.go
More file actions
486 lines (411 loc) · 13.8 KB
/
app_llm_test.go
File metadata and controls
486 lines (411 loc) · 13.8 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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
package main
import (
"context"
"fmt"
"os"
"testing"
"text/template"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/tmc/langchaingo/llms"
"github.com/tmc/langchaingo/textsplitter"
"gorm.io/gorm"
)
// Mock LLM for testing
type mockLLM struct {
lastPrompt string
Response string
Error error
}
func (m *mockLLM) CreateEmbedding(_ context.Context, texts []string) ([][]float32, error) {
return nil, nil // Not used in these tests
}
func (m *mockLLM) Call(ctx context.Context, prompt string, options ...llms.CallOption) (string, error) {
m.lastPrompt = prompt
resp, err := m.GenerateContent(ctx, []llms.MessageContent{
{Role: llms.ChatMessageTypeHuman, Parts: []llms.ContentPart{llms.TextContent{Text: prompt}}}},
options...)
if err != nil {
return "", err
}
return resp.Choices[0].Content, nil
}
func (m *mockLLM) GenerateContent(ctx context.Context, messages []llms.MessageContent, options ...llms.CallOption) (*llms.ContentResponse, error) {
if len(messages) > 0 && len(messages[0].Parts) > 0 {
if textContent, ok := messages[0].Parts[0].(llms.TextContent); ok {
m.lastPrompt = textContent.Text
}
}
if m.Error != nil {
return nil, m.Error
}
content := "test response"
if m.Response != "" {
content = m.Response
}
return &llms.ContentResponse{
Choices: []*llms.ContentChoice{
{
Content: content,
},
},
}, nil
}
// Mock templates for testing
const (
testTitleTemplate = `
Language: {{.Language}}
Title: {{.Title}}
Content: {{.Content}}
`
testTagTemplate = `
Language: {{.Language}}
Tags: {{.AvailableTags}}
Content: {{.Content}}
`
testCorrespondentTemplate = `
Language: {{.Language}}
Content: {{.Content}}
`
testCreatedDateContentTemplate = `
Language: {{.Language}}
Content: {{.Content}}
`
)
func TestPromptTokenLimits(t *testing.T) {
testLogger := logrus.WithField("test", "test")
// Initialize test templates
var err error
titleTemplate, err = template.New("title").Parse(testTitleTemplate)
require.NoError(t, err)
tagTemplate, err = template.New("tag").Parse(testTagTemplate)
require.NoError(t, err)
correspondentTemplate, err = template.New("correspondent").Parse(testCorrespondentTemplate)
require.NoError(t, err)
createdDateTemplate, err = template.New("created_date").Parse(testCreatedDateContentTemplate)
require.NoError(t, err)
// Save current env and restore after test
originalLimit := os.Getenv("TOKEN_LIMIT")
defer os.Setenv("TOKEN_LIMIT", originalLimit)
// Create a test app with mock LLM
mockLLM := &mockLLM{}
app := &App{
LLM: mockLLM,
}
// Set up test template
testTemplate := template.Must(template.New("test").Parse(`
Language: {{.Language}}
Content: {{.Content}}
`))
tests := []struct {
name string
tokenLimit int
content string
}{
{
name: "no limit",
tokenLimit: 0,
content: "This is the original content that should not be truncated.",
},
{
name: "content within limit",
tokenLimit: 100,
content: "Short content",
},
{
name: "content exceeds limit",
tokenLimit: 50,
content: "This is a much longer content that should definitely be truncated to fit within token limits",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
// Set token limit for this test
os.Setenv("TOKEN_LIMIT", fmt.Sprintf("%d", tc.tokenLimit))
resetTokenLimit()
// Prepare test data
data := map[string]interface{}{
"Language": "English",
}
// Calculate available tokens
availableTokens, err := getAvailableTokensForContent(testTemplate, data)
require.NoError(t, err)
// Truncate content if needed
truncatedContent, err := truncateContentByTokens(tc.content, availableTokens)
require.NoError(t, err)
// Test with the app's LLM
ctx := context.Background()
_, err = app.getSuggestedTitle(ctx, truncatedContent, "Test Title", testLogger)
require.NoError(t, err)
// Verify truncation
if tc.tokenLimit > 0 {
// Count tokens in final prompt received by LLM
splitter := textsplitter.NewTokenSplitter()
tokens, err := splitter.SplitText(mockLLM.lastPrompt)
require.NoError(t, err)
// Verify prompt is within limits
assert.LessOrEqual(t, len(tokens), tc.tokenLimit,
"Final prompt should be within token limit")
if len(tc.content) > len(truncatedContent) {
// Content was truncated
t.Logf("Content truncated from %d to %d characters",
len(tc.content), len(truncatedContent))
}
} else {
// No limit set, content should be unchanged
assert.Contains(t, mockLLM.lastPrompt, tc.content,
"Original content should be in prompt when no limit is set")
}
})
}
}
func TestTokenLimitInCorrespondentGeneration(t *testing.T) {
// Save current env and restore after test
originalLimit := os.Getenv("TOKEN_LIMIT")
defer os.Setenv("TOKEN_LIMIT", originalLimit)
// Create a test app with mock LLM
mockLLM := &mockLLM{}
app := &App{
LLM: mockLLM,
}
// Test content that would exceed reasonable token limits
longContent := "This is a very long content that would normally exceed token limits. " +
"It contains multiple sentences and should be truncated appropriately " +
"based on the token limit that we set."
// Set a small token limit
os.Setenv("TOKEN_LIMIT", "50")
resetTokenLimit()
// Call getSuggestedCorrespondent
ctx := context.Background()
availableCorrespondents := []string{"Test Corp", "Example Inc"}
correspondentBlackList := []string{"Blocked Corp"}
_, err := app.getSuggestedCorrespondent(ctx, longContent, "Test Title", availableCorrespondents, correspondentBlackList)
require.NoError(t, err)
// Verify the final prompt size
splitter := textsplitter.NewTokenSplitter()
tokens, err := splitter.SplitText(mockLLM.lastPrompt)
require.NoError(t, err)
// Final prompt should be within token limit
assert.LessOrEqual(t, len(tokens), 50, "Final prompt should be within token limit")
}
func TestTokenLimitInTagGeneration(t *testing.T) {
testLogger := logrus.WithField("test", "test")
// Save current env and restore after test
originalLimit := os.Getenv("TOKEN_LIMIT")
defer os.Setenv("TOKEN_LIMIT", originalLimit)
// Create a test app with mock LLM
mockLLM := &mockLLM{}
app := &App{
LLM: mockLLM,
}
// Test content that would exceed reasonable token limits
longContent := "This is a very long content that would normally exceed token limits. " +
"It contains multiple sentences and should be truncated appropriately."
// Set a small token limit
os.Setenv("TOKEN_LIMIT", "50")
resetTokenLimit()
// Call getSuggestedTags
ctx := context.Background()
availableTags := []string{"test", "example"}
originalTags := []string{"original"}
_, err := app.getSuggestedTags(ctx, longContent, "Test Title", availableTags, originalTags, testLogger)
require.NoError(t, err)
// Verify the final prompt size
splitter := textsplitter.NewTokenSplitter()
tokens, err := splitter.SplitText(mockLLM.lastPrompt)
require.NoError(t, err)
// Final prompt should be within token limit
assert.LessOrEqual(t, len(tokens), 50, "Final prompt should be within token limit")
}
func TestTokenLimitInTitleGeneration(t *testing.T) {
testLogger := logrus.WithField("test", "test")
// Save current env and restore after test
originalLimit := os.Getenv("TOKEN_LIMIT")
defer os.Setenv("TOKEN_LIMIT", originalLimit)
// Create a test app with mock LLM
mockLLM := &mockLLM{}
app := &App{
LLM: mockLLM,
}
// Test content that would exceed reasonable token limits
longContent := "This is a very long content that would normally exceed token limits. " +
"It contains multiple sentences and should be truncated appropriately."
// Set a small token limit
os.Setenv("TOKEN_LIMIT", "50")
resetTokenLimit()
// Call getSuggestedTitle
ctx := context.Background()
_, err := app.getSuggestedTitle(ctx, longContent, "Original Title", testLogger)
require.NoError(t, err)
// Verify the final prompt size
splitter := textsplitter.NewTokenSplitter()
tokens, err := splitter.SplitText(mockLLM.lastPrompt)
require.NoError(t, err)
// Final prompt should be within token limit
assert.LessOrEqual(t, len(tokens), 50, "Final prompt should be within token limit")
}
func TestTokenLimitInCreatedDateGeneration(t *testing.T) {
testLogger := logrus.WithField("test", "test")
// Save current env and restore after test
originalLimit := os.Getenv("TOKEN_LIMIT")
defer os.Setenv("TOKEN_LIMIT", originalLimit)
// Create a test app with mock LLM
mockLLM := &mockLLM{}
app := &App{
LLM: mockLLM,
}
// Test content that would exceed reasonable token limits
longContent := "This is a very long content that would normally exceed token limits. " +
"It contains multiple sentences and should be truncated appropriately."
// Set a small token limit
os.Setenv("TOKEN_LIMIT", "50")
resetTokenLimit()
// Call getSuggestedCreatedDate
ctx := context.Background()
_, err := app.getSuggestedCreatedDate(ctx, longContent, testLogger)
require.NoError(t, err)
// Verify the final prompt size
splitter := textsplitter.NewTokenSplitter()
tokens, err := splitter.SplitText(mockLLM.lastPrompt)
require.NoError(t, err)
// Final prompt should be within token limit
assert.LessOrEqual(t, len(tokens), 50, "Final prompt should be within token limit")
}
func TestStripReasoning(t *testing.T) {
tests := []struct {
name string
input string
expected string
}{
{
name: "No reasoning tags",
input: "This is a test content without reasoning tags.",
expected: "This is a test content without reasoning tags.",
},
{
name: "Reasoning tags at the start",
input: "<think>Start reasoning</think>\n\nContent \n\n",
expected: "Content",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
result := stripReasoning(tc.input)
assert.Equal(t, tc.expected, result)
})
}
}
// mockPaperlessClient is a mock implementation of the ClientInterface for testing.
type mockPaperlessClient struct {
CustomFields []CustomField
Error error
}
func (m *mockPaperlessClient) GetCustomFields(ctx context.Context) ([]CustomField, error) {
if m.Error != nil {
return nil, m.Error
}
return m.CustomFields, nil
}
// Implement other methods of the interface with empty bodies as they are not needed for this test.
func (m *mockPaperlessClient) GetDocumentsByTags(ctx context.Context, tags []string, pageSize int) ([]Document, error) {
return nil, nil
}
func (m *mockPaperlessClient) UpdateDocuments(ctx context.Context, documents []DocumentSuggestion, db *gorm.DB, isUndo bool) error {
return nil
}
func (m *mockPaperlessClient) GetDocument(ctx context.Context, documentID int) (Document, error) {
return Document{}, nil
}
func (m *mockPaperlessClient) GetAllTags(ctx context.Context) (map[string]int, error) {
return nil, nil
}
func (m *mockPaperlessClient) GetAllCorrespondents(ctx context.Context) (map[string]int, error) {
return nil, nil
}
func (m *mockPaperlessClient) GetAllDocumentTypes(ctx context.Context) ([]DocumentType, error) {
return nil, nil
}
func (m *mockPaperlessClient) CreateTag(ctx context.Context, tagName string) (int, error) {
return 0, nil
}
func (m *mockPaperlessClient) DownloadDocumentAsImages(ctx context.Context, documentID int, pageLimit int) ([]string, int, error) {
return nil, 0, nil
}
func (m *mockPaperlessClient) DownloadDocumentAsPDF(ctx context.Context, documentID int, limitPages int, split bool) ([]string, []byte, int, error) {
return nil, nil, 0, nil
}
func (m *mockPaperlessClient) UploadDocument(ctx context.Context, data []byte, filename string, metadata map[string]interface{}) (string, error) {
return "", nil
}
func (m *mockPaperlessClient) GetTaskStatus(ctx context.Context, taskID string) (map[string]interface{}, error) {
return nil, nil
}
func (m *mockPaperlessClient) DeleteDocument(ctx context.Context, documentID int) error { return nil }
func TestGetSuggestedCustomFields(t *testing.T) {
// 1. Setup
mockedLLMResponse := `
[
{
"field": "Invoice Number",
"value": "INV-12345"
},
{
"field": "Due Date",
"value": "2025-12-31"
},
{
"field": "NonExistentField",
"value": "Some Value"
}
]
`
mockClient := &mockPaperlessClient{
CustomFields: []CustomField{
{ID: 1, Name: "Invoice Number", DataType: "string"},
{ID: 2, Name: "Due Date", DataType: "date"},
{ID: 3, Name: "Amount", DataType: "float"},
},
}
app := &App{
LLM: &mockLLM{Response: mockedLLMResponse},
Client: mockClient,
}
// Create a dummy template file as loadTemplates() will be called
err := os.MkdirAll("prompts", 0755)
require.NoError(t, err)
err = os.WriteFile("prompts/custom_field_prompt.tmpl", []byte("test"), 0644)
require.NoError(t, err)
defer os.RemoveAll("prompts")
err = loadTemplates()
require.NoError(t, err)
// 2. Define Inputs
doc := Document{
Content: "The invoice number is INV-12345 and the due date is 2025-12-31.",
}
selectedFieldIDs := []int{1, 2} // User has selected "Invoice Number" and "Due Date"
// 3. Execute
testLogger := logrus.WithField("test", "TestGetSuggestedCustomFields")
suggestions, err := app.getSuggestedCustomFields(context.Background(), doc, selectedFieldIDs, testLogger)
// 4. Assert
require.NoError(t, err)
require.NotNil(t, suggestions)
assert.Len(t, suggestions, 2, "Should return 2 suggestions, ignoring the non-existent one")
// Check Invoice Number
invoiceField, ok := findFieldByID(suggestions, 1)
assert.True(t, ok, "Invoice Number (ID 1) should be in the suggestions")
assert.Equal(t, "INV-12345", invoiceField.Value)
// Check Due Date
dueDateField, ok := findFieldByID(suggestions, 2)
assert.True(t, ok, "Due Date (ID 2) should be in the suggestions")
assert.Equal(t, "2025-12-31", dueDateField.Value)
}
// Helper function to find a custom field by ID in a slice
func findFieldByID(fields []CustomFieldSuggestion, id int) (CustomFieldSuggestion, bool) {
for _, field := range fields {
if field.ID == id {
return field, true
}
}
return CustomFieldSuggestion{}, false
}