Repository navigation
Expand file tree
/
Copy pathtest_openwebui_pipe.py
More file actions
569 lines (484 loc) · 17.2 KB
/
Copy pathtest_openwebui_pipe.py
File metadata and controls
569 lines (484 loc) · 17.2 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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
import asyncio
import builtins
import importlib.util
import sys
import types
from pathlib import Path
import pytest
REPO_ROOT = Path(__file__).resolve().parents[2]
MODULE_PATH = (
REPO_ROOT
/ "python"
/ "reference_integrations"
/ "openwebui_pipe"
/ "open_webui_pipe.py"
)
def _load_module_with_stubs(module_name: str, monkeypatch: pytest.MonkeyPatch):
fastapi_mod = types.ModuleType("fastapi")
class _Request:
pass
fastapi_mod.Request = _Request
open_webui_mod = types.ModuleType("open_webui")
open_webui_models_mod = types.ModuleType("open_webui.models")
open_webui_models_users_mod = types.ModuleType("open_webui.models.users")
open_webui_utils_mod = types.ModuleType("open_webui.utils")
open_webui_utils_chat_mod = types.ModuleType("open_webui.utils.chat")
class _Users:
@staticmethod
def get_user_by_id(user_id: object) -> dict[str, object]:
return {"id": user_id}
async def _chat_completion(
_: object, payload: dict[str, object], __: object
) -> dict[str, object]:
return {"choices": [{"message": {"content": payload.get("_mock_content", "")}}]}
open_webui_models_users_mod.Users = _Users
open_webui_utils_chat_mod.generate_chat_completion = _chat_completion
monkeypatch.setitem(sys.modules, "fastapi", fastapi_mod)
monkeypatch.setitem(sys.modules, "open_webui", open_webui_mod)
monkeypatch.setitem(sys.modules, "open_webui.models", open_webui_models_mod)
monkeypatch.setitem(
sys.modules, "open_webui.models.users", open_webui_models_users_mod
)
monkeypatch.setitem(sys.modules, "open_webui.utils", open_webui_utils_mod)
monkeypatch.setitem(sys.modules, "open_webui.utils.chat", open_webui_utils_chat_mod)
real_import = builtins.__import__
def _guarded_import(
name: str,
globals_: dict[str, object] | None = None,
locals_: dict[str, object] | None = None,
fromlist: tuple[str, ...] = (),
level: int = 0,
) -> object:
if name == "pydantic":
raise ModuleNotFoundError("No module named 'pydantic'")
return real_import(name, globals_, locals_, fromlist, level)
monkeypatch.setattr(builtins, "__import__", _guarded_import)
spec = importlib.util.spec_from_file_location(module_name, MODULE_PATH)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
module._ENGINES_BY_CHAT_KEY.clear()
module._CHECKPOINTS_BY_CHAT_KEY.clear()
return module
def test_import_works_without_pydantic(monkeypatch) -> None:
module = _load_module_with_stubs("owui_import_no_pydantic", monkeypatch)
pipe = module.Pipe()
assert pipe.valves.BASE_MODEL_ID == ""
def test_missing_base_model_id_returns_deterministic_misconfiguration_message(
monkeypatch,
) -> None:
module = _load_module_with_stubs("owui_missing_base_model", monkeypatch)
pipe = module.Pipe()
pipe.valves.BASE_MODEL_ID = ""
result = asyncio.run(
pipe.pipe(
{"model": "pipe-model", "messages": [{"role": "user", "content": "hello"}]},
__user__={"id": "u1"},
__request__=object(),
)
)
assert result == "Context Compiler pipe misconfigured: BASE_MODEL_ID is required."
def test_recursive_base_model_id_returns_deterministic_recursion_guard_message(
monkeypatch,
) -> None:
module = _load_module_with_stubs("owui_recursion_guard", monkeypatch)
pipe = module.Pipe()
pipe.valves.BASE_MODEL_ID = "pipe-model"
result = asyncio.run(
pipe.pipe(
{"model": "pipe-model", "messages": [{"role": "user", "content": "hello"}]},
__user__={"id": "u1"},
__request__=object(),
)
)
assert result == (
"Context Compiler pipe misconfigured: BASE_MODEL_ID must not match "
"the selected pipe model id to avoid recursive routing."
)
def test_checkpoint_restore_and_persist_across_chat_ids(monkeypatch) -> None:
module = _load_module_with_stubs("owui_checkpoint_restore", monkeypatch)
pipe = module.Pipe()
pipe.valves.BASE_MODEL_ID = "base-model"
first = asyncio.run(
pipe.pipe(
{
"model": "pipe-model",
"messages": [
{"role": "user", "content": "use docker instead of kubectl"}
],
},
__user__={"id": "u1"},
__request__=object(),
__chat_id__="chat-1",
)
)
assert first == 'Did you mean to use "docker" instead?'
checkpoint = module._CHECKPOINTS_BY_CHAT_KEY["chat-1"]
module._ENGINES_BY_CHAT_KEY.clear()
second = asyncio.run(
pipe.pipe(
{"model": "pipe-model", "messages": [{"role": "user", "content": "yes"}]},
__user__={"id": "u1"},
__request__=object(),
__chat_id__="chat-1",
)
)
other_chat = asyncio.run(
pipe.pipe(
{
"model": "pipe-model",
"messages": [{"role": "user", "content": "show state"}],
},
__user__={"id": "u1"},
__request__=object(),
__chat_id__="chat-2",
)
)
assert second == "State updated."
assert checkpoint != module._CHECKPOINTS_BY_CHAT_KEY["chat-1"]
assert (
other_chat
== "Premise: none\nUse: none\nProhibit: none\nPending clarification: no"
)
def test_normal_update_returns_local_ack_and_skips_downstream(monkeypatch) -> None:
module = _load_module_with_stubs("owui_update_local_ack", monkeypatch)
forwarded: list[dict[str, object]] = []
async def _forward(
_: object, payload: dict[str, object], __: object
) -> dict[str, object]:
forwarded.append(payload)
return {"ok": True}
module.generate_chat_completion = _forward
pipe = module.Pipe()
pipe.valves.BASE_MODEL_ID = "base-model"
result = asyncio.run(
pipe.pipe(
{
"model": "pipe-model",
"messages": [{"role": "user", "content": "prohibit peanuts"}],
},
__user__={"id": "u1"},
__request__=object(),
__chat_id__="chat-update",
)
)
assert result == "State updated: Prohibit peanuts."
assert forwarded == []
def test_confirmation_resume_returns_local_ack_and_skips_downstream(
monkeypatch,
) -> None:
module = _load_module_with_stubs("owui_confirmation_resume", monkeypatch)
forwarded: list[dict[str, object]] = []
async def _forward(
_: object, payload: dict[str, object], __: object
) -> dict[str, object]:
forwarded.append(payload)
return {"ok": True}
module.generate_chat_completion = _forward
pipe = module.Pipe()
pipe.valves.BASE_MODEL_ID = "base-model"
chat_id = "chat-confirm"
clarify = asyncio.run(
pipe.pipe(
{
"model": "pipe-model",
"messages": [
{"role": "user", "content": "use docker instead of kubectl"}
],
},
__user__={"id": "u1"},
__request__=object(),
__chat_id__=chat_id,
)
)
resumed = asyncio.run(
pipe.pipe(
{"model": "pipe-model", "messages": [{"role": "user", "content": "yes"}]},
__user__={"id": "u1"},
__request__=object(),
__chat_id__=chat_id,
)
)
assert clarify == 'Did you mean to use "docker" instead?'
assert resumed == "State updated."
assert forwarded == []
def test_exact_show_state_is_local_and_non_exact_forwards_normally(monkeypatch) -> None:
module = _load_module_with_stubs("owui_show_state", monkeypatch)
forwarded: list[dict[str, object]] = []
async def _forward(
_: object, payload: dict[str, object], __: object
) -> dict[str, object]:
forwarded.append(payload)
return {"choices": [{"message": {"content": "downstream"}}]}
module.generate_chat_completion = _forward
pipe = module.Pipe()
pipe.valves.BASE_MODEL_ID = "base-model"
exact = asyncio.run(
pipe.pipe(
{
"model": "pipe-model",
"messages": [{"role": "user", "content": "show state"}],
},
__user__={"id": "u1"},
__request__=object(),
__chat_id__="chat-show",
)
)
non_exact = asyncio.run(
pipe.pipe(
{
"model": "pipe-model",
"messages": [{"role": "user", "content": "show state please"}],
},
__user__={"id": "u1"},
__request__=object(),
__chat_id__="chat-show",
)
)
assert (
exact == "Premise: none\nUse: none\nProhibit: none\nPending clarification: no"
)
assert non_exact == {"choices": [{"message": {"content": "downstream"}}]}
assert len(forwarded) == 1
def test_near_miss_directive_clarify_returns_deterministic_text_and_skips_downstream(
monkeypatch,
) -> None:
module = _load_module_with_stubs("owui_near_miss", monkeypatch)
forwarded: list[dict[str, object]] = []
async def _forward(
_: object, payload: dict[str, object], __: object
) -> dict[str, object]:
forwarded.append(payload)
return {"choices": [{"message": {"content": "downstream"}}]}
module.generate_chat_completion = _forward
pipe = module.Pipe()
pipe.valves.BASE_MODEL_ID = "base-model"
result = asyncio.run(
pipe.pipe(
{
"model": "pipe-model",
"messages": [
{"role": "user", "content": "set premise to concise replies"}
],
},
__user__={"id": "u1"},
__request__=object(),
__chat_id__="chat-near-miss",
)
)
assert result == "Invalid premise syntax.\nUse 'set premise <value>'."
assert forwarded == []
def test_passthrough_with_non_empty_state_injects_exactly_one_cc_state_system_message(
monkeypatch,
) -> None:
module = _load_module_with_stubs("owui_passthrough_inject", monkeypatch)
forwarded: list[dict[str, object]] = []
async def _forward(
_: object, payload: dict[str, object], __: object
) -> dict[str, object]:
forwarded.append(payload)
return {"choices": [{"message": {"content": "downstream"}}]}
module.generate_chat_completion = _forward
pipe = module.Pipe()
pipe.valves.BASE_MODEL_ID = "base-model"
chat_id = "chat-passthrough-state"
asyncio.run(
pipe.pipe(
{
"model": "pipe-model",
"messages": [{"role": "user", "content": "use docker"}],
},
__user__={"id": "u1"},
__request__=object(),
__chat_id__=chat_id,
)
)
result = asyncio.run(
pipe.pipe(
{
"model": "pipe-model",
"messages": [
{"role": "system", "content": "original system"},
{"role": "user", "content": "hello"},
],
},
__user__={"id": "u1"},
__request__=object(),
__chat_id__=chat_id,
)
)
assert result == {"choices": [{"message": {"content": "downstream"}}]}
system_messages = [
message
for message in forwarded[0]["messages"]
if message.get("role") == "system"
]
cc_messages = [
message
for message in system_messages
if isinstance(message.get("content"), str)
and message["content"].startswith("[[cc_state]]")
]
assert len(cc_messages) == 1
def test_passthrough_with_saved_premise_injects_premise_in_cc_state(
monkeypatch,
) -> None:
module = _load_module_with_stubs("owui_passthrough_premise", monkeypatch)
forwarded: list[dict[str, object]] = []
async def _forward(
_: object, payload: dict[str, object], __: object
) -> dict[str, object]:
forwarded.append(payload)
return {"choices": [{"message": {"content": "downstream"}}]}
module.generate_chat_completion = _forward
pipe = module.Pipe()
pipe.valves.BASE_MODEL_ID = "base-model"
chat_id = "chat-premise-state"
asyncio.run(
pipe.pipe(
{
"model": "pipe-model",
"messages": [
{
"role": "user",
"content": "set premise draft is a board update summarizing quarterly results",
}
],
},
__user__={"id": "u1"},
__request__=object(),
__chat_id__=chat_id,
)
)
asyncio.run(
pipe.pipe(
{
"model": "pipe-model",
"messages": [
{"role": "system", "content": "original system"},
{"role": "user", "content": "what should I emphasize?"},
],
},
__user__={"id": "u1"},
__request__=object(),
__chat_id__=chat_id,
)
)
cc_messages = [
message
for message in forwarded[0]["messages"]
if message.get("role") == "system"
and isinstance(message.get("content"), str)
and message["content"].startswith("[[cc_state]]")
]
assert len(cc_messages) == 1
assert (
"Premise: draft is a board update summarizing quarterly results"
in cc_messages[0]["content"]
)
def test_empty_state_passthrough_does_not_inject_compiler_state(monkeypatch) -> None:
module = _load_module_with_stubs("owui_passthrough_empty", monkeypatch)
forwarded: list[dict[str, object]] = []
async def _forward(
_: object, payload: dict[str, object], __: object
) -> dict[str, object]:
forwarded.append(payload)
return {"choices": [{"message": {"content": "downstream"}}]}
module.generate_chat_completion = _forward
pipe = module.Pipe()
pipe.valves.BASE_MODEL_ID = "base-model"
asyncio.run(
pipe.pipe(
{
"model": "pipe-model",
"messages": [
{"role": "system", "content": "original system"},
{"role": "user", "content": "hello"},
],
},
__user__={"id": "u1"},
__request__=object(),
__chat_id__="chat-empty-state",
)
)
assert forwarded[0]["messages"] == [
{"role": "system", "content": "original system"},
{"role": "user", "content": "hello"},
]
def test_repeated_passthrough_does_not_duplicate_compiler_owned_system_message(
monkeypatch,
) -> None:
module = _load_module_with_stubs("owui_passthrough_dedupe", monkeypatch)
forwarded: list[dict[str, object]] = []
async def _forward(
_: object, payload: dict[str, object], __: object
) -> dict[str, object]:
forwarded.append(payload)
return {"choices": [{"message": {"content": "downstream"}}]}
module.generate_chat_completion = _forward
pipe = module.Pipe()
pipe.valves.BASE_MODEL_ID = "base-model"
chat_id = "chat-dedupe"
asyncio.run(
pipe.pipe(
{
"model": "pipe-model",
"messages": [{"role": "user", "content": "use docker"}],
},
__user__={"id": "u1"},
__request__=object(),
__chat_id__=chat_id,
)
)
first_body = {
"model": "pipe-model",
"messages": [
{"role": "system", "content": "original system"},
{"role": "user", "content": "hello"},
],
}
asyncio.run(
pipe.pipe(
first_body, __user__={"id": "u1"}, __request__=object(), __chat_id__=chat_id
)
)
forwarded_messages = forwarded[-1]["messages"]
second_body = {"model": "pipe-model", "messages": forwarded_messages}
asyncio.run(
pipe.pipe(
second_body,
__user__={"id": "u1"},
__request__=object(),
__chat_id__=chat_id,
)
)
cc_messages = [
message
for message in forwarded[-1]["messages"]
if message.get("role") == "system"
and isinstance(message.get("content"), str)
and message["content"].startswith("[[cc_state]]")
]
assert len(cc_messages) == 1
def test_model_not_found_is_normalized(monkeypatch) -> None:
module = _load_module_with_stubs("owui_model_not_found", monkeypatch)
pipe = module.Pipe()
pipe.valves.BASE_MODEL_ID = "base-model"
async def _forward(
_: object, payload: dict[str, object], __: object
) -> dict[str, object]:
return {"error": {"message": "MODEL NOT FOUND"}}
module.generate_chat_completion = _forward
result = asyncio.run(
pipe.pipe(
{"model": "pipe-model", "messages": [{"role": "user", "content": "hello"}]},
__user__={"id": "u1"},
__request__=object(),
__chat_id__="chat-model-not-found",
)
)
assert result == (
"Context Compiler pipe misconfigured: BASE_MODEL_ID is invalid or not "
"configured in Open WebUI. Configure a valid model id in "
"Admin Panel → Settings → Models."
)