Repository navigation
Expand file tree
/
Copy patheval_openai_compatible.py
More file actions
1249 lines (1082 loc) · 42.5 KB
/
Copy patheval_openai_compatible.py
File metadata and controls
1249 lines (1082 loc) · 42.5 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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Simple Python eval for llama-swap Docs Agent against an OpenAI-compatible API.
Connects to an OpenAI-compatible /v1/chat/completions endpoint.
Runs cases in evals/docs-agent/cases/**/*.yaml,
implements the 4 docs tools locally from docs/kb/**/*.md so you don't need Go.
Usage:
python eval_openai_compatible.py
python eval_openai_compatible.py --repo-root /path/to/llama-swap
python eval_openai_compatible.py --model your-model --base-url http://localhost:8080 --group ttl
python eval_openai_compatible.py --group routing --group ttl --only ttl-unload-after-5min
python eval_openai_compatible.py --cases evals/docs-agent/cases --max-iterations 8
"""
import argparse
import json
import re
import time
import sys
import os
import threading
from pathlib import Path
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, as_completed
import yaml
import requests
from requests.exceptions import (
RequestException,
ConnectionError as RequestsConnectionError,
Timeout as RequestsTimeout,
)
SCRIPT_DIR = Path(__file__).resolve().parent
DEFAULT_MODEL = "your-model"
DEFAULT_BASE_URL = "http://localhost:8080"
def find_repo_root(start: Path):
"""
Find the llama-swap repository root by walking upward from `start`.
We look for files/directories that should exist at the repo root.
"""
start = start.resolve()
for candidate in [start, *start.parents]:
if (
(candidate / "config-schema.json").is_file()
and (candidate / "docs" / "kb").is_dir()
and (candidate / "evals" / "docs-agent" / "cases").is_dir()
):
return candidate
return None
DOCS_AGENT_SYSTEM_PROMPT = """You are the llama-swap documentation assistant. You answer questions about llama-swap: how to configure it, what a setting does, and why something is not working.
## Tools
Tools are namespaced by provider.
- `docs__search_docs` - keyword search across all documentation. This is almost always the right first call.
- `docs__list_docs` - the index of every document, with ids, titles and summaries. Use it to browse when a search comes back empty.
- `docs__get_doc` - read one document in full by id. Ids come from the other two tools.
- `docs__get_config_schema` - look up one configuration key by dotted path (for example `models.*.ttl`) to get its type, default and allowed values.
- `config__get_config` - the configuration this server is running right now, with credentials redacted. Use it only when the question is about this specific running setup.
- `sys__now` - the current date and time on the server.
Document ids beginning with `reference/config/` are sections of `config.example.yaml` reproduced verbatim.
## How to answer
1. **Every answer starts with a search.** Call `docs__search_docs` before answering every question, including questions that look familiar or can be answered with the schema. A schema call is not a substitute for the search. llama-swap changes often and its option names are easy to confuse with other projects'.
2. **Keep the important words.** Search with all distinctive parts of the question. For example, a question involving Docker, TTL, and stopping needs all three concepts in the query; do not reduce it to only "ttl unload".
3. **Read enough to answer every part.** If a result is truncated, or a question asks what to set *and* what else to check, call `docs__get_doc` and verify that the final answer addresses each part.
4. **Verify key names.** Before you state a configuration key's default, type, or allowed values, confirm it with `docs__get_config_schema`. If the requested schema path is unknown, explicitly say that the requested key does not exist before naming any real alternative.
5. **Show working YAML.** Most questions are best answered with a short, pasteable `yaml` block plus a sentence about what it does. Copy examples from the documentation; the schema describes shape and types but is not a source of working commands.
6. **Say when you do not know.** If the documentation does not cover something, say so plainly and name the closest thing that does exist. Never invent a configuration key, a CLI flag, or an endpoint to fill a gap. "llama-swap does not have that" is a correct and useful answer.
7. **Be brief.** Answer the question that was asked. No preamble, no summary of what you are about to do, no restating the question."""
# ---------- docs index ----------
class DocStore:
def __init__(self, kb_root: Path):
self.kb_root = kb_root
self.docs = [] # list of {id,title,summary,content,path}
self.by_id = {}
self._load()
def _parse_frontmatter(self, text: str):
if text.startswith("---"):
end = text.find("\n---", 3)
if end != -1:
fm_text = text[3:end]
try:
fm = yaml.safe_load(fm_text) or {}
except:
fm = {}
body = text[end+4:].lstrip("\n")
return fm, body
return {}, text
def _load(self):
for p in sorted(self.kb_root.rglob("*.md")):
rel = p.relative_to(self.kb_root)
doc_id = str(rel.with_suffix("")).replace("\\","/")
text = p.read_text(encoding="utf-8", errors="ignore")
fm, body = self._parse_frontmatter(text)
title = fm.get("title") or doc_id
summary = fm.get("summary") or body[:200].strip()
# also scan reference/config docs
self.docs.append({"id": doc_id, "title": title, "summary": summary, "content": text, "path": p, "fm": fm})
self.by_id[doc_id] = {"id": doc_id, "title": title, "summary": summary, "content": text}
# also load config-schema as reference docs?
# Keep sorted for deterministic list
def list_docs(self):
return [{"id": d["id"], "title": d["title"], "summary": d["summary"]} for d in self.docs]
def get_doc(self, doc_id: str):
# normalize
doc_id = doc_id.strip().removesuffix(".md")
if doc_id in self.by_id:
return self.by_id[doc_id]["content"]
# try fallback with .md
for d in self.docs:
if d["id"] == doc_id:
return d["content"]
return None
def search(self, query: str, top_k=5):
tokens = [t.lower() for t in re.findall(r"[a-zA-Z0-9_.-]+", query) if len(t) >= 2]
if not tokens:
tokens = query.lower().split()
scored = []
for d in self.docs:
content_lower = d["content"].lower()
title_lower = d["title"].lower()
score = 0
for tok in tokens:
# weight title higher
c = content_lower.count(tok)
t = title_lower.count(tok) * 5
score += c + t
# bonus if all tokens present
if all(tok in content_lower for tok in tokens):
score += 10
if score > 0:
# snippet: find first occurrence
idx = -1
for tok in tokens:
i = content_lower.find(tok)
if i != -1:
if idx == -1 or i < idx:
idx = i
snippet = d["content"][max(0, idx-200): idx+800] if idx != -1 else d["content"][:800]
scored.append((score, d, snippet))
scored.sort(key=lambda x: x[0], reverse=True)
results = []
for score, d, snippet in scored[:top_k]:
results.append({"id": d["id"], "title": d["title"], "summary": d["summary"], "score": score, "snippet": snippet[:1000]})
return results
# ---------- config schema ----------
class ConfigSchema:
def __init__(self, path: Path):
self.data = json.loads(path.read_text(encoding="utf-8"))
def get(self, dotted: str):
# examples: models.*.ttl , globalTTL, routing.router.use
parts = dotted.split(".")
# walk
cur = self.data
# try direct traversal
def resolve(node, idx):
if idx >= len(parts):
return node
key = parts[idx]
if key == "*":
# wildcard: look into additionalProperties
if isinstance(node, dict):
ap = node.get("additionalProperties")
if ap:
return resolve(ap, idx+1)
# for definitions refs
props = node.get("properties")
if props:
# ambiguous, return whole node
return node
return None
# normal key
if isinstance(node, dict):
# check properties
if "properties" in node and key in node["properties"]:
return resolve(node["properties"][key], idx+1)
# check $ref
if "$ref" in node:
# resolve ref
ref = node["$ref"]
if ref.startswith("#/definitions/"):
def_name = ref.split("/")[-1]
target = self.data.get("definitions", {}).get(def_name)
if target:
# restart resolution from target with same remaining
return resolve(target, idx)
if ref.startswith("#/properties/"):
pass
# fallback: follow ref's properties
# direct key
if key in node:
return resolve(node[key], idx+1)
# definitions
if "definitions" in node and key in node["definitions"]:
return resolve(node["definitions"][key], idx+1)
return None
# first try simple lookup by scanning properties recursively
# brute force: search for key name in schema description
node = resolve(cur, 0)
if node is not None and isinstance(node, dict) and ("description" in node or "type" in node):
return node
# fallback: search by last part name in definitions/properties
last = parts[-1]
# search in definitions and top properties
for container in [self.data.get("properties", {}), self.data.get("definitions", {})]:
if last in container:
return container[last]
for v in container.values():
if isinstance(v, dict) and "properties" in v and last in v["properties"]:
return v["properties"][last]
return None
class APIError(RuntimeError):
"""Structured error from the OpenAI-compatible API."""
def __init__(self, message, *, kind="api_error", status_code=None, url=None, retryable=False):
super().__init__(message)
self.kind = kind
self.status_code = status_code
self.url = url
self.retryable = retryable
def __str__(self):
return str(self.args[0])
# ---------- OpenAI-compatible client ----------
def openai_compatible_chat(
base_url,
model,
messages,
tools,
temperature=0,
api_key=None,
timeout=300,
retries=2,
):
url = base_url.rstrip("/") + "/v1/chat/completions"
body = {
"model": model,
"messages": messages,
"temperature": temperature,
"stream": False,
}
if tools:
body["tools"] = tools
body["tool_choice"] = "auto"
headers = {}
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
last_error = None
for attempt in range(retries + 1):
try:
resp = requests.post(
url,
json=body,
headers=headers,
timeout=timeout,
)
except RequestsTimeout as e:
last_error = APIError(
f"request timed out after {timeout}s: {url}",
kind="timeout",
url=url,
retryable=True,
)
except RequestsConnectionError as e:
last_error = APIError(
f"cannot connect to {url}: {e}",
kind="connection_error",
url=url,
retryable=True,
)
except RequestException as e:
last_error = APIError(
f"HTTP request failed for {url}: {e}",
kind="request_error",
url=url,
retryable=False,
)
else:
if resp.status_code >= 400:
# Some APIs return useful JSON error messages.
try:
error_data = resp.json()
error_text = json.dumps(error_data, ensure_ascii=False)
except ValueError:
error_text = resp.text.strip()
error_text = error_text[:1000]
retryable = resp.status_code in {408, 429, 500, 502, 503, 504}
last_error = APIError(
f"API returned HTTP {resp.status_code}: {error_text}",
kind="http_error",
status_code=resp.status_code,
url=url,
retryable=retryable,
)
else:
try:
data = resp.json()
except ValueError as e:
raise APIError(
f"API returned invalid JSON from {url}: {e}; "
f"body={resp.text[:500]!r}",
kind="invalid_json",
status_code=resp.status_code,
url=url,
)
if not isinstance(data, dict):
raise APIError(
f"API returned unexpected response type "
f"{type(data).__name__}, expected object",
kind="invalid_response",
status_code=resp.status_code,
url=url,
)
choices = data.get("choices")
if not isinstance(choices, list) or not choices:
raise APIError(
f"API response has no choices: "
f"{json.dumps(data, ensure_ascii=False)[:1000]}",
kind="invalid_response",
status_code=resp.status_code,
url=url,
)
first = choices[0]
if not isinstance(first, dict):
raise APIError(
f"API response choices[0] is not an object: "
f"{type(first).__name__}",
kind="invalid_response",
status_code=resp.status_code,
url=url,
)
message = first.get("message")
if not isinstance(message, dict):
raise APIError(
f"API response choices[0].message is missing or invalid",
kind="invalid_response",
status_code=resp.status_code,
url=url,
)
return message
# Retry only transient failures.
if last_error and last_error.retryable and attempt < retries:
# Exponential backoff: 1s, 2s, ...
delay = 2 ** attempt
time.sleep(delay)
continue
break
raise last_error
# ---------- tool definitions ----------
TOOL_DEFS = [
{"type":"function","function":{"name":"docs__search_docs","description":"Keyword search across all documentation. Almost always the right first call.","parameters":{"type":"object","properties":{"query":{"type":"string","description":"Search query with distinctive keywords"}},"required":["query"]}}},
{"type":"function","function":{"name":"docs__list_docs","description":"Index of every document with ids, titles and summaries.","parameters":{"type":"object","properties":{}}}},
{"type":"function","function":{"name":"docs__get_doc","description":"Read one document in full by id.","parameters":{"type":"object","properties":{"id":{"type":"string","description":"Document id from search/list"}},"required":["id"]}}},
{"type":"function","function":{"name":"docs__get_config_schema","description":"Look up configuration key by dotted path e.g. models.*.ttl","parameters":{"type":"object","properties":{"path":{"type":"string","description":"Dotted config path"}},"required":["path"]}}},
{"type":"function","function":{"name":"config__get_config","description":"Current server config (redacted). Only for questions about this running setup.","parameters":{"type":"object","properties":{}}}},
{"type":"function","function":{"name":"sys__now","description":"Current date/time on server.","parameters":{"type":"object","properties":{}}}},
]
def execute_tool(name, args, doc_store: DocStore, cfg_schema: ConfigSchema):
try:
if name == "docs__search_docs":
q = args.get("query","")
results = doc_store.search(q, top_k=5)
if not results:
return json.dumps({"results":[],"message":"No matches. Try docs__list_docs or different keywords."}, indent=2)
# format concisely
out = []
for r in results:
out.append(f"ID: {r['id']}\nTitle: {r['title']}\nSummary: {r['summary']}\nSnippet: {r['snippet'][:600]}\n---")
return "\n".join(out)
elif name == "docs__list_docs":
lst = doc_store.list_docs()
return json.dumps(lst[:60], indent=2) # truncate
elif name == "docs__get_doc":
doc_id = args.get("id","")
content = doc_store.get_doc(doc_id)
if content is None:
return f"Error: unknown doc id '{doc_id}'. Use docs__search_docs or docs__list_docs to find valid ids."
return content[:8000] # truncate
elif name == "docs__get_config_schema":
path = args.get("path","")
node = cfg_schema.get(path)
if node is None:
return f"Error: unknown config path '{path}'. No such key exists."
return json.dumps(node, indent=2)
elif name == "config__get_config":
return json.dumps({"models":{},"globalTTL":0,"note":"dummy config for eval - not the real server config"}, indent=2)
elif name == "sys__now":
return datetime.now().isoformat()
else:
return f"Error: unknown tool {name}"
except Exception as e:
return f"Error executing {name}: {e}"
# ---------- case loading ----------
def load_cases(cases_dir: Path):
cases = []
for p in sorted(cases_dir.rglob("*.yaml")):
if not p.is_file():
continue
rel = str(p.relative_to(cases_dir))
group = Path(rel).parts[0] if "/" in rel or "\\" in rel else "default"
data = yaml.safe_load(p.read_text(encoding="utf-8"))
if not data:
continue
for idx, raw in enumerate(data):
# normalize like cases.ts does
c = {
"id": raw.get("id"),
"question": raw.get("question"),
"tags": raw.get("tags") or [],
"expect_regex": raw.get("expect_regex") or [],
"expect_any": raw.get("expect_any") or [],
"forbid_regex": raw.get("forbid_regex") or [],
"expect_tools": raw.get("expect_tools") or [],
"expect_tools_any": raw.get("expect_tools_any") or [],
"forbid_tools": raw.get("forbid_tools") or [],
"require_tools": raw.get("require_tools") is True,
"max_iterations": raw.get("max_iterations"),
"group": group,
"file": rel,
"reference": raw.get("reference") or "",
}
# validation: at least one assertion
has = len(c["expect_regex"])+len(c["expect_any"])+len(c["forbid_regex"])+len(c["expect_tools"])+len(c["expect_tools_any"])+len(c["forbid_tools"])
if has==0 and c["max_iterations"] is None and not c["require_tools"]:
print(f"WARN {rel}[{c['id']}] has no assertions", file=sys.stderr)
cases.append(c)
# check duplicates
seen={}
for c in cases:
if c["id"] in seen:
raise SystemExit(f"duplicate id {c['id']} in {seen[c['id']]} and {c['file']}")
seen[c["id"]]=c["file"]
return cases
# ---------- grading ----------
def grade_case(case, answer: str, tool_calls: list, iterations: int, error=None):
assertions=[]
called = set(t["name"] for t in tool_calls)
if error:
assertions.append(("no_error", error, False))
if case["max_iterations"] is not None and iterations > case["max_iterations"]:
assertions.append(("max_iterations", f"{iterations} <= {case['max_iterations']}", False))
elif case["max_iterations"] is not None:
assertions.append(("max_iterations", f"{iterations} <= {case['max_iterations']}", True))
def matches(pat, text):
try:
return re.search(pat, text, re.IGNORECASE) is not None
except re.error:
return pat.lower() in text.lower()
for pat in case["expect_regex"]:
ok = matches(pat, answer)
assertions.append(("expect_regex", pat, ok))
if case["expect_any"]:
ok = any(matches(p, answer) for p in case["expect_any"])
assertions.append(("expect_any", " | ".join(case["expect_any"]), ok))
for pat in case["forbid_regex"]:
ok = not matches(pat, answer)
assertions.append(("forbid_regex", pat, ok))
for name in case["expect_tools"]:
ok = name in called
assertions.append(("expect_tool", name, ok))
if case["expect_tools_any"]:
ok = any(n in called for n in case["expect_tools_any"])
assertions.append(("expect_tools_any", " | ".join(case["expect_tools_any"]), ok))
for name in case["forbid_tools"]:
ok = name not in called
assertions.append(("forbid_tool", name, ok))
if case["require_tools"]:
ok = len(tool_calls)>0
assertions.append(("require_tools", "answered without calling any tool", ok))
passed = all(ok for _,_,ok in assertions)
return assertions, passed
# ---------- agent loop ----------
def run_case(
base_url,
model,
question,
doc_store,
cfg_schema,
max_iterations=8,
temperature=0,
api_key=None,
timeout=300,
retries=2,
):
messages = [
{"role": "system", "content": DOCS_AGENT_SYSTEM_PROMPT},
{"role": "user", "content": question},
]
tool_calls_log = []
iterations = 0
answer = ""
error = None
for it in range(1, max_iterations + 1):
iterations = it
try:
msg = openai_compatible_chat(
base_url,
model,
messages,
TOOL_DEFS,
temperature=temperature,
api_key=api_key,
timeout=timeout,
retries=retries,
)
except APIError as e:
error = f"{e.kind}: {e}"
break
except Exception as e:
# Last-resort protection. A single malformed case should never
# crash the entire evaluator.
error = f"unexpected_error: {type(e).__name__}: {e}"
break
if not isinstance(msg, dict):
error = (
f"invalid_message: expected object, "
f"got {type(msg).__name__}"
)
break
tool_calls = msg.get("tool_calls") or []
content = msg.get("content") or ""
if not isinstance(tool_calls, list):
error = "invalid_response: tool_calls is not a list"
break
if not isinstance(content, str):
content = str(content)
assistant_msg = {
"role": "assistant",
"content": content,
}
if tool_calls:
assistant_msg["tool_calls"] = tool_calls
messages.append(assistant_msg)
if not tool_calls:
answer = content
break
for tc_index, tc in enumerate(tool_calls):
try:
if not isinstance(tc, dict):
raise ValueError(
f"tool call {tc_index} is not an object"
)
function = tc.get("function")
if not isinstance(function, dict):
raise ValueError(
f"tool call {tc_index} has no valid function object"
)
fname = function.get("name")
if not fname:
raise ValueError(
f"tool call {tc_index} has no function name"
)
raw_args = function.get("arguments", "{}")
if isinstance(raw_args, dict):
args = raw_args
elif isinstance(raw_args, str):
if raw_args.strip():
try:
args = json.loads(raw_args)
except json.JSONDecodeError as e:
# Don't silently turn malformed arguments into {}.
raise ValueError(
f"invalid JSON arguments for {fname}: {e}"
)
else:
args = {}
else:
raise ValueError(
f"arguments for {fname} have invalid type "
f"{type(raw_args).__name__}"
)
if not isinstance(args, dict):
raise ValueError(
f"arguments for {fname} must be an object, "
f"got {type(args).__name__}"
)
result = execute_tool(
fname,
args,
doc_store,
cfg_schema,
)
tool_calls_log.append({
"name": fname,
"args": json.dumps(
args,
ensure_ascii=False,
),
"ok": not result.startswith("Error:"),
})
messages.append({
"role": "tool",
"tool_call_id": tc.get(
"id",
f"call_{fname}_{tc_index}",
),
"content": result,
})
except Exception as e:
# Tool-call formatting errors shouldn't kill the entire run.
# Feed an error back to the model so it can recover.
fname = (
tc.get("function", {}).get("name", "unknown")
if isinstance(tc, dict)
else "unknown"
)
error_text = (
f"Error processing tool call {fname}: "
f"{type(e).__name__}: {e}"
)
tool_calls_log.append({
"name": fname,
"args": "{}",
"ok": False,
})
messages.append({
"role": "tool",
"tool_call_id": tc.get(
"id",
f"call_{fname}_{tc_index}",
) if isinstance(tc, dict) else f"call_{tc_index}",
"content": error_text,
})
else:
error = (
f"hit {max_iterations}-iteration ceiling "
f"without answering"
)
if not answer:
for m in reversed(messages):
if (
isinstance(m, dict)
and m.get("role") == "assistant"
and m.get("content")
):
answer = str(m["content"])
break
return answer, tool_calls_log, iterations, error
def run_case_worker(case, args, doc_store, cfg_schema):
"""
Run one evaluation case.
Kept as a separate function so it can safely execute in a thread pool.
"""
q = case["question"]
t0 = time.time()
try:
answer, tool_log, iters, err = run_case(
args.base_url,
args.model,
q,
doc_store,
cfg_schema,
max_iterations=(
case["max_iterations"]
if case["max_iterations"] is not None
else args.max_iterations
),
temperature=args.temperature,
api_key=args.api_key,
timeout=args.timeout,
retries=args.retries,
)
except Exception as e:
answer = ""
tool_log = []
iters = 0
err = f"worker_error: {type(e).__name__}: {e}"
dt = time.time() - t0
assertions, ok = grade_case(
case,
answer,
tool_log,
iters,
err,
)
return {
"case": case,
"answer": answer,
"tool_log": tool_log,
"iterations": iters,
"error": err,
"assertions": assertions,
"passed": ok,
"duration": dt,
}
def check_server(base_url, model=None, api_key=None, timeout=5):
"""
Validate that the OpenAI-compatible server is reachable and optionally
verify that the requested model exists.
Returns:
{
"ok": bool,
"models": [...],
"error": str | None,
"kind": str | None,
}
"""
url = base_url.rstrip("/") + "/v1/models"
headers = {}
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
try:
resp = requests.get(
url,
headers=headers,
timeout=timeout,
)
except RequestsTimeout:
return {
"ok": False,
"models": [],
"error": f"timed out connecting to {url}",
"kind": "timeout",
}
except RequestsConnectionError as e:
return {
"ok": False,
"models": [],
"error": f"cannot reach {url}: {e}",
"kind": "connection_error",
}
except RequestException as e:
return {
"ok": False,
"models": [],
"error": f"request failed for {url}: {e}",
"kind": "request_error",
}
if resp.status_code != 200:
try:
detail = resp.json()
detail = json.dumps(detail, ensure_ascii=False)
except ValueError:
detail = resp.text.strip()
return {
"ok": False,
"models": [],
"error": (
f"{url} returned HTTP {resp.status_code}: "
f"{detail[:1000]}"
),
"kind": "http_error",
}
try:
data = resp.json()
except ValueError as e:
return {
"ok": False,
"models": [],
"error": f"{url} returned invalid JSON: {e}",
"kind": "invalid_json",
}
if not isinstance(data, dict):
return {
"ok": False,
"models": [],
"error": f"{url} returned {type(data).__name__}, expected object",
"kind": "invalid_response",
}
raw_models = data.get("data")
if not isinstance(raw_models, list):
return {
"ok": False,
"models": [],
"error": "response from /v1/models has no valid 'data' list",
"kind": "invalid_response",
}
models = []
for item in raw_models:
if isinstance(item, dict) and item.get("id"):
models.append(str(item["id"]))
if model and model not in models:
return {
"ok": False,
"models": models,
"error": (
f"model {model!r} was not returned by /v1/models. "
f"Available models: {models[:20]}"
),
"kind": "model_not_found",
}
return {
"ok": True,
"models": models,
"error": None,
"kind": None,
}
# ---------- main ----------
def main():
ap = argparse.ArgumentParser(description="OpenAI-compatible docs-agent eval (Python)")
ap.add_argument(
"--repo-root",
help=(
"Path to the llama-swap repository. "
"If omitted, automatically detected from the script location."
),
)
ap.add_argument("--model", default=DEFAULT_MODEL, help="Model name")
ap.add_argument("--base-url", default=DEFAULT_BASE_URL, help="OpenAI-compatible API base URL")
ap.add_argument("--api-key", default=os.environ.get("OPENAI_API_KEY"))
ap.add_argument(
"--cases",
help="cases dir (defaults to <repo-root>/evals/docs-agent/cases)",
)
ap.add_argument("--group", action="append", default=[], help="filter group, repeatable")
ap.add_argument("--only", help="regex filter on case id")
ap.add_argument("--max-iterations", type=int, default=8)
ap.add_argument("--temperature", type=float, default=0)
ap.add_argument("--concurrency", type=int, default=1, help="number of cases to run concurrently")
ap.add_argument("--timeout", type=float, default=300, help="API request timeout in seconds")
ap.add_argument("--retries", type=int, default=2, help="retries for transient API failures")
ap.add_argument("--limit", type=int, help="limit number of cases for quick test")
args = ap.parse_args()
# Resolve llama-swap repository root.
if args.repo_root:
repo_root = Path(args.repo_root).expanduser().resolve()
if not repo_root.is_dir():
print(
f"ERROR: repo root does not exist: {repo_root}",
file=sys.stderr,
)
sys.exit(1)
else:
repo_root = find_repo_root(SCRIPT_DIR)
if repo_root is None:
print(
"ERROR: could not automatically find the llama-swap "
"repository root.",
file=sys.stderr,
)
print(
"Use --repo-root /path/to/llama-swap",
file=sys.stderr,
)
sys.exit(1)
# Validate required repo files/directories.
docs_root = repo_root / "docs" / "kb"
config_schema_path = repo_root / "config-schema.json"
if not docs_root.is_dir():
print(
f"ERROR: documentation directory does not exist: {docs_root}",
file=sys.stderr,
)
sys.exit(1)
if not config_schema_path.is_file():
print(
f"ERROR: config schema does not exist: {config_schema_path}",
file=sys.stderr,
)
sys.exit(1)
if args.cases:
cases_dir = Path(args.cases).expanduser().resolve()
else:
cases_dir = repo_root / "evals" / "docs-agent" / "cases"
if not cases_dir.is_dir():
print(
f"ERROR: cases directory does not exist: {cases_dir}",
file=sys.stderr,
)
sys.exit(1)
print(
f"Repo root: {repo_root}",
file=sys.stderr,
)
print(
f"Cases: {cases_dir}",
file=sys.stderr,
)
cases = load_cases(cases_dir)
if args.group:
avail = sorted(set(c["group"] for c in cases))
unknown = [g for g in args.group if g not in avail]
if unknown:
print(f"unknown --group {unknown}; available: {avail}", file=sys.stderr); sys.exit(1)
cases = [c for c in cases if c["group"] in args.group]
if args.only:
pat = re.compile(args.only)