ccheney commited on
Commit
2d661b0
·
verified ·
1 Parent(s): 1f9c35f

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. Dockerfile +125 -0
  3. README.md +112 -5
  4. biome.json +85 -0
  5. package-lock.json +0 -0
  6. package.json +46 -0
  7. packages/benchmark/Dockerfile +181 -0
  8. packages/benchmark/README.md +269 -0
  9. packages/benchmark/data/.gitignore +12 -0
  10. packages/benchmark/data/.gitkeep +7 -0
  11. packages/benchmark/data/longmemeval_oracle.json +3 -0
  12. packages/benchmark/data/results-demo-report.md +26 -0
  13. packages/benchmark/data/results-demo.jsonl +5 -0
  14. packages/benchmark/data/results-full-report.md +38 -0
  15. packages/benchmark/data/results-full.jsonl +500 -0
  16. packages/benchmark/hf-space/Dockerfile +125 -0
  17. packages/benchmark/hf-space/README.md +117 -0
  18. packages/benchmark/hf-space/deploy.sh +97 -0
  19. packages/benchmark/hf-space/run.sh +303 -0
  20. packages/benchmark/package.json +35 -0
  21. packages/benchmark/results/benchmark-50-gpt4o-report.md +38 -0
  22. packages/benchmark/results/benchmark-50-gpt4o.jsonl +50 -0
  23. packages/benchmark/results/full-run-20251218-report.md +38 -0
  24. packages/benchmark/results/full-run-20251218.jsonl +500 -0
  25. packages/benchmark/src/cli/commands/evaluate.ts +78 -0
  26. packages/benchmark/src/cli/commands/ingest.ts +177 -0
  27. packages/benchmark/src/cli/commands/run.ts +367 -0
  28. packages/benchmark/src/cli/commands/train-fusion.ts +495 -0
  29. packages/benchmark/src/cli/commands/validate.ts +28 -0
  30. packages/benchmark/src/cli/index.ts +159 -0
  31. packages/benchmark/src/core/config.ts +132 -0
  32. packages/benchmark/src/core/index.ts +24 -0
  33. packages/benchmark/src/core/runner.ts +226 -0
  34. packages/benchmark/src/core/types.ts +202 -0
  35. packages/benchmark/src/index.ts +29 -0
  36. packages/benchmark/src/longmemeval/evaluator.ts +582 -0
  37. packages/benchmark/src/longmemeval/index.ts +24 -0
  38. packages/benchmark/src/longmemeval/key-expansion.ts +494 -0
  39. packages/benchmark/src/longmemeval/loader.ts +226 -0
  40. packages/benchmark/src/longmemeval/mapper.ts +234 -0
  41. packages/benchmark/src/longmemeval/pipeline.ts +446 -0
  42. packages/benchmark/src/longmemeval/providers/anthropic-provider.ts +321 -0
  43. packages/benchmark/src/longmemeval/providers/engram-provider.ts +1274 -0
  44. packages/benchmark/src/longmemeval/providers/index.ts +17 -0
  45. packages/benchmark/src/longmemeval/providers/qdrant-provider.ts +283 -0
  46. packages/benchmark/src/longmemeval/reader.ts +780 -0
  47. packages/benchmark/src/longmemeval/retriever.ts +321 -0
  48. packages/benchmark/src/longmemeval/temporal.ts +430 -0
  49. packages/benchmark/src/longmemeval/types.ts +216 -0
  50. packages/benchmark/tests/core/config.test.ts +139 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ packages/benchmark/data/longmemeval_oracle.json filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =============================================================================
2
+ # Engram Benchmark - Hugging Face Spaces
3
+ # =============================================================================
4
+ # GPU-enabled container for running LongMemEval benchmarks with L4 GPU.
5
+ # Designed for Hugging Face Spaces Docker deployment.
6
+ #
7
+ # Usage:
8
+ # 1. Push this to HF Spaces (engram/benchmark)
9
+ # 2. Select L4 GPU hardware ($0.80/hr)
10
+ # 3. Access web UI to trigger benchmark runs
11
+ #
12
+ # =============================================================================
13
+
14
+ # -----------------------------------------------------------------------------
15
+ # Stage 1: Build dependencies
16
+ # -----------------------------------------------------------------------------
17
+ FROM node:22-bookworm-slim AS builder
18
+
19
+ WORKDIR /app
20
+
21
+ # Install build essentials for native modules
22
+ RUN apt-get update && apt-get install -y \
23
+ python3 \
24
+ make \
25
+ g++ \
26
+ git \
27
+ && rm -rf /var/lib/apt/lists/*
28
+
29
+ # Copy monorepo package files
30
+ COPY package*.json ./
31
+ COPY packages/benchmark/package.json packages/benchmark/
32
+ COPY packages/search/package.json packages/search/
33
+ COPY packages/graph/package.json packages/graph/
34
+ COPY packages/storage/package.json packages/storage/
35
+ COPY packages/logger/package.json packages/logger/
36
+ COPY packages/common/package.json packages/common/
37
+ COPY packages/temporal/package.json packages/temporal/
38
+
39
+ # Install all dependencies
40
+ RUN npm install --include=dev
41
+
42
+ # Copy source code
43
+ COPY packages/ packages/
44
+ COPY biome.json ./
45
+
46
+ # -----------------------------------------------------------------------------
47
+ # Stage 2: Runtime image with CUDA support
48
+ # -----------------------------------------------------------------------------
49
+ FROM nvidia/cuda:12.3.2-cudnn9-runtime-ubuntu22.04
50
+
51
+ # Install Node.js 22 LTS and system dependencies
52
+ RUN apt-get update && apt-get install -y \
53
+ curl \
54
+ ca-certificates \
55
+ wget \
56
+ jq \
57
+ && curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \
58
+ && apt-get install -y nodejs \
59
+ && rm -rf /var/lib/apt/lists/*
60
+
61
+ WORKDIR /app
62
+
63
+ # Copy built application from builder
64
+ COPY --from=builder /app/node_modules ./node_modules
65
+ COPY --from=builder /app/packages ./packages
66
+ COPY --from=builder /app/package*.json ./
67
+
68
+ # Reinstall native modules for the runtime platform
69
+ RUN npm install --os=linux --cpu=x64 sharp
70
+
71
+ # Model cache directory
72
+ ENV HF_HOME=/app/.cache
73
+ ENV TRANSFORMERS_CACHE=/app/.cache
74
+ ENV XDG_CACHE_HOME=/app/.cache
75
+
76
+ # Create cache directory for models (downloaded on first run)
77
+ # Skipping model preload during Docker build to avoid build failures
78
+ # Models will be cached after first run
79
+ RUN mkdir -p /app/.cache
80
+
81
+ # Install Qdrant for local vector search
82
+ RUN wget -q https://github.com/qdrant/qdrant/releases/download/v1.16.2/qdrant-x86_64-unknown-linux-gnu.tar.gz \
83
+ && tar xzf qdrant-x86_64-unknown-linux-gnu.tar.gz -C /usr/local/bin \
84
+ && rm qdrant-x86_64-unknown-linux-gnu.tar.gz \
85
+ && mkdir -p /app/qdrant-storage
86
+
87
+ # Install Redis 7.4+ for FalkorDB (Ubuntu 22.04 has old Redis, install from source)
88
+ RUN apt-get update && apt-get install -y \
89
+ libgomp1 \
90
+ build-essential \
91
+ && rm -rf /var/lib/apt/lists/* \
92
+ && mkdir -p /app/falkordb-data \
93
+ && wget -q https://github.com/redis/redis/archive/refs/tags/7.4.2.tar.gz \
94
+ && tar xzf 7.4.2.tar.gz \
95
+ && cd redis-7.4.2 && make -j$(nproc) && make install \
96
+ && cd .. && rm -rf redis-7.4.2 7.4.2.tar.gz
97
+
98
+ # Download FalkorDB module (v4.14.10 - latest)
99
+ RUN mkdir -p /opt/falkordb \
100
+ && wget -q https://github.com/FalkorDB/FalkorDB/releases/download/v4.14.10/falkordb-x64.so -O /opt/falkordb/falkordb.so \
101
+ && chmod +x /opt/falkordb/falkordb.so
102
+
103
+ # Copy HF Space runner script
104
+ COPY packages/benchmark/hf-space/run.sh /app/run.sh
105
+ RUN chmod +x /app/run.sh
106
+
107
+ # Create directories for data and results
108
+ RUN mkdir -p /data /results
109
+
110
+ # Environment configuration
111
+ ENV NODE_ENV=production
112
+ ENV BENCHMARK_VERBOSE=true
113
+ ENV NODE_OPTIONS="--max-old-space-size=24576"
114
+
115
+ # GPU mode with FP16 for L4
116
+ ENV EMBEDDER_DEVICE=cuda
117
+ ENV EMBEDDER_DTYPE=fp16
118
+ ENV QDRANT_URL=http://localhost:6333
119
+ ENV FALKORDB_URL=redis://localhost:6379
120
+
121
+ # HF Spaces requires port 7860
122
+ EXPOSE 7860
123
+
124
+ # Run the benchmark server
125
+ CMD ["/app/run.sh"]
README.md CHANGED
@@ -1,10 +1,117 @@
1
  ---
2
  title: Engram Benchmark
3
- emoji: 🏆
4
- colorFrom: indigo
5
- colorTo: purple
6
  sdk: docker
7
- pinned: false
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Engram Benchmark
3
+ emoji: 🧠
4
+ colorFrom: purple
5
+ colorTo: blue
6
  sdk: docker
7
+ app_port: 7860
8
+ suggested_hardware: l4x1
9
+ suggested_storage: small
10
  ---
11
 
12
+ # Engram LongMemEval Benchmark
13
+
14
+ GPU-accelerated benchmark runner for evaluating the Engram memory retrieval system on LongMemEval dataset.
15
+
16
+ **Full Engram Stack:** FalkorDB (bitemporal graph) + Qdrant (vectors) running in-container.
17
+
18
+ ## Hardware
19
+
20
+ This Space requires **L4 GPU** ($0.80/hr) for optimal performance:
21
+ - 24GB VRAM for embedding models (E5-large, fp16)
22
+ - CUDA 12.3 with cuDNN 9 for ONNX Runtime
23
+
24
+ ## API Endpoints
25
+
26
+ | Endpoint | Method | Description |
27
+ |----------|--------|-------------|
28
+ | `/` | GET | Health check (shows FalkorDB + Qdrant status) |
29
+ | `/ingest` | POST | Ingest dataset into FalkorDB + Qdrant |
30
+ | `/start` | POST | Start benchmark (requires ingest first) |
31
+ | `/status` | GET | Get current status and output |
32
+ | `/results` | GET | Download results (when complete) |
33
+
34
+ ## Usage
35
+
36
+ ```bash
37
+ # Check health
38
+ curl https://engram-benchmark.hf.space/
39
+
40
+ # Step 1: Ingest data into FalkorDB (graph) + Qdrant (vectors)
41
+ curl -X POST https://engram-benchmark.hf.space/ingest
42
+
43
+ # Wait for ingest to complete...
44
+ curl https://engram-benchmark.hf.space/status
45
+
46
+ # Step 2: Run benchmark with full Engram pipeline
47
+ curl -X POST https://engram-benchmark.hf.space/start
48
+
49
+ # Check status
50
+ curl https://engram-benchmark.hf.space/status
51
+
52
+ # Step 3: Download results
53
+ curl https://engram-benchmark.hf.space/results > results.jsonl
54
+ ```
55
+
56
+ ## Architecture
57
+
58
+ The benchmark runs the **full Engram stack**:
59
+
60
+ ```
61
+ LongMemEval Dataset
62
+ ↓
63
+ FalkorDB (bitemporal graph)
64
+ - Session nodes with timestamps
65
+ - Turn nodes with content
66
+ - Memory nodes for retrieval
67
+ ↓
68
+ Qdrant (vector index)
69
+ - E5-large embeddings (fp16)
70
+ - Hybrid search (dense + sparse)
71
+ ↓
72
+ Engram Retrieval Pipeline
73
+ - Graph traversal + vector search
74
+ - Session-aware hierarchical retrieval
75
+ - Temporal query parsing
76
+ ↓
77
+ Gemini (answer generation)
78
+ ↓
79
+ Results
80
+ ```
81
+
82
+ ## Configuration
83
+
84
+ Set these secrets in the Space settings:
85
+
86
+ | Secret | Description |
87
+ |--------|-------------|
88
+ | `GOOGLE_GENERATIVE_AI_API_KEY` | Gemini API key for answer generation |
89
+
90
+ ## Benchmark Features
91
+
92
+ Full Engram pipeline with all optimizations:
93
+
94
+ **Retrieval:**
95
+ - Dense embeddings (E5-large, 1024d, fp16)
96
+ - Sparse embeddings (SPLADE)
97
+ - Hybrid search with RRF fusion
98
+ - Multi-query expansion
99
+ - Session-aware hierarchical retrieval
100
+ - Temporal query parsing
101
+
102
+ **Reranking:**
103
+ - Cross-encoder reranking (accurate tier)
104
+ - Deep candidate pool (50 docs)
105
+
106
+ **Reading:**
107
+ - Chain-of-Note structured reasoning
108
+ - Time-aware query expansion
109
+
110
+ **Abstention (3-layer):**
111
+ - Low retrieval confidence
112
+ - NLI answer grounding
113
+ - Hedging pattern detection
114
+
115
+ ## Results
116
+
117
+ Results are saved to `/results/benchmark-results.jsonl` and can be downloaded via the `/results` endpoint.
biome.json ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "https://biomejs.dev/schemas/2.3.8/schema.json",
3
+ "vcs": {
4
+ "enabled": true,
5
+ "clientKind": "git",
6
+ "useIgnoreFile": true
7
+ },
8
+ "files": {
9
+ "ignoreUnknown": false,
10
+ "includes": ["**", "!**/dist", "!**/.next", "!**/node_modules", "!**/coverage", "!**/.turbo"]
11
+ },
12
+ "css": {
13
+ "linter": {
14
+ "enabled": false
15
+ }
16
+ },
17
+ "formatter": {
18
+ "enabled": true,
19
+ "indentStyle": "tab",
20
+ "indentWidth": 2,
21
+ "lineWidth": 100
22
+ },
23
+ "assist": { "actions": { "source": { "organizeImports": "on" } } },
24
+ "linter": {
25
+ "enabled": true,
26
+ "rules": {
27
+ "recommended": true,
28
+ "suspicious": {
29
+ "noExplicitAny": "off",
30
+ "noArrayIndexKey": "warn"
31
+ },
32
+ "a11y": {
33
+ "useButtonType": "warn",
34
+ "noSvgWithoutTitle": "off",
35
+ "noStaticElementInteractions": "off"
36
+ },
37
+ "complexity": {
38
+ "noUselessConstructor": "warn",
39
+ "noBannedTypes": "warn"
40
+ },
41
+ "style": {
42
+ "noNonNullAssertion": "warn"
43
+ },
44
+ "correctness": {
45
+ "noUnusedVariables": "warn",
46
+ "noUnusedFunctionParameters": "warn",
47
+ "noConstructorReturn": "warn"
48
+ }
49
+ }
50
+ },
51
+ "overrides": [
52
+ {
53
+ "includes": ["**/*.test.ts", "**/*.test.tsx", "tests/**/*"],
54
+ "linter": {
55
+ "rules": {
56
+ "suspicious": {
57
+ "noExplicitAny": "off",
58
+ "noArrayIndexKey": "off"
59
+ },
60
+ "correctness": {
61
+ "noUnusedVariables": "off"
62
+ }
63
+ }
64
+ }
65
+ },
66
+ {
67
+ "includes": ["scripts/**/*"],
68
+ "linter": {
69
+ "rules": {
70
+ "suspicious": {
71
+ "noExplicitAny": "off"
72
+ },
73
+ "correctness": {
74
+ "noUnusedFunctionParameters": "off"
75
+ }
76
+ }
77
+ }
78
+ }
79
+ ],
80
+ "javascript": {
81
+ "formatter": {
82
+ "quoteStyle": "double"
83
+ }
84
+ }
85
+ }
package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
package.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "engram",
3
+ "version": "0.0.0",
4
+ "private": true,
5
+ "workspaces": [
6
+ "apps/*",
7
+ "packages/*",
8
+ "tooling/*"
9
+ ],
10
+ "overrides": {
11
+ "zod": "$zod"
12
+ },
13
+ "scripts": {
14
+ "build": "turbo run build",
15
+ "typecheck": "turbo run typecheck",
16
+ "dev": "turbo run dev",
17
+ "lint": "biome check --write .",
18
+ "format": "biome format --write .",
19
+ "test": "vitest run",
20
+ "infra:up": "docker-compose -f docker-compose.dev.yml up -d",
21
+ "infra:down": "docker-compose -f docker-compose.dev.yml down",
22
+ "prepare": "husky"
23
+ },
24
+ "devDependencies": {
25
+ "@biomejs/biome": "^2.3.8",
26
+ "@engram/events": "*",
27
+ "@engram/storage": "*",
28
+ "@modelcontextprotocol/sdk": "^1.24.3",
29
+ "@qdrant/js-client-rest": "^1.16.2",
30
+ "@vitest/coverage-v8": "^3.2.4",
31
+ "falkordb": "^6.3.1",
32
+ "husky": "^9.1.7",
33
+ "jsdom": "^27.3.0",
34
+ "patch-package": "^8.0.1",
35
+ "pino-pretty": "^13.1.3",
36
+ "tsx": "^4.21.0",
37
+ "turbo": "^2.6.3",
38
+ "typescript": "^5.9.3",
39
+ "vitest": "^3.2.3",
40
+ "zod": "^4.1.13"
41
+ },
42
+ "packageManager": "npm@11.4.1",
43
+ "dependencies": {
44
+ "@confluentinc/kafka-javascript": "^1.7.0"
45
+ }
46
+ }
packages/benchmark/Dockerfile ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =============================================================================
2
+ # Engram Benchmark Container
3
+ # =============================================================================
4
+ # GPU-enabled container for running LongMemEval benchmarks with all Engram
5
+ # features enabled. Uses NVIDIA L4 GPU in Cloud Run.
6
+ #
7
+ # Build:
8
+ # docker build -t engram-benchmark .
9
+ #
10
+ # Run locally (CPU):
11
+ # docker run --rm engram-benchmark --help
12
+ #
13
+ # Run with GPU:
14
+ # docker run --rm --gpus all engram-benchmark
15
+ #
16
+ # =============================================================================
17
+
18
+ # -----------------------------------------------------------------------------
19
+ # Stage 1: Build dependencies
20
+ # -----------------------------------------------------------------------------
21
+ FROM node:24-bookworm-slim AS builder
22
+
23
+ WORKDIR /app
24
+
25
+ # Install build essentials for native modules
26
+ RUN apt-get update && apt-get install -y \
27
+ python3 \
28
+ make \
29
+ g++ \
30
+ git \
31
+ && rm -rf /var/lib/apt/lists/*
32
+
33
+ # Copy package files for dependency installation
34
+ COPY package*.json ./
35
+ COPY packages/benchmark/package.json packages/benchmark/
36
+ COPY packages/search/package.json packages/search/
37
+ COPY packages/graph/package.json packages/graph/
38
+ COPY packages/storage/package.json packages/storage/
39
+ COPY packages/logger/package.json packages/logger/
40
+ COPY packages/common/package.json packages/common/
41
+ COPY packages/temporal/package.json packages/temporal/
42
+
43
+ # Install all dependencies
44
+ RUN npm install --include=dev
45
+
46
+ # Copy source code
47
+ COPY packages/ packages/
48
+ COPY biome.json ./
49
+
50
+ # Skip typecheck in Docker build (already validated locally)
51
+ # The onnxruntime-node types are provided by @huggingface/transformers at runtime
52
+
53
+ # -----------------------------------------------------------------------------
54
+ # Stage 2: Runtime image with CUDA support
55
+ # -----------------------------------------------------------------------------
56
+ # Using CUDA 12.3.2 with cuDNN 9 for ONNX Runtime GPU support (embedding models, rerankers)
57
+ # cuDNN 9 is required by onnxruntime-node; only available with CUDA 12.3.2 on Ubuntu 22.04
58
+ FROM nvidia/cuda:12.3.2-cudnn9-runtime-ubuntu22.04
59
+
60
+ # Install Node.js 24
61
+ RUN apt-get update && apt-get install -y \
62
+ curl \
63
+ ca-certificates \
64
+ && curl -fsSL https://deb.nodesource.com/setup_24.x | bash - \
65
+ && apt-get install -y nodejs \
66
+ && rm -rf /var/lib/apt/lists/*
67
+
68
+ WORKDIR /app
69
+
70
+ # Copy built application from builder
71
+ COPY --from=builder /app/node_modules ./node_modules
72
+ COPY --from=builder /app/packages ./packages
73
+ COPY --from=builder /app/package*.json ./
74
+
75
+ # Reinstall native modules for the runtime platform (needed for cross-platform builds)
76
+ # sharp and onnxruntime-node have native bindings that must match the runtime architecture
77
+ RUN npm install --os=linux --cpu=x64 sharp
78
+
79
+ # Model cache directory - set before preloading
80
+ ENV HF_HOME=/app/.cache
81
+ ENV TRANSFORMERS_CACHE=/app/.cache
82
+ ENV XDG_CACHE_HOME=/app/.cache
83
+
84
+ # Pre-download HuggingFace models at build time to avoid runtime download issues
85
+ # Models are cached in /app/.cache and included in the image
86
+ # Download q8 quantized models for CPU mode (4x smaller than FP32, fits in 24GB RAM)
87
+ RUN mkdir -p /app/.cache && \
88
+ node -e "const { pipeline } = require('@huggingface/transformers'); \
89
+ (async () => { \
90
+ console.log('Pre-downloading embedding models (q8 quantized for CPU)...'); \
91
+ await pipeline('feature-extraction', 'Xenova/multilingual-e5-large', { dtype: 'q8' }); \
92
+ await pipeline('feature-extraction', 'Xenova/multilingual-e5-small', { dtype: 'q8' }); \
93
+ console.log('Pre-downloading reranker models...'); \
94
+ await pipeline('text-classification', 'Xenova/ms-marco-MiniLM-L-6-v2', { dtype: 'q8' }); \
95
+ console.log('Models pre-downloaded successfully'); \
96
+ })().catch(e => { console.error('Model preload failed:', e); process.exit(1); });"
97
+
98
+ # Create non-root user for security
99
+ RUN groupadd -r engram && useradd -r -g engram engram \
100
+ && mkdir -p /data /results \
101
+ && chown -R engram:engram /app /data /results
102
+
103
+ USER engram
104
+
105
+ # Environment configuration
106
+ ENV NODE_ENV=production
107
+ ENV BENCHMARK_VERBOSE=true
108
+ # Increase Node.js heap size (default ~4GB is too small for loading multiple models)
109
+ ENV NODE_OPTIONS="--max-old-space-size=16384"
110
+
111
+ # Force CPU mode to avoid ONNX Runtime CUDA memory allocation issues
112
+ # The BFC arena in CUDAExecutionProvider allocates 4-10x model size
113
+ # which causes OOM even with 24GB VRAM when loading multiple models
114
+ # Use q8 quantized models (4x smaller than FP32) to fit in 24GB RAM
115
+ ENV EMBEDDER_DEVICE=cpu
116
+ ENV EMBEDDER_DTYPE=q8
117
+
118
+ # Default command runs full benchmark with ALL features enabled
119
+ ENTRYPOINT ["npx", "tsx", "packages/benchmark/src/cli/index.ts"]
120
+
121
+ # =============================================================================
122
+ # FULL ENGRAM BENCHMARK - ALL FEATURES ENABLED
123
+ # =============================================================================
124
+ # This command enables every Engram optimization for maximum retrieval quality:
125
+ #
126
+ # Retrieval:
127
+ # - Dense embeddings (E5-large, 1024d) - SOTA multilingual
128
+ # - Sparse embeddings (SPLADE)
129
+ # - Hybrid search with RRF fusion
130
+ # - Multi-query expansion (3 variations)
131
+ # - Session-aware hierarchical retrieval
132
+ # - Temporal query parsing (chrono-node)
133
+ #
134
+ # Reranking:
135
+ # - Cross-encoder reranking (accurate tier)
136
+ # - Deep candidate pool (50 docs)
137
+ #
138
+ # Reading:
139
+ # - Chain-of-Note structured reasoning
140
+ # - Time-aware query expansion
141
+ #
142
+ # Abstention (3-layer):
143
+ # - Layer 1: Low retrieval confidence
144
+ # - Layer 2: NLI answer grounding
145
+ # - Layer 3: Hedging pattern detection
146
+ #
147
+ # Optimization:
148
+ # - Key expansion with fact extraction
149
+ # - Temporal analysis
150
+ #
151
+ # =============================================================================
152
+ CMD ["run", "longmemeval", \
153
+ "--dataset", "/data/longmemeval_oracle.json", \
154
+ "--variant", "oracle", \
155
+ "--embeddings", "engram", \
156
+ "--llm", "gemini", \
157
+ "--gemini-model", "gemini-3-flash-preview", \
158
+ "--top-k", "10", \
159
+ "--hybrid-search", \
160
+ "--rerank", \
161
+ "--rerank-tier", "accurate", \
162
+ "--rerank-depth", "50", \
163
+ "--multi-query", \
164
+ "--multi-query-variations", "3", \
165
+ "--session-aware", \
166
+ "--top-sessions", "5", \
167
+ "--turns-per-session", "3", \
168
+ "--temporal-aware", \
169
+ "--temporal-confidence-threshold", "0.5", \
170
+ "--abstention", \
171
+ "--abstention-threshold", "0.3", \
172
+ "--abstention-hedging", \
173
+ "--abstention-nli", \
174
+ "--abstention-nli-threshold", "0.7", \
175
+ "--key-expansion", \
176
+ "--temporal-analysis", \
177
+ "--chain-of-note", \
178
+ "--time-aware", \
179
+ "--embedding-model", "e5-small", \
180
+ "--verbose", \
181
+ "--output", "/results/benchmark-results.jsonl"]
packages/benchmark/README.md ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @engram/benchmark
2
+
3
+ [![LongMemEval](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/ccheney/engram/main/.github/benchmark-history/badge.json)](https://github.com/ccheney/engram/actions/workflows/benchmark.yml)
4
+
5
+ Benchmark suite for evaluating Engram's memory system against industry-standard benchmarks.
6
+
7
+ ## Supported Benchmarks
8
+
9
+ ### LongMemEval (ICLR 2025)
10
+
11
+ [LongMemEval](https://github.com/xiaowu0162/LongMemEval) tests 5 core memory abilities:
12
+
13
+ | Ability | Code | Description |
14
+ |:--------|:-----|:------------|
15
+ | Information Extraction | IE | Recall specific facts from history |
16
+ | Multi-Session Reasoning | MR | Synthesize across sessions |
17
+ | Temporal Reasoning | TR | Use timestamps and temporal refs |
18
+ | Knowledge Update | KU | Handle contradictory info over time |
19
+ | Abstention | ABS | Recognize unanswerable questions |
20
+
21
+ ## Quick Start
22
+
23
+ ### 1. Download the Dataset
24
+
25
+ ```bash
26
+ cd packages/benchmark/data
27
+
28
+ # Oracle dataset (smallest, ~500 questions with evidence only)
29
+ curl -L -o longmemeval_oracle.json \
30
+ "https://huggingface.co/datasets/xiaowu0162/longmemeval-cleaned/resolve/main/longmemeval_oracle.json"
31
+
32
+ # Small dataset (~115k tokens, ~40 sessions)
33
+ curl -L -o longmemeval_s_cleaned.json \
34
+ "https://huggingface.co/datasets/xiaowu0162/longmemeval-cleaned/resolve/main/longmemeval_s_cleaned.json"
35
+ ```
36
+
37
+ ### 2. Validate the Dataset
38
+
39
+ ```bash
40
+ npx tsx src/cli/index.ts validate data/longmemeval_oracle.json
41
+ ```
42
+
43
+ ### 3. Run the Benchmark
44
+
45
+ ```bash
46
+ # Quick test with stub providers
47
+ npx tsx src/cli/index.ts run longmemeval \
48
+ --dataset data/longmemeval_oracle.json \
49
+ --limit 10 \
50
+ --verbose
51
+
52
+ # Full run with E5 embeddings
53
+ npx tsx src/cli/index.ts run longmemeval \
54
+ --dataset data/longmemeval_oracle.json \
55
+ --embeddings e5 \
56
+ --llm anthropic \
57
+ --chain-of-note \
58
+ --key-expansion \
59
+ --temporal-analysis \
60
+ --output results/benchmark.jsonl
61
+ ```
62
+
63
+ ### Let Engram Cook (Full Pipeline)
64
+
65
+ Run the complete Engram retrieval pipeline with **all optimizations enabled**:
66
+
67
+ ```bash
68
+ # Ensure infrastructure is running
69
+ docker ps | grep qdrant || npm run infra:up
70
+
71
+ # Full Engram pipeline - EVERY FEATURE ENABLED
72
+ GOOGLE_GENERATIVE_AI_API_KEY="..." NODE_OPTIONS="--max-old-space-size=8192" \
73
+ npx tsx src/cli/index.ts run longmemeval \
74
+ --dataset data/longmemeval_oracle.json \
75
+ --variant oracle \
76
+ --embeddings engram \
77
+ --llm gemini \
78
+ --gemini-model gemini-3-flash-preview \
79
+ --top-k 10 \
80
+ --hybrid-search \
81
+ --rerank \
82
+ --rerank-tier accurate \
83
+ --rerank-depth 50 \
84
+ --multi-query \
85
+ --multi-query-variations 3 \
86
+ --session-aware \
87
+ --top-sessions 5 \
88
+ --turns-per-session 3 \
89
+ --temporal-aware \
90
+ --temporal-confidence-threshold 0.5 \
91
+ --abstention \
92
+ --abstention-threshold 0.3 \
93
+ --abstention-hedging \
94
+ --abstention-nli \
95
+ --abstention-nli-threshold 0.7 \
96
+ --key-expansion \
97
+ --temporal-analysis \
98
+ --chain-of-note \
99
+ --time-aware \
100
+ --embedding-model e5-small \
101
+ --verbose \
102
+ --debug-retrieval \
103
+ --output results/engram-full-$(date +%Y%m%d).jsonl
104
+ ```
105
+
106
+ **What this enables:**
107
+
108
+ | Category | Feature | Description |
109
+ |:---------|:--------|:------------|
110
+ | **Retrieval** | Dense embeddings | E5-small (384d) |
111
+ | | Sparse embeddings | SPLADE learned sparse |
112
+ | | Hybrid search | Dense + Sparse + RRF fusion |
113
+ | | Multi-query | Query expansion with 3 variations |
114
+ | | Session-aware | Hierarchical session→turn retrieval |
115
+ | | Temporal parsing | chrono-node date extraction |
116
+ | **Reranking** | Cross-encoder | Accurate tier (deeper model) |
117
+ | | Rerank depth | 50 candidates before reranking |
118
+ | **Reading** | Chain-of-Note | Structured evidence reasoning |
119
+ | | Time-aware | Temporal query expansion |
120
+ | **Abstention** | Layer 1 | Low retrieval confidence detection |
121
+ | | Layer 2 | NLI answer grounding check |
122
+ | | Layer 3 | Hedging pattern detection |
123
+ | **Optimization** | Key expansion | Fact extraction (+9% recall) |
124
+ | | Temporal analysis | Time-aware queries (+7-11% TR) |
125
+ | **Debug** | Debug retrieval | Show retrieved vs expected docs |
126
+
127
+ ### 4. Evaluate Results
128
+
129
+ ```bash
130
+ npx tsx src/cli/index.ts evaluate \
131
+ --hypothesis results/benchmark.jsonl \
132
+ --ground-truth data/longmemeval_oracle.json \
133
+ --output results/metrics.json
134
+ ```
135
+
136
+ ## CLI Options
137
+
138
+ ### `run` Command
139
+
140
+ | Option | Description | Default |
141
+ |:-------|:------------|:--------|
142
+ | `-d, --dataset <path>` | Path to dataset file | Required |
143
+ | `-v, --variant <s\|m\|oracle>` | Dataset variant | `s` |
144
+ | `-o, --output <path>` | Output file for results | - |
145
+ | `-l, --limit <n>` | Limit number of instances | - |
146
+ | `-k, --top-k <n>` | Documents to retrieve | `10` |
147
+ | `--retriever <method>` | dense, bm25, hybrid | `dense` |
148
+ | `--chain-of-note` | Enable Chain-of-Note | `false` |
149
+ | `--time-aware` | Enable time-aware query expansion | `false` |
150
+ | `--key-expansion` | Enable key expansion (+9% recall) | `false` |
151
+ | `--temporal-analysis` | Enable temporal analysis (+7-11% TR) | `false` |
152
+ | `--embeddings <provider>` | stub, qdrant, e5, engram | `stub` |
153
+ | `--llm <provider>` | stub, anthropic, openai, ollama | `stub` |
154
+
155
+ #### Engram Pipeline Options (when `--embeddings engram`)
156
+
157
+ | Option | Description | Default |
158
+ |:-------|:------------|:--------|
159
+ | `--hybrid-search` | Enable hybrid search (dense + SPLADE + RRF) | `true` |
160
+ | `--rerank` | Enable cross-encoder reranking | `true` |
161
+ | `--rerank-tier <tier>` | Reranker: fast, accurate, code, colbert | `fast` |
162
+ | `--rerank-depth <n>` | Candidates to fetch before reranking | `30` |
163
+ | `--qdrant-url <url>` | Qdrant server URL | `http://localhost:6333` |
164
+
165
+ ### `evaluate` Command
166
+
167
+ | Option | Description |
168
+ |:-------|:------------|
169
+ | `-h, --hypothesis <path>` | Path to hypothesis JSONL |
170
+ | `-g, --ground-truth <path>` | Path to ground truth dataset |
171
+ | `-o, --output <path>` | Output file for metrics |
172
+ | `--llm-eval` | Use LLM-based evaluation |
173
+
174
+ ## Metrics
175
+
176
+ ### QA Metrics
177
+
178
+ - **Overall Accuracy**: Percentage of correct answers
179
+ - **Per-Ability Accuracy**: Breakdown by IE, MR, TR, KU, ABS
180
+
181
+ ### Retrieval Metrics
182
+
183
+ - **Recall@K**: Percentage of evidence retrieved at K={1,5,10}
184
+ - **NDCG@K**: Normalized Discounted Cumulative Gain
185
+ - **MRR**: Mean Reciprocal Rank
186
+
187
+ ### Abstention Metrics
188
+
189
+ - **Precision**: Correct abstentions / Total abstentions
190
+ - **Recall**: Correct abstentions / Questions requiring abstention
191
+ - **F1 Score**: Harmonic mean of precision and recall
192
+
193
+ ## Optimizations
194
+
195
+ Based on [LongMemEval paper](https://arxiv.org/abs/2410.10813) findings:
196
+
197
+ | Optimization | Improvement | Flag |
198
+ |:-------------|:------------|:-----|
199
+ | Chain-of-Note | +10 points QA | `--chain-of-note` |
200
+ | Key Expansion | +9.4% recall | `--key-expansion` |
201
+ | Time-Aware Queries | +7-11% on TR | `--temporal-analysis` |
202
+
203
+ ## GPU Deployment (Hugging Face Spaces)
204
+
205
+ For GPU-accelerated benchmark runs, deploy to Hugging Face Spaces with L4 GPU ($0.80/hr):
206
+
207
+ ```bash
208
+ # Install HF CLI
209
+ pip install huggingface_hub
210
+
211
+ # Login
212
+ huggingface-cli login
213
+
214
+ # Deploy
215
+ cd packages/benchmark/hf-space
216
+ ./deploy.sh ccheney/engram-benchmark
217
+ ```
218
+
219
+ Then:
220
+ 1. Set `GOOGLE_GENERATIVE_AI_API_KEY` secret in Space settings
221
+ 2. Select L4 GPU hardware
222
+ 3. Wait for build
223
+ 4. `POST /start` to run benchmark
224
+
225
+ See `hf-space/README.md` for API documentation.
226
+
227
+ ## CI/CD
228
+
229
+ The benchmark runs automatically:
230
+ - **Weekly**: Sunday at midnight (scheduled)
231
+ - **On PR**: When benchmark code changes
232
+ - **Manual**: Via workflow dispatch
233
+
234
+ Results are stored as artifacts and tracked historically.
235
+
236
+ ## Development
237
+
238
+ ```bash
239
+ # Run tests
240
+ npm test
241
+
242
+ # Type check
243
+ npm run typecheck
244
+
245
+ # Build
246
+ npm run build
247
+ ```
248
+
249
+ ## Architecture
250
+
251
+ ```
252
+ packages/benchmark/
253
+ ├── src/
254
+ │ ├── longmemeval/
255
+ │ │ ├── types.ts # Zod schemas & types
256
+ │ │ ├── loader.ts # Dataset loading
257
+ │ │ ├── mapper.ts # LongMemEval → Engram
258
+ │ │ ├── retriever.ts # Vector retrieval
259
+ │ │ ├── reader.ts # LLM answer generation
260
+ │ │ ├── evaluator.ts # Metrics computation
261
+ │ │ ├── pipeline.ts # Orchestration
262
+ │ │ ├── key-expansion.ts # Fact extraction
263
+ │ │ ├── temporal.ts # Time-aware queries
264
+ │ │ └── providers/ # Real provider integrations
265
+ │ └── cli/
266
+ │ └── commands/ # CLI command handlers
267
+ ├── tests/ # Test suites
268
+ └── data/ # Dataset storage
269
+ ```
packages/benchmark/data/.gitignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Downloaded datasets
2
+ *.json
3
+
4
+ # Benchmark results
5
+ *.jsonl
6
+
7
+ # Generated reports
8
+ *-report.md
9
+
10
+ # Keep the gitkeep
11
+ !.gitkeep
12
+ !.gitignore
packages/benchmark/data/.gitkeep ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Download LongMemEval dataset from HuggingFace:
2
+ # https://huggingface.co/datasets/xiaowu0162/longmemeval-cleaned
3
+ #
4
+ # Place the following files here:
5
+ # - longmemeval_s_cleaned.json (~115k tokens, ~40 sessions)
6
+ # - longmemeval_m_cleaned.json (~1.5M tokens, ~500 sessions)
7
+ # - longmemeval_oracle.json (evidence-only sessions)
packages/benchmark/data/longmemeval_oracle.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:821a2034d219ab45846873dd14c14f12cfe7776e73527a483f9dac095d38620c
3
+ size 15388478
packages/benchmark/data/results-demo-report.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LongMemEval Benchmark Results
2
+
3
+ ## Overall
4
+ - Total: 5
5
+ - Correct: 3
6
+ - Accuracy: 60.0%
7
+
8
+ ## By Memory Ability
9
+
10
+ | Ability | Total | Correct | Accuracy |
11
+ |:--------|------:|--------:|---------:|
12
+ | Information Extraction (IE) | 0 | 0 | 0.0% |
13
+ | Multi-Session Reasoning (MR) | 0 | 0 | 0.0% |
14
+ | Temporal Reasoning (TR) | 5 | 3 | 60.0% |
15
+ | Knowledge Update (KU) | 0 | 0 | 0.0% |
16
+ | Abstention (ABS) | 0 | 0 | 0.0% |
17
+
18
+ ## Retrieval Metrics
19
+
20
+ - Turn Recall: 50.0%
21
+ - Session Recall: 50.0%
22
+
23
+ ### Recall@K
24
+ - Recall@1: 0.0%
25
+ - Recall@5: 0.0%
26
+ - Recall@10: 50.0%
packages/benchmark/data/results-demo.jsonl ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {"question_id":"gpt4_2655b836","hypothesis":"I cannot answer \"What was the first issue I had with my new car after its first service?\" without a real LLM provider configured."}
2
+ {"question_id":"gpt4_2487a7cb","hypothesis":"I cannot answer \"Which event did I attend first, the 'Effective Time Management' workshop or the 'Data Analysis using Python' webinar?\" without a real LLM provider configured."}
3
+ {"question_id":"gpt4_76048e76","hypothesis":"I cannot answer \"Which vehicle did I take care of first in February, the bike or the car?\" without a real LLM provider configured."}
4
+ {"question_id":"gpt4_2312f94c","hypothesis":"I cannot answer \"Which device did I got first, the Samsung Galaxy S22 or the Dell XPS 13?\" without a real LLM provider configured."}
5
+ {"question_id":"0bb5a684","hypothesis":"I cannot answer \"How many days before the team meeting I was preparing for did I attend the workshop on 'Effective Communication in the Workplace'?\" without a real LLM provider configured."}
packages/benchmark/data/results-full-report.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LongMemEval Benchmark Results
2
+
3
+ ## Overall
4
+ - Total: 500
5
+ - Correct: 39
6
+ - Accuracy: 7.8%
7
+
8
+ ## By Memory Ability
9
+
10
+ | Ability | Total | Correct | Accuracy |
11
+ |:--------|------:|--------:|---------:|
12
+ | Information Extraction (IE) | 150 | 6 | 4.0% |
13
+ | Multi-Session Reasoning (MR) | 121 | 1 | 0.8% |
14
+ | Temporal Reasoning (TR) | 127 | 31 | 24.4% |
15
+ | Knowledge Update (KU) | 72 | 1 | 1.4% |
16
+ | Abstention (ABS) | 30 | 0 | 0.0% |
17
+
18
+ ## Retrieval Metrics
19
+
20
+ - Turn Recall: 53.0%
21
+ - Session Recall: 53.0%
22
+ - MRR: 0.530
23
+
24
+ ### Recall@K
25
+
26
+ | K | Recall |
27
+ |--:|-------:|
28
+ | 1 | 0.0% |
29
+ | 5 | 0.0% |
30
+ | 10 | 53.0% |
31
+
32
+ ### NDCG@K
33
+
34
+ | K | NDCG |
35
+ |--:|-----:|
36
+ | 1 | 0.000 |
37
+ | 5 | 0.000 |
38
+ | 10 | 0.530 |
packages/benchmark/data/results-full.jsonl ADDED
@@ -0,0 +1,500 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"question_id":"gpt4_2655b836","hypothesis":"Unable to answer: \"What was the first issue I had with my new car after its first service?\""}
2
+ {"question_id":"gpt4_2487a7cb","hypothesis":"Unable to answer: \"Which event did I attend first, the 'Effective Time Management' workshop or the 'Data Analysis using Python' webinar?\""}
3
+ {"question_id":"gpt4_76048e76","hypothesis":"Unable to answer: \"Which vehicle did I take care of first in February, the bike or the car?\""}
4
+ {"question_id":"gpt4_2312f94c","hypothesis":"Unable to answer: \"Which device did I got first, the Samsung Galaxy S22 or the Dell XPS 13?\""}
5
+ {"question_id":"0bb5a684","hypothesis":"Unable to answer: \"How many days before the team meeting I was preparing for did I attend the workshop on 'Effective Communication in the Workplace'?\""}
6
+ {"question_id":"08f4fc43","hypothesis":"Unable to answer: \"How many days had passed between the Sunday mass at St. Mary's Church and the Ash Wednesday service at the cathedral?\""}
7
+ {"question_id":"2c63a862","hypothesis":"Unable to answer: \"How many days did it take for me to find a house I loved after starting to work with Rachel?\""}
8
+ {"question_id":"gpt4_385a5000","hypothesis":"Unable to answer: \"Which seeds were started first, the tomatoes or the marigolds?\""}
9
+ {"question_id":"2a1811e2","hypothesis":"Unable to answer: \"How many days had passed between the Hindu festival of Holi and the Sunday mass at St. Mary's Church?\""}
10
+ {"question_id":"bbf86515","hypothesis":"Unable to answer: \"How many days before the 'Rack Fest' did I participate in the 'Turbocharged Tuesdays' event?\""}
11
+ {"question_id":"gpt4_5dcc0aab","hypothesis":"Unable to answer: \"Which pair of shoes did I clean last month?\""}
12
+ {"question_id":"gpt4_0b2f1d21","hypothesis":"Unable to answer: \"Which event happened first, the purchase of the coffee maker or the malfunction of the stand mixer?\""}
13
+ {"question_id":"f0853d11","hypothesis":"Unable to answer: \"How many days had passed between the 'Walk for Hunger' event and the 'Coastal Cleanup' event?\""}
14
+ {"question_id":"gpt4_6ed717ea","hypothesis":"Unable to answer: \"Which item did I purchase first, the dog bed for Max or the training pads for Luna?\""}
15
+ {"question_id":"gpt4_70e84552","hypothesis":"Unable to answer: \"Which task did I complete first, fixing the fence or trimming the goats' hooves?\""}
16
+ {"question_id":"a3838d2b","hypothesis":"Unable to answer: \"How many charity events did I participate in before the 'Run for the Cure' event?\""}
17
+ {"question_id":"gpt4_93159ced","hypothesis":"Unable to answer: \"How long have I been working before I started my current job at NovaTech?\""}
18
+ {"question_id":"gpt4_2d58bcd6","hypothesis":"Unable to answer: \"Which book did I finish reading first, 'The Hate U Give' or 'The Nightingale'?\""}
19
+ {"question_id":"gpt4_65aabe59","hypothesis":"Unable to answer: \"Which device did I set up first, the smart thermostat or the mesh network system?\""}
20
+ {"question_id":"982b5123","hypothesis":"Unable to answer: \"How many months ago did I book the Airbnb in San Francisco?\""}
21
+ {"question_id":"b9cfe692","hypothesis":"Unable to answer: \"How long did I take to finish 'The Seven Husbands of Evelyn Hugo' and 'The Nightingale' combined?\""}
22
+ {"question_id":"gpt4_4edbafa2","hypothesis":"Unable to answer: \"What was the date on which I attended the first BBQ event in June?\""}
23
+ {"question_id":"c8090214","hypothesis":"Unable to answer: \"How many days before I bought the iPhone 13 Pro did I attend the Holiday Market?\""}
24
+ {"question_id":"gpt4_483dd43c","hypothesis":"Unable to answer: \"Which show did I start watching first, 'The Crown' or 'Game of Thrones'?\""}
25
+ {"question_id":"e4e14d04","hypothesis":"Unable to answer: \"How long had I been a member of 'Book Lovers Unite' when I attended the meetup?\""}
26
+ {"question_id":"c9f37c46","hypothesis":"Unable to answer: \"How long had I been watching stand-up comedy specials regularly when I attended the open mic night at the local comedy club?\""}
27
+ {"question_id":"gpt4_2c50253f","hypothesis":"Unable to answer: \"What time do I wake up on Tuesdays and Thursdays?\""}
28
+ {"question_id":"dcfa8644","hypothesis":"Unable to answer: \"How many days had passed since I bought my Adidas running shoes when I realized one of the shoelaces on my old Converse sneakers had broken?\""}
29
+ {"question_id":"gpt4_b4a80587","hypothesis":"Unable to answer: \"Which event happened first, the road trip to the coast or the arrival of the new prime lens?\""}
30
+ {"question_id":"gpt4_9a159967","hypothesis":"Unable to answer: \"Which airline did I fly with the most in March and April?\""}
31
+ {"question_id":"cc6d1ec1","hypothesis":"Unable to answer: \"How long had I been bird watching when I attended the bird watching workshop?\""}
32
+ {"question_id":"gpt4_8c8961ae","hypothesis":"Unable to answer: \"Which trip did I take first, the one to Europe with family or the solo trip to Thailand?\""}
33
+ {"question_id":"gpt4_d9af6064","hypothesis":"Unable to answer: \"Which device did I set up first, the smart thermostat or the new router?\""}
34
+ {"question_id":"gpt4_7de946e7","hypothesis":"Unable to answer: \"Which health issue did I deal with first, the persistent cough or the skin tag removal?\""}
35
+ {"question_id":"d01c6aa8","hypothesis":"Unable to answer: \"How old was I when I moved to the United States?\""}
36
+ {"question_id":"993da5e2","hypothesis":"Unable to answer: \"How long had I been using the new area rug when I rearranged my living room furniture?\""}
37
+ {"question_id":"a3045048","hypothesis":"Unable to answer: \"How many days before my best friend's birthday party did I order her gift?\""}
38
+ {"question_id":"gpt4_d31cdae3","hypothesis":"Unable to answer: \"Which trip did the narrator take first, the solo trip to Europe or the family road trip across the American Southwest?\""}
39
+ {"question_id":"gpt4_cd90e484","hypothesis":"Unable to answer: \"How long did I use my new binoculars before I saw the American goldfinches returning to the area?\""}
40
+ {"question_id":"gpt4_88806d6e","hypothesis":"Unable to answer: \"Who did I meet first, Mark and Sarah or Tom?\""}
41
+ {"question_id":"gpt4_4cd9eba1","hypothesis":"Unable to answer: \"How many weeks have I been accepted into the exchange program when I started attending the pre-departure orientation sessions?\""}
42
+ {"question_id":"gpt4_93f6379c","hypothesis":"Unable to answer: \"Which group did I join first, 'Page Turners' or 'Marketing Professionals'?\""}
43
+ {"question_id":"b29f3365","hypothesis":"Unable to answer: \"How long had I been taking guitar lessons when I bought the new guitar amp?\""}
44
+ {"question_id":"gpt4_2f56ae70","hypothesis":"Unable to answer: \"Which streaming service did I start using most recently?\""}
45
+ {"question_id":"6613b389","hypothesis":"Unable to answer: \"How many months before my anniversary did Rachel get engaged?\""}
46
+ {"question_id":"gpt4_78cf46a3","hypothesis":"Unable to answer: \"Which event happened first, the narrator losing their phone charger or the narrator receiving their new phone case?\""}
47
+ {"question_id":"gpt4_0a05b494","hypothesis":"Unable to answer: \"Who did I meet first, the woman selling jam at the farmer's market or the tourist from Australia?\""}
48
+ {"question_id":"gpt4_1a1dc16d","hypothesis":"Unable to answer: \"Which event happened first, the meeting with Rachel or the pride parade?\""}
49
+ {"question_id":"gpt4_2f584639","hypothesis":"Unable to answer: \"Which gift did I buy first, the necklace for my sister or the photo album for my mom?\""}
50
+ {"question_id":"gpt4_213fd887","hypothesis":"Unable to answer: \"Which event did I participate in first, the volleyball league or the charity 5K run to raise money for a local children's hospital?\""}
51
+ {"question_id":"gpt4_5438fa52","hypothesis":"Unable to answer: \"Which event happened first, my attendance at a cultural festival or the start of my Spanish classes?\""}
52
+ {"question_id":"gpt4_c27434e8","hypothesis":"Unable to answer: \"Which project did I start first, the Ferrari model or the Japanese Zero fighter plane model?\""}
53
+ {"question_id":"gpt4_fe651585","hypothesis":"Unable to answer: \"Who became a parent first, Rachel or Alex?\""}
54
+ {"question_id":"8c18457d","hypothesis":"Unable to answer: \"How many days had passed between the day I bought a gift for my brother's graduation ceremony and the day I bought a birthday gift for my best friend?\""}
55
+ {"question_id":"gpt4_70e84552_abs","hypothesis":"Unable to answer: \"Which task did I complete first, fixing the fence or purchasing three cows from Peter?\""}
56
+ {"question_id":"gpt4_93159ced_abs","hypothesis":"Unable to answer: \"How long have I been working before I started my current job at Google?\""}
57
+ {"question_id":"982b5123_abs","hypothesis":"Unable to answer: \"When did I book the Airbnb in Sacramento?\""}
58
+ {"question_id":"c8090214_abs","hypothesis":"Unable to answer: \"How many days before I bought my iPad did I attend the Holiday Market?\""}
59
+ {"question_id":"gpt4_c27434e8_abs","hypothesis":"Unable to answer: \"Which project did I start first, the Ferrari model or the Porsche 991 Turbo S model?\""}
60
+ {"question_id":"gpt4_fe651585_abs","hypothesis":"Unable to answer: \"Who became a parent first, Tom or Alex?\""}
61
+ {"question_id":"0a995998","hypothesis":"Unable to answer: \"How many items of clothing do I need to pick up or return from a store?\""}
62
+ {"question_id":"6d550036","hypothesis":"Unable to answer: \"How many projects have I led or am currently leading?\""}
63
+ {"question_id":"gpt4_59c863d7","hypothesis":"Unable to answer: \"How many model kits have I worked on or bought?\""}
64
+ {"question_id":"b5ef892d","hypothesis":"Unable to answer: \"How many days did I spend on camping trips in the United States this year?\""}
65
+ {"question_id":"e831120c","hypothesis":"Unable to answer: \"How many weeks did it take me to watch all the Marvel Cinematic Universe movies and the main Star Wars films?\""}
66
+ {"question_id":"3a704032","hypothesis":"Unable to answer: \"How many plants did I acquire in the last month?\""}
67
+ {"question_id":"gpt4_d84a3211","hypothesis":"Unable to answer: \"How much total money have I spent on bike-related expenses since the start of the year?\""}
68
+ {"question_id":"aae3761f","hypothesis":"Unable to answer: \"How many hours in total did I spend driving to my three road trip destinations combined?\""}
69
+ {"question_id":"gpt4_f2262a51","hypothesis":"Unable to answer: \"How many different doctors did I visit?\""}
70
+ {"question_id":"dd2973ad","hypothesis":"Unable to answer: \"What time did I go to bed on the day before I had a doctor's appointment?\""}
71
+ {"question_id":"c4a1ceb8","hypothesis":"Unable to answer: \"How many different types of citrus fruits have I used in my cocktail recipes?\""}
72
+ {"question_id":"gpt4_a56e767c","hypothesis":"Unable to answer: \"How many movie festivals that I attended?\""}
73
+ {"question_id":"6cb6f249","hypothesis":"Unable to answer: \"How many days did I take social media breaks in total?\""}
74
+ {"question_id":"46a3abf7","hypothesis":"Unable to answer: \"How many tanks do I currently have, including the one I set up for my friend's kid?\""}
75
+ {"question_id":"36b9f61e","hypothesis":"Unable to answer: \"What is the total amount I spent on luxury items in the past few months?\""}
76
+ {"question_id":"28dc39ac","hypothesis":"Unable to answer: \"How many hours have I spent playing games in total?\""}
77
+ {"question_id":"gpt4_2f8be40d","hypothesis":"Unable to answer: \"How many weddings have I attended in this year?\""}
78
+ {"question_id":"2e6d26dc","hypothesis":"Unable to answer: \"How many babies were born to friends and family members in the last few months?\""}
79
+ {"question_id":"gpt4_15e38248","hypothesis":"Unable to answer: \"How many pieces of furniture did I buy, assemble, sell, or fix in the past few months?\""}
80
+ {"question_id":"88432d0a","hypothesis":"Unable to answer: \"How many times did I bake something in the past two weeks?\""}
81
+ {"question_id":"80ec1f4f","hypothesis":"Unable to answer: \"How many different museums or galleries did I visit in the month of February?\""}
82
+ {"question_id":"d23cf73b","hypothesis":"Unable to answer: \"How many different cuisines have I learned to cook or tried out in the past few months?\""}
83
+ {"question_id":"gpt4_7fce9456","hypothesis":"Unable to answer: \"How many properties did I view before making an offer on the townhouse in the Brookside neighborhood?\""}
84
+ {"question_id":"d682f1a2","hypothesis":"Unable to answer: \"How many different types of food delivery services have I used recently?\""}
85
+ {"question_id":"7024f17c","hypothesis":"Unable to answer: \"How many hours of jogging and yoga did I do last week?\""}
86
+ {"question_id":"gpt4_5501fe77","hypothesis":"Unable to answer: \"Which social media platform did I gain the most followers on over the past month?\""}
87
+ {"question_id":"gpt4_2ba83207","hypothesis":"Unable to answer: \"Which grocery store did I spend the most money at in the past month?\""}
88
+ {"question_id":"2318644b","hypothesis":"Unable to answer: \"How much more did I spend on accommodations per night in Hawaii compared to Tokyo?\""}
89
+ {"question_id":"2ce6a0f2","hypothesis":"Unable to answer: \"How many different art-related events did I attend in the past month?\""}
90
+ {"question_id":"gpt4_d12ceb0e","hypothesis":"Unable to answer: \"What is the average age of me, my parents, and my grandparents?\""}
91
+ {"question_id":"00ca467f","hypothesis":"Unable to answer: \"How many doctor's appointments did I go to in March?\""}
92
+ {"question_id":"b3c15d39","hypothesis":"Unable to answer: \"How many days did it take for me to receive the new remote shutter release after I ordered it?\""}
93
+ {"question_id":"gpt4_31ff4165","hypothesis":"Unable to answer: \"How many health-related devices do I use in a day?\""}
94
+ {"question_id":"eeda8a6d","hypothesis":"Unable to answer: \"How many fish are there in total in both of my aquariums?\""}
95
+ {"question_id":"2788b940","hypothesis":"Unable to answer: \"How many fitness classes do I attend in a typical week?\""}
96
+ {"question_id":"60bf93ed","hypothesis":"Unable to answer: \"How many days did it take for my laptop backpack to arrive after I bought it?\""}
97
+ {"question_id":"9d25d4e0","hypothesis":"Unable to answer: \"How many pieces of jewelry did I acquire in the last two months?\""}
98
+ {"question_id":"129d1232","hypothesis":"Unable to answer: \"How much money did I raise in total through all the charity events I participated in?\""}
99
+ {"question_id":"60472f9c","hypothesis":"Unable to answer: \"How many projects have I been working on simultaneously, excluding my thesis?\""}
100
+ {"question_id":"gpt4_194be4b3","hypothesis":"Unable to answer: \"How many musical instruments do I currently own?\""}
101
+ {"question_id":"a9f6b44c","hypothesis":"Unable to answer: \"How many bikes did I service or plan to service in March?\""}
102
+ {"question_id":"d851d5ba","hypothesis":"Unable to answer: \"How much money did I raise for charity in total?\""}
103
+ {"question_id":"5a7937c8","hypothesis":"Unable to answer: \"How many days did I spend participating in faith-related activities in December?\""}
104
+ {"question_id":"gpt4_ab202e7f","hypothesis":"Unable to answer: \"How many kitchen items did I replace or fix?\""}
105
+ {"question_id":"gpt4_e05b82a6","hypothesis":"Unable to answer: \"How many times did I ride rollercoasters across all the events I attended from July to October?\""}
106
+ {"question_id":"gpt4_731e37d7","hypothesis":"Unable to answer: \"How much total money did I spend on attending workshops in the last four months?\""}
107
+ {"question_id":"edced276","hypothesis":"Unable to answer: \"How many days did I spend in total traveling in Hawaii and in New York City?\""}
108
+ {"question_id":"10d9b85a","hypothesis":"Unable to answer: \"How many days did I spend attending workshops, lectures, and conferences in April?\""}
109
+ {"question_id":"e3038f8c","hypothesis":"Unable to answer: \"How many rare items do I have in total?\""}
110
+ {"question_id":"2b8f3739","hypothesis":"Unable to answer: \"What is the total amount of money I earned from selling my products at the markets?\""}
111
+ {"question_id":"1a8a66a6","hypothesis":"Unable to answer: \"How many magazine subscriptions do I currently have?\""}
112
+ {"question_id":"c2ac3c61","hypothesis":"Unable to answer: \"How many online courses have I completed in total?\""}
113
+ {"question_id":"bf659f65","hypothesis":"Unable to answer: \"How many music albums or EPs have I purchased or downloaded?\""}
114
+ {"question_id":"gpt4_372c3eed","hypothesis":"Unable to answer: \"How many years in total did I spend in formal education from high school to the completion of my Bachelor's degree?\""}
115
+ {"question_id":"gpt4_2f91af09","hypothesis":"Unable to answer: \"How many total pieces of writing have I completed since I started writing again three weeks ago, including short stories, poems, and pieces for the writing challenge?\""}
116
+ {"question_id":"81507db6","hypothesis":"Unable to answer: \"How many graduation ceremonies have I attended in the past three months?\""}
117
+ {"question_id":"88432d0a_abs","hypothesis":"Unable to answer: \"How many times did I bake egg tarts in the past two weeks?\""}
118
+ {"question_id":"80ec1f4f_abs","hypothesis":"Unable to answer: \"How many different museums or galleries did I visit in December?\""}
119
+ {"question_id":"eeda8a6d_abs","hypothesis":"Unable to answer: \"How many fish are there in my 30-gallon tank?\""}
120
+ {"question_id":"60bf93ed_abs","hypothesis":"Unable to answer: \"How many days did it take for my iPad case to arrive after I bought it?\""}
121
+ {"question_id":"edced276_abs","hypothesis":"Unable to answer: \"How many days did I spend in total traveling in Hawaii and in Seattle?\""}
122
+ {"question_id":"gpt4_372c3eed_abs","hypothesis":"Unable to answer: \"How many years in total did I spend in formal education from high school to the completion of my Master's degree?\""}
123
+ {"question_id":"6a1eabeb","hypothesis":"Unable to answer: \"What was my personal best time in the charity 5K run?\""}
124
+ {"question_id":"6aeb4375","hypothesis":"Unable to answer: \"How many Korean restaurants have I tried in my city?\""}
125
+ {"question_id":"830ce83f","hypothesis":"Unable to answer: \"Where did Rachel move to after her recent relocation?\""}
126
+ {"question_id":"852ce960","hypothesis":"Unable to answer: \"What was the amount I was pre-approved for when I got my mortgage from Wells Fargo?\""}
127
+ {"question_id":"945e3d21","hypothesis":"Unable to answer: \"How often do I attend yoga classes to help with my anxiety?\""}
128
+ {"question_id":"d7c942c3","hypothesis":"Unable to answer: \"Is my mom using the same grocery list method as me?\""}
129
+ {"question_id":"71315a70","hypothesis":"Unable to answer: \"How many hours have I spent on my abstract ocean sculpture?\""}
130
+ {"question_id":"89941a93","hypothesis":"Unable to answer: \"How many bikes do I currently own?\""}
131
+ {"question_id":"ce6d2d27","hypothesis":"Unable to answer: \"What day of the week do I take a cocktail-making class?\""}
132
+ {"question_id":"9ea5eabc","hypothesis":"Unable to answer: \"Where did I go on my most recent family trip?\""}
133
+ {"question_id":"07741c44","hypothesis":"Unable to answer: \"Where do I initially keep my old sneakers?\""}
134
+ {"question_id":"a1eacc2a","hypothesis":"Unable to answer: \"How many short stories have I written since I started writing regularly?\""}
135
+ {"question_id":"184da446","hypothesis":"Unable to answer: \"How many pages of 'A Short History of Nearly Everything' have I read so far?\""}
136
+ {"question_id":"031748ae","hypothesis":"Unable to answer: \"How many engineers do I lead when I just started my new role as Senior Software Engineer? How many engineers do I lead now?\""}
137
+ {"question_id":"4d6b87c8","hypothesis":"Unable to answer: \"How many titles are currently on my to-watch list?\""}
138
+ {"question_id":"0f05491a","hypothesis":"Unable to answer: \"How many stars do I need to reach the gold level on my Starbucks Rewards app?\""}
139
+ {"question_id":"08e075c7","hypothesis":"Unable to answer: \"How long have I been using my Fitbit Charge 3?\""}
140
+ {"question_id":"f9e8c073","hypothesis":"Unable to answer: \"How many sessions of the bereavement support group did I attend?\""}
141
+ {"question_id":"41698283","hypothesis":"Unable to answer: \"What type of camera lens did I purchase most recently?\""}
142
+ {"question_id":"2698e78f","hypothesis":"Unable to answer: \"How often do I see my therapist, Dr. Smith?\""}
143
+ {"question_id":"b6019101","hypothesis":"Unable to answer: \"How many MCU films did I watch in the last 3 months?\""}
144
+ {"question_id":"45dc21b6","hypothesis":"Unable to answer: \"How many of Emma's recipes have I tried out?\""}
145
+ {"question_id":"5a4f22c0","hypothesis":"Unable to answer: \"What company is Rachel, an old colleague from my previous company, currently working at?\""}
146
+ {"question_id":"6071bd76","hypothesis":"Unable to answer: \"For the coffee-to-water ratio in my French press, did I switch to more water per tablespoon of coffee, or less?\""}
147
+ {"question_id":"e493bb7c","hypothesis":"Unable to answer: \"Where is the painting 'Ethereal Dreams' by Emma Taylor currently hanging?\""}
148
+ {"question_id":"618f13b2","hypothesis":"Unable to answer: \"How many times have I worn my new black Converse Chuck Taylor All Star sneakers?\""}
149
+ {"question_id":"72e3ee87","hypothesis":"Unable to answer: \"How many episodes of the Science series have I completed on Crash Course?\""}
150
+ {"question_id":"c4ea545c","hypothesis":"Unable to answer: \"Do I go to the gym more frequently than I did previously?\""}
151
+ {"question_id":"01493427","hypothesis":"Unable to answer: \"How many new postcards have I added to my collection since I started collecting again?\""}
152
+ {"question_id":"6a27ffc2","hypothesis":"Unable to answer: \"How many videos of Corey Schafer's Python programming series have I completed so far?\""}
153
+ {"question_id":"2133c1b5","hypothesis":"Unable to answer: \"How long have I been living in my current apartment in Harajuku?\""}
154
+ {"question_id":"18bc8abd","hypothesis":"Unable to answer: \"What brand of BBQ sauce am I currently obsessed with?\""}
155
+ {"question_id":"db467c8c","hypothesis":"Unable to answer: \"How long have my parents been staying with me in the US?\""}
156
+ {"question_id":"7a87bd0c","hypothesis":"Unable to answer: \"How long have I been sticking to my daily tidying routine?\""}
157
+ {"question_id":"e61a7584","hypothesis":"Unable to answer: \"How long have I had my cat, Luna?\""}
158
+ {"question_id":"1cea1afa","hypothesis":"Unable to answer: \"How many Instagram followers do I currently have?\""}
159
+ {"question_id":"ed4ddc30","hypothesis":"Unable to answer: \"How many dozen eggs do we currently have stocked up in our refrigerator?\""}
160
+ {"question_id":"8fb83627","hypothesis":"Unable to answer: \"How many issues of National Geographic have I finished reading?\""}
161
+ {"question_id":"b01defab","hypothesis":"Unable to answer: \"Did I finish reading 'The Nightingale' by Kristin Hannah?\""}
162
+ {"question_id":"22d2cb42","hypothesis":"Unable to answer: \"Where did I get my guitar serviced?\""}
163
+ {"question_id":"0e4e4c46","hypothesis":"Unable to answer: \"What is my current highest score in Ticket to Ride?\""}
164
+ {"question_id":"4b24c848","hypothesis":"Unable to answer: \"How many tops have I bought from H&M so far?\""}
165
+ {"question_id":"7e974930","hypothesis":"Unable to answer: \"How much did I earn at the Downtown Farmers Market on my most recent visit?\""}
166
+ {"question_id":"603deb26","hypothesis":"Unable to answer: \"How many times have I tried making a Negroni at home since my friend Emma showed me how to make it?\""}
167
+ {"question_id":"59524333","hypothesis":"Unable to answer: \"What time do I usually go to the gym?\""}
168
+ {"question_id":"5831f84d","hypothesis":"Unable to answer: \"How many Crash Course videos have I watched in the past few weeks?\""}
169
+ {"question_id":"eace081b","hypothesis":"Unable to answer: \"Where am I planning to stay for my birthday trip to Hawaii?\""}
170
+ {"question_id":"affe2881","hypothesis":"Unable to answer: \"How many different species of birds have I seen in my local park?\""}
171
+ {"question_id":"50635ada","hypothesis":"Unable to answer: \"What was my previous frequent flyer status on United Airlines before I got the current status?\""}
172
+ {"question_id":"e66b632c","hypothesis":"Unable to answer: \"What was my previous personal best time for the charity 5K run?\""}
173
+ {"question_id":"0ddfec37","hypothesis":"Unable to answer: \"How many autographed baseballs have I added to my collection in the first three months of collection?\""}
174
+ {"question_id":"f685340e","hypothesis":"Unable to answer: \"How often do I play tennis with my friends at the local park previously? How often do I play now?\""}
175
+ {"question_id":"cc5ded98","hypothesis":"Unable to answer: \"How much time do I dedicate to coding exercises each day?\""}
176
+ {"question_id":"dfde3500","hypothesis":"Unable to answer: \"What day of the week did I meet with my previous language exchange tutor Juan?\""}
177
+ {"question_id":"69fee5aa","hypothesis":"Unable to answer: \"How many pre-1920 American coins do I have in my collection?\""}
178
+ {"question_id":"7401057b","hypothesis":"Unable to answer: \"How many free night's stays can I redeem at any Hilton property with my accumulated points?\""}
179
+ {"question_id":"cf22b7bf","hypothesis":"Unable to answer: \"How much weight have I lost since I started going to the gym consistently?\""}
180
+ {"question_id":"a2f3aa27","hypothesis":"Unable to answer: \"How many followers do I have on Instagram now?\""}
181
+ {"question_id":"c7dc5443","hypothesis":"Unable to answer: \"What is my current record in the recreational volleyball league?\""}
182
+ {"question_id":"06db6396","hypothesis":"Unable to answer: \"How many projects have I completed since starting painting classes?\""}
183
+ {"question_id":"3ba21379","hypothesis":"Unable to answer: \"What type of vehicle model am I currently working on?\""}
184
+ {"question_id":"9bbe84a2","hypothesis":"Unable to answer: \"What was my previous goal for my Apex Legends level before I updated my goal?\""}
185
+ {"question_id":"10e09553","hypothesis":"Unable to answer: \"How many largemouth bass did I catch with Alex on the earlier fishing trip to Lake Michigan before the 7/22 trip?\""}
186
+ {"question_id":"dad224aa","hypothesis":"Unable to answer: \"What time do I wake up on Saturday mornings?\""}
187
+ {"question_id":"ba61f0b9","hypothesis":"Unable to answer: \"How many women are on the team led by my former manager Rachel?\""}
188
+ {"question_id":"42ec0761","hypothesis":"Unable to answer: \"Do I have a spare screwdriver for opening up my laptop?\""}
189
+ {"question_id":"5c40ec5b","hypothesis":"Unable to answer: \"How many times have I met up with Alex from Germany?\""}
190
+ {"question_id":"c6853660","hypothesis":"Unable to answer: \"Did I mostly recently increase or decrease the limit on the number of cups of coffee in the morning?\""}
191
+ {"question_id":"26bdc477","hypothesis":"Unable to answer: \"How many trips have I taken my Canon EOS 80D camera on?\""}
192
+ {"question_id":"0977f2af","hypothesis":"Unable to answer: \"What new kitchen gadget did I invest in before getting the Air Fryer?\""}
193
+ {"question_id":"6aeb4375_abs","hypothesis":"Unable to answer: \"How many Italian restaurants have I tried in my city?\""}
194
+ {"question_id":"031748ae_abs","hypothesis":"Unable to answer: \"How many engineers do I lead when I just started my new role as Software Engineer Manager?\""}
195
+ {"question_id":"2698e78f_abs","hypothesis":"Unable to answer: \"How often do I see Dr. Johnson?\""}
196
+ {"question_id":"2133c1b5_abs","hypothesis":"Unable to answer: \"How long have I been living in my current apartment in Shinjuku?\""}
197
+ {"question_id":"0ddfec37_abs","hypothesis":"Unable to answer: \"How many autographed football have I added to my collection in the first three months of collection?\""}
198
+ {"question_id":"f685340e_abs","hypothesis":"Unable to answer: \"How often do I play table tennis with my friends at the local park?\""}
199
+ {"question_id":"89941a94","hypothesis":"Unable to answer: \"Before I purchased the gravel bike, do I have other bikes in addition to my mountain bike and my commuter bike?\""}
200
+ {"question_id":"07741c45","hypothesis":"Unable to answer: \"Where do I currently keep my old sneakers?\""}
201
+ {"question_id":"8a2466db","hypothesis":"Unable to answer: \"Can you recommend some resources where I can learn more about video editing?\""}
202
+ {"question_id":"06878be2","hypothesis":"Unable to answer: \"Can you suggest some accessories that would complement my current photography setup?\""}
203
+ {"question_id":"75832dbd","hypothesis":"Unable to answer: \"Can you recommend some recent publications or conferences that I might find interesting?\""}
204
+ {"question_id":"0edc2aef","hypothesis":"Unable to answer: \"Can you suggest a hotel for my upcoming trip to Miami?\""}
205
+ {"question_id":"35a27287","hypothesis":"Unable to answer: \"Can you recommend some interesting cultural events happening around me this weekend?\""}
206
+ {"question_id":"32260d93","hypothesis":"Unable to answer: \"Can you recommend a show or movie for me to watch tonight?\""}
207
+ {"question_id":"195a1a1b","hypothesis":"Unable to answer: \"Can you suggest some activities that I can do in the evening?\""}
208
+ {"question_id":"afdc33df","hypothesis":"Unable to answer: \"My kitchen's becoming a bit of a mess again. Any tips for keeping it clean?\""}
209
+ {"question_id":"caf03d32","hypothesis":"Unable to answer: \"I've been struggling with my slow cooker recipes. Any advice on getting better results?\""}
210
+ {"question_id":"54026fce","hypothesis":"Unable to answer: \"I've been thinking about ways to stay connected with my colleagues. Any suggestions?\""}
211
+ {"question_id":"06f04340","hypothesis":"Unable to answer: \"What should I serve for dinner this weekend with my homegrown ingredients?\""}
212
+ {"question_id":"6b7dfb22","hypothesis":"Unable to answer: \"I've been feeling a bit stuck with my paintings lately. Do you have any ideas on how I can find new inspiration?\""}
213
+ {"question_id":"1a1907b4","hypothesis":"Unable to answer: \"I've been thinking about making a cocktail for an upcoming get-together, but I'm not sure which one to choose. Any suggestions?\""}
214
+ {"question_id":"09d032c9","hypothesis":"Unable to answer: \"I've been having trouble with the battery life on my phone lately. Any tips?\""}
215
+ {"question_id":"38146c39","hypothesis":"Unable to answer: \"I've been feeling like my chocolate chip cookies need something extra. Any advice?\""}
216
+ {"question_id":"d24813b1","hypothesis":"Unable to answer: \"I'm thinking of inviting my colleagues over for a small gathering. Any tips on what to bake?\""}
217
+ {"question_id":"57f827a0","hypothesis":"Unable to answer: \"I was thinking about rearranging the furniture in my bedroom this weekend. Any tips?\""}
218
+ {"question_id":"95228167","hypothesis":"Unable to answer: \"I'm getting excited about my visit to the music store this weekend. Any tips on what to look for in a new guitar?\""}
219
+ {"question_id":"505af2f5","hypothesis":"Unable to answer: \"I was thinking of trying a new coffee creamer recipe. Any recommendations?\""}
220
+ {"question_id":"75f70248","hypothesis":"Unable to answer: \"I've been sneezing quite a bit lately. Do you think it might be my living room?\""}
221
+ {"question_id":"d6233ab6","hypothesis":"Unable to answer: \"I've been feeling nostalgic lately. Do you think it would be a good idea to attend my high school reunion?\""}
222
+ {"question_id":"1da05512","hypothesis":"Unable to answer: \"I'm trying to decide whether to buy a NAS device now or wait. What do you think?\""}
223
+ {"question_id":"fca70973","hypothesis":"Unable to answer: \"I am planning another theme park weekend; do you have any suggestions?\""}
224
+ {"question_id":"b6025781","hypothesis":"Unable to answer: \"I'm planning my meal prep next week, any suggestions for new recipes?\""}
225
+ {"question_id":"a89d7624","hypothesis":"Unable to answer: \"I'm planning a trip to Denver soon. Any suggestions on what to do there?\""}
226
+ {"question_id":"b0479f84","hypothesis":"Unable to answer: \"I've got some free time tonight, any documentary recommendations?\""}
227
+ {"question_id":"1d4e3b97","hypothesis":"Unable to answer: \"I noticed my bike seems to be performing even better during my Sunday group rides. Could there be a reason for this?\""}
228
+ {"question_id":"07b6f563","hypothesis":"Unable to answer: \"Can you suggest some useful accessories for my phone?\""}
229
+ {"question_id":"1c0ddc50","hypothesis":"Unable to answer: \"Can you suggest some activities I can do during my commute to work?\""}
230
+ {"question_id":"0a34ad58","hypothesis":"Unable to answer: \"I’m a bit anxious about getting around Tokyo. Do you have any helpful tips?\""}
231
+ {"question_id":"7161e7e2","hypothesis":"Unable to answer: \"I'm checking our previous chat about the shift rotation sheet for GM social media agents. Can you remind me what was the rotation for Admon on a Sunday?\""}
232
+ {"question_id":"c4f10528","hypothesis":"Unable to answer: \"I'm planning to visit Bandung again and I was wondering if you could remind me of the name of that restaurant in Cihampelas Walk that serves a great Nasi Goreng?\""}
233
+ {"question_id":"89527b6b","hypothesis":"Unable to answer: \"I'm going back to our previous conversation about the children's book on dinosaurs. Can you remind me what color was the scaly body of the Plesiosaur in the image?\""}
234
+ {"question_id":"e9327a54","hypothesis":"Unable to answer: \"I'm planning to revisit Orlando. I was wondering if you could remind me of that unique dessert shop with the giant milkshakes we talked about last time?\""}
235
+ {"question_id":"4c36ccef","hypothesis":"Unable to answer: \"Can you remind me of the name of the romantic Italian restaurant in Rome you recommended for dinner?\""}
236
+ {"question_id":"6ae235be","hypothesis":"Unable to answer: \"I remember you told me about the refining processes at CITGO's three refineries earlier. Can you remind me what kind of processes are used at the Lake Charles Refinery?\""}
237
+ {"question_id":"7e00a6cb","hypothesis":"Unable to answer: \"I'm planning my trip to Amsterdam again and I was wondering, what was the name of that hostel near the Red Light District that you recommended last time?\""}
238
+ {"question_id":"1903aded","hypothesis":"Unable to answer: \"I think we discussed work from home jobs for seniors earlier. Can you remind me what was the 7th job in the list you provided?\""}
239
+ {"question_id":"ceb54acb","hypothesis":"Unable to answer: \"In our previous chat, you suggested 'sexual compulsions' and a few other options for alternative terms for certain behaviors. Can you remind me what the other four options were?\""}
240
+ {"question_id":"f523d9fe","hypothesis":"Unable to answer: \"I wanted to check back on our previous conversation about Netflix. I mentioned that I wanted to be able to access all seasons of old shows? Do you remember what show I used as an example, the one that only had the last season available?\""}
241
+ {"question_id":"0e5e2d1a","hypothesis":"Unable to answer: \"I wanted to follow up on our previous conversation about binaural beats for anxiety and depression. Can you remind me how many subjects were in the study published in the journal Music and Medicine that found significant reductions in symptoms of depression, anxiety, and stress?\""}
242
+ {"question_id":"fea54f57","hypothesis":"Unable to answer: \"I was thinking about our previous conversation about the Fifth Album, and I was wondering if you could remind me what song you said best exemplified the band's growth and development as artists?\""}
243
+ {"question_id":"cc539528","hypothesis":"Unable to answer: \"I wanted to follow up on our previous conversation about front-end and back-end development. Can you remind me of the specific back-end programming languages you recommended I learn?\""}
244
+ {"question_id":"dc439ea3","hypothesis":"Unable to answer: \"I was looking back at our previous conversation about Native American powwows and I was wondering, which traditional game did you say was often performed by skilled dancers at powwows?\""}
245
+ {"question_id":"18dcd5a5","hypothesis":"Unable to answer: \"I'm going back to our previous chat about the Lost Temple of the Djinn one-shot. Can you remind me how many mummies the party will face in the temple?\""}
246
+ {"question_id":"488d3006","hypothesis":"Unable to answer: \"I'm planning to go back to the Natural Park of Moncayo mountain in Aragón and I was wondering, what was the name of that hiking trail you recommended that takes you through the park's most stunning landscapes and offers panoramic views of the surrounding mountainside?\""}
247
+ {"question_id":"58470ed2","hypothesis":"Unable to answer: \"I was going through our previous conversation about The Library of Babel, and I wanted to confirm - what did Borges say about the center and circumference of the Library?\""}
248
+ {"question_id":"8cf51dda","hypothesis":"Unable to answer: \"I'm going back to our previous conversation about the grant aim page on molecular subtypes and endometrial cancer. Can you remind me what were the three objectives we outlined for the project?\""}
249
+ {"question_id":"1d4da289","hypothesis":"Unable to answer: \"I was thinking about our previous conversation about data privacy and security. You mentioned that companies use two-factor authentication to enhance security. Can you remind me what kind of two-factor authentication methods you were referring to?\""}
250
+ {"question_id":"8464fc84","hypothesis":"Unable to answer: \"I'm planning to visit the Vatican again and I was wondering if you could remind me of the name of that famous deli near the Vatican that serves the best cured meats and cheeses?\""}
251
+ {"question_id":"8aef76bc","hypothesis":"Unable to answer: \"I'm going back to our previous conversation about DIY home decor projects using recycled materials. Can you remind me what sealant you recommended for the newspaper flower vase?\""}
252
+ {"question_id":"71a3fd6b","hypothesis":"Unable to answer: \"I'm planning my trip to Speyer again and I wanted to confirm, what's the phone number of the Speyer tourism board that you provided me earlier?\""}
253
+ {"question_id":"2bf43736","hypothesis":"Unable to answer: \"I was going through our previous chat and I wanted to clarify something about the prayer of beginners in Tanqueray's Spiritual Life treatise. Can you remind me which chapter of the second part discusses vocal prayer and meditation?\""}
254
+ {"question_id":"70b3e69b","hypothesis":"Unable to answer: \"I was going through our previous conversation about the impact of the political climate in Catalonia on its literature and music. Can you remind me of the example you gave of a Spanish-Catalan singer-songwriter who supports unity between Catalonia and Spain?\""}
255
+ {"question_id":"8752c811","hypothesis":"Unable to answer: \"I remember you provided a list of 100 prompt parameters that I can specify to influence your output. Can you remind me what was the 27th parameter on that list?\""}
256
+ {"question_id":"3249768e","hypothesis":"Unable to answer: \"I'm looking back at our previous conversation about building a cocktail bar. You recommended five bottles to make the widest variety of gin-based cocktails. Can you remind me what the fifth bottle was?\""}
257
+ {"question_id":"1b9b7252","hypothesis":"Unable to answer: \"I wanted to follow up on our previous conversation about mindfulness techniques. You mentioned some great resources for guided imagery exercises, can you remind me of the website that had free exercises like 'The Mountain Meditation' and 'The Body Scan Meditation'?\""}
258
+ {"question_id":"1568498a","hypothesis":"Unable to answer: \"I'm looking back at our previous chess game and I was wondering, what was the move you made after 27. Kg2 Bd5+?\""}
259
+ {"question_id":"6222b6eb","hypothesis":"Unable to answer: \"I was going through our previous conversation about atmospheric correction methods, and I wanted to confirm - you mentioned that 6S, MAJA, and Sen2Cor are all algorithms for atmospheric correction of remote sensing images. Can you remind me which one is implemented in the SIAC_GEE tool?\""}
260
+ {"question_id":"e8a79c70","hypothesis":"Unable to answer: \"I was going through our previous conversation about making a classic French omelette, and I wanted to confirm - how many eggs did you say we need for the recipe?\""}
261
+ {"question_id":"d596882b","hypothesis":"Unable to answer: \"I'm planning another trip to New York City and I was wondering if you could remind me of that vegan eatery you recommended last time, the one with multiple locations throughout the city?\""}
262
+ {"question_id":"e3fc4d6e","hypothesis":"Unable to answer: \"I wanted to follow up on our previous conversation about the fusion breakthrough at Lawrence Livermore National Laboratory. Can you remind me who is the President's Chief Advisor for Science and Technology mentioned in the article?\""}
263
+ {"question_id":"51b23612","hypothesis":"Unable to answer: \"I was going through our previous conversation about political propaganda and humor, and I was wondering if you could remind me of that Soviet cartoon you mentioned that mocked Western culture?\""}
264
+ {"question_id":"3e321797","hypothesis":"Unable to answer: \"I wanted to follow up on our previous conversation about natural remedies for dark circles under the eyes. You mentioned applying tomato juice mixed with lemon juice, how long did you say I should leave it on for?\""}
265
+ {"question_id":"e982271f","hypothesis":"Unable to answer: \"I was going through our previous chat. Can you remind me of the name of the last venue you recommended in the list of popular venues in Portland for indie music shows?\""}
266
+ {"question_id":"352ab8bd","hypothesis":"Unable to answer: \"Can you remind me what was the average improvement in framerate when using the Hardware-Aware Modular Training (HAMT) agent in the 'To Adapt or Not to Adapt? Real-Time Adaptation for Semantic Segmentation' submission?\""}
267
+ {"question_id":"fca762bc","hypothesis":"Unable to answer: \"I wanted to follow up on our previous conversation about language learning apps. You mentioned a few options, and I was wondering if you could remind me of the one that uses mnemonics to help learners memorize words and phrases?\""}
268
+ {"question_id":"7a8d0b71","hypothesis":"Unable to answer: \"I'm looking back at our previous chat about the DHL Wellness Retreats campaign. Can you remind me how much was allocated for influencer marketing in the campaign plan?\""}
269
+ {"question_id":"a40e080f","hypothesis":"Unable to answer: \"I was going through our previous conversation and I was wondering if you could remind me of the two companies you mentioned that prioritize employee safety and well-being like Triumvirate?\""}
270
+ {"question_id":"8b9d4367","hypothesis":"Unable to answer: \"I wanted to follow up on our previous conversation about private sector businesses in Chaudhary. Can you remind me of the company that employs over 40,000 people in the rug-manufacturing industry?\""}
271
+ {"question_id":"5809eb10","hypothesis":"Unable to answer: \"I'm looking back at our previous conversation about the Bajimaya v Reward Homes Pty Ltd case. Can you remind me what year the construction of the house began?\""}
272
+ {"question_id":"41275add","hypothesis":"Unable to answer: \"I wanted to follow up on our previous conversation about YouTube videos for workplace posture. Can you remind me of the Mayo Clinic video you recommended?\""}
273
+ {"question_id":"4388e9dd","hypothesis":"Unable to answer: \"I was going through our previous chat and I was wondering, what was Andy wearing in the script you wrote for the comedy movie scene?\""}
274
+ {"question_id":"4baee567","hypothesis":"Unable to answer: \"I was looking back at our previous chat and I wanted to confirm, how many times did the Chiefs play the Jaguars at Arrowhead Stadium?\""}
275
+ {"question_id":"561fabcd","hypothesis":"Unable to answer: \"I was thinking back to our previous conversation about the Radiation Amplified zombie, and I was wondering if you remembered what we finally decided to name it?\""}
276
+ {"question_id":"b759caee","hypothesis":"Unable to answer: \"I was looking back at our previous conversation about buying unique engagement rings directly from designers. Can you remind me of the Instagram handle of the UK-based designer who works with unusual gemstones?\""}
277
+ {"question_id":"ac031881","hypothesis":"Unable to answer: \"I'm trying to recall what the designation on my jumpsuit was that helped me find the file number in the records room?\""}
278
+ {"question_id":"28bcfaac","hypothesis":"Unable to answer: \"I'm going back to our previous conversation about music theory. You mentioned some online resources for learning music theory. Can you remind me of the website you recommended for free lessons and exercises?\""}
279
+ {"question_id":"16c90bf4","hypothesis":"Unable to answer: \"I'm looking back at our previous conversation about the Seco de Cordero recipe from Ancash. You mentioned using a light or medium-bodied beer, but I was wondering if you could remind me what type of beer you specifically recommended?\""}
280
+ {"question_id":"c8f1aeed","hypothesis":"Unable to answer: \"I wanted to follow up on our previous conversation about fracking in the Marcellus Shale region. You mentioned that some states require fracking companies to monitor groundwater quality at nearby wells before drilling and for a certain period after drilling is complete. Can you remind me which state you mentioned as an example that has this requirement?\""}
281
+ {"question_id":"eaca4986","hypothesis":"Unable to answer: \"I'm looking back at our previous conversation where you created two sad songs for me. Can you remind me what was the chord progression for the chorus in the second song?\""}
282
+ {"question_id":"c7cf7dfd","hypothesis":"Unable to answer: \"I'm going back to our previous conversation about traditional Indian embroidery and tailoring techniques. Can you remind me of the name of that online store based in India that sells traditional Indian fabrics, threads, and embellishments?\""}
283
+ {"question_id":"e48988bc","hypothesis":"Unable to answer: \"I was looking back at our previous conversation about environmentally responsible supply chain practices, and I was wondering if you could remind me of the company you mentioned that's doing a great job with sustainability?\""}
284
+ {"question_id":"1de5cff2","hypothesis":"Unable to answer: \"I was going through our previous conversation about high-end fashion brands, and I was wondering if you could remind me of the brand that uses wild rubber sourced from the Amazon rainforest?\""}
285
+ {"question_id":"65240037","hypothesis":"Unable to answer: \"I remember you told me to dilute tea tree oil with a carrier oil before applying it to my skin. Can you remind me what the recommended ratio is?\""}
286
+ {"question_id":"778164c6","hypothesis":"Unable to answer: \"I was looking back at our previous conversation about Caribbean dishes and I was wondering, what was the name of that Jamaican dish you recommended I try with snapper that has fruit in it?\""}
287
+ {"question_id":"e47becba","hypothesis":"Unable to answer: \"What degree did I graduate with?\""}
288
+ {"question_id":"118b2229","hypothesis":"Unable to answer: \"How long is my daily commute to work?\""}
289
+ {"question_id":"51a45a95","hypothesis":"Unable to answer: \"Where did I redeem a $5 coupon on coffee creamer?\""}
290
+ {"question_id":"58bf7951","hypothesis":"Unable to answer: \"What play did I attend at the local community theater?\""}
291
+ {"question_id":"1e043500","hypothesis":"Unable to answer: \"What is the name of the playlist I created on Spotify?\""}
292
+ {"question_id":"c5e8278d","hypothesis":"Unable to answer: \"What was my last name before I changed it?\""}
293
+ {"question_id":"6ade9755","hypothesis":"Unable to answer: \"Where do I take yoga classes?\""}
294
+ {"question_id":"6f9b354f","hypothesis":"Unable to answer: \"What color did I repaint my bedroom walls?\""}
295
+ {"question_id":"58ef2f1c","hypothesis":"Unable to answer: \"When did I volunteer at the local animal shelter's fundraising dinner?\""}
296
+ {"question_id":"f8c5f88b","hypothesis":"Unable to answer: \"Where did I buy my new tennis racket from?\""}
297
+ {"question_id":"5d3d2817","hypothesis":"Unable to answer: \"What was my previous occupation?\""}
298
+ {"question_id":"7527f7e2","hypothesis":"Unable to answer: \"How much did I spend on a designer handbag?\""}
299
+ {"question_id":"c960da58","hypothesis":"Unable to answer: \"How many playlists do I have on Spotify?\""}
300
+ {"question_id":"3b6f954b","hypothesis":"Unable to answer: \"Where did I attend for my study abroad program?\""}
301
+ {"question_id":"726462e0","hypothesis":"Unable to answer: \"What was the discount I got on my first purchase from the new clothing brand?\""}
302
+ {"question_id":"94f70d80","hypothesis":"Unable to answer: \"How long did it take me to assemble the IKEA bookshelf?\""}
303
+ {"question_id":"66f24dbb","hypothesis":"Unable to answer: \"What did I buy for my sister's birthday gift?\""}
304
+ {"question_id":"ad7109d1","hypothesis":"Unable to answer: \"What speed is my new internet plan?\""}
305
+ {"question_id":"af8d2e46","hypothesis":"Unable to answer: \"How many shirts did I pack for my 5-day trip to Costa Rica?\""}
306
+ {"question_id":"dccbc061","hypothesis":"Unable to answer: \"What was my previous stance on spirituality?\""}
307
+ {"question_id":"c8c3f81d","hypothesis":"Unable to answer: \"What brand are my favorite running shoes?\""}
308
+ {"question_id":"8ebdbe50","hypothesis":"Unable to answer: \"What certification did I complete last month?\""}
309
+ {"question_id":"6b168ec8","hypothesis":"Unable to answer: \"How many bikes do I own?\""}
310
+ {"question_id":"75499fd8","hypothesis":"Unable to answer: \"What breed is my dog?\""}
311
+ {"question_id":"21436231","hypothesis":"Unable to answer: \"How many largemouth bass did I catch on my fishing trip to Lake Michigan?\""}
312
+ {"question_id":"95bcc1c8","hypothesis":"Unable to answer: \"How many amateur comedians did I watch perform at the open mic night?\""}
313
+ {"question_id":"0862e8bf","hypothesis":"Unable to answer: \"What is the name of my cat?\""}
314
+ {"question_id":"853b0a1d","hypothesis":"Unable to answer: \"How old was I when my grandma gave me the silver necklace?\""}
315
+ {"question_id":"a06e4cfe","hypothesis":"Unable to answer: \"What is my preferred gin-to-vermouth ratio for a classic gin martini?\""}
316
+ {"question_id":"37d43f65","hypothesis":"Unable to answer: \"How much RAM did I upgrade my laptop to?\""}
317
+ {"question_id":"b86304ba","hypothesis":"Unable to answer: \"How much is the painting of a sunset worth in terms of the amount I paid for it?\""}
318
+ {"question_id":"d52b4f67","hypothesis":"Unable to answer: \"Where did I attend my cousin's wedding?\""}
319
+ {"question_id":"25e5aa4f","hypothesis":"Unable to answer: \"Where did I complete my Bachelor's degree in Computer Science?\""}
320
+ {"question_id":"caf9ead2","hypothesis":"Unable to answer: \"How long did it take to move to the new apartment?\""}
321
+ {"question_id":"8550ddae","hypothesis":"Unable to answer: \"What type of cocktail recipe did I try last weekend?\""}
322
+ {"question_id":"60d45044","hypothesis":"Unable to answer: \"What type of rice is my favorite?\""}
323
+ {"question_id":"3f1e9474","hypothesis":"Unable to answer: \"Who did I have a conversation with about destiny?\""}
324
+ {"question_id":"86b68151","hypothesis":"Unable to answer: \"Where did I buy my new bookshelf from?\""}
325
+ {"question_id":"577d4d32","hypothesis":"Unable to answer: \"What time do I stop checking work emails and messages?\""}
326
+ {"question_id":"ec81a493","hypothesis":"Unable to answer: \"How many copies of my favorite artist's debut album were released worldwide?\""}
327
+ {"question_id":"15745da0","hypothesis":"Unable to answer: \"How long have I been collecting vintage cameras?\""}
328
+ {"question_id":"e01b8e2f","hypothesis":"Unable to answer: \"Where did I go on a week-long trip with my family?\""}
329
+ {"question_id":"bc8a6e93","hypothesis":"Unable to answer: \"What did I bake for my niece's birthday party?\""}
330
+ {"question_id":"ccb36322","hypothesis":"Unable to answer: \"What is the name of the music streaming service have I been using lately?\""}
331
+ {"question_id":"001be529","hypothesis":"Unable to answer: \"How long did I wait for the decision on my asylum application?\""}
332
+ {"question_id":"b320f3f8","hypothesis":"Unable to answer: \"What type of action figure did I buy from a thrift store?\""}
333
+ {"question_id":"19b5f2b3","hypothesis":"Unable to answer: \"How long was I in Japan for?\""}
334
+ {"question_id":"4fd1909e","hypothesis":"Unable to answer: \"Where did I attend the Imagine Dragons concert?\""}
335
+ {"question_id":"545bd2b5","hypothesis":"Unable to answer: \"How much screen time have I been averaging on Instagram per day?\""}
336
+ {"question_id":"8a137a7f","hypothesis":"Unable to answer: \"What type of bulb did I replace in my bedside lamp?\""}
337
+ {"question_id":"76d63226","hypothesis":"Unable to answer: \"What size is my new Samsung TV?\""}
338
+ {"question_id":"86f00804","hypothesis":"Unable to answer: \"What book am I currently reading?\""}
339
+ {"question_id":"8e9d538c","hypothesis":"Unable to answer: \"How many skeins of worsted weight yarn did I find in my stash?\""}
340
+ {"question_id":"311778f1","hypothesis":"Unable to answer: \"How many hours did I spend watching documentaries on Netflix last month?\""}
341
+ {"question_id":"c19f7a0b","hypothesis":"Unable to answer: \"What time do I usually get home from work on weeknights?\""}
342
+ {"question_id":"4100d0a0","hypothesis":"Unable to answer: \"What is my ethnicity?\""}
343
+ {"question_id":"29f2956b","hypothesis":"Unable to answer: \"How much time do I dedicate to practicing guitar every day?\""}
344
+ {"question_id":"1faac195","hypothesis":"Unable to answer: \"Where does my sister Emily live?\""}
345
+ {"question_id":"faba32e5","hypothesis":"Unable to answer: \"How long did Alex marinate the BBQ ribs in special sauce?\""}
346
+ {"question_id":"f4f1d8a4","hypothesis":"Unable to answer: \"Who gave me a new stand mixer as a birthday gift?\""}
347
+ {"question_id":"c14c00dd","hypothesis":"Unable to answer: \"What brand of shampoo do I currently use?\""}
348
+ {"question_id":"36580ce8","hypothesis":"Unable to answer: \"What health issue did I initially think was just a cold?\""}
349
+ {"question_id":"3d86fd0a","hypothesis":"Unable to answer: \"Where did I meet Sophia?\""}
350
+ {"question_id":"a82c026e","hypothesis":"Unable to answer: \"What game did I finally beat last weekend?\""}
351
+ {"question_id":"0862e8bf_abs","hypothesis":"Unable to answer: \"What is the name of my hamster?\""}
352
+ {"question_id":"15745da0_abs","hypothesis":"Unable to answer: \"How long have I been collecting vintage films?\""}
353
+ {"question_id":"bc8a6e93_abs","hypothesis":"Unable to answer: \"What did I bake for my uncle's birthday party?\""}
354
+ {"question_id":"19b5f2b3_abs","hypothesis":"Unable to answer: \"How long was I in Korea for?\""}
355
+ {"question_id":"29f2956b_abs","hypothesis":"Unable to answer: \"How much time do I dedicate to practicing violin every day?\""}
356
+ {"question_id":"f4f1d8a4_abs","hypothesis":"Unable to answer: \"What did my dad gave me as a birthday gift?\""}
357
+ {"question_id":"gpt4_59149c77","hypothesis":"Unable to answer: \"How many days passed between my visit to the Museum of Modern Art (MoMA) and the 'Ancient Civilizations' exhibit at the Metropolitan Museum of Art?\""}
358
+ {"question_id":"gpt4_f49edff3","hypothesis":"Unable to answer: \"Which three events happened in the order from first to last: the day I helped my friend prepare the nursery, the day I helped my cousin pick out stuff for her baby shower, and the day I ordered a customized phone case for my friend's birthday?\""}
359
+ {"question_id":"71017276","hypothesis":"Unable to answer: \"How many weeks ago did I meet up with my aunt and receive the crystal chandelier?\""}
360
+ {"question_id":"b46e15ed","hypothesis":"Unable to answer: \"How many months have passed since I participated in two charity events in a row, on consecutive days?\""}
361
+ {"question_id":"gpt4_fa19884c","hypothesis":"Unable to answer: \"How many days passed between the day I started playing along to my favorite songs on my old keyboard and the day I discovered a bluegrass band?\""}
362
+ {"question_id":"0bc8ad92","hypothesis":"Unable to answer: \"How many months have passed since I last visited a museum with a friend?\""}
363
+ {"question_id":"af082822","hypothesis":"Unable to answer: \"How many weeks ago did I attend the friends and family sale at Nordstrom?\""}
364
+ {"question_id":"gpt4_4929293a","hypothesis":"Unable to answer: \"Which event happened first, my cousin's wedding or Michael's engagement party?\""}
365
+ {"question_id":"gpt4_b5700ca9","hypothesis":"Unable to answer: \"How many days ago did I attend the Maundy Thursday service at the Episcopal Church?\""}
366
+ {"question_id":"9a707b81","hypothesis":"Unable to answer: \"How many days ago did I attend a baking class at a local culinary school when I made my friend's birthday cake?\""}
367
+ {"question_id":"gpt4_1d4ab0c9","hypothesis":"Unable to answer: \"How many days passed between the day I started watering my herb garden and the day I harvested my first batch of fresh herbs?\""}
368
+ {"question_id":"gpt4_e072b769","hypothesis":"Unable to answer: \"How many weeks ago did I start using the cashback app 'Ibotta'?\""}
369
+ {"question_id":"0db4c65d","hypothesis":"Unable to answer: \"How many days had passed since I finished reading 'The Seven Husbands of Evelyn Hugo' when I attended the book reading event at the local library, where the author of 'The Silent Patient' is discussing her latest thriller novel?\""}
370
+ {"question_id":"gpt4_1d80365e","hypothesis":"Unable to answer: \"How many days did I spend on my solo camping trip to Yosemite National Park?\""}
371
+ {"question_id":"gpt4_7f6b06db","hypothesis":"Unable to answer: \"What is the order of the three trips I took in the past three months, from earliest to latest?\""}
372
+ {"question_id":"gpt4_6dc9b45b","hypothesis":"Unable to answer: \"How many months ago did I attend the Seattle International Film Festival?\""}
373
+ {"question_id":"gpt4_8279ba02","hypothesis":"Unable to answer: \"How many days ago did I buy a smoker?\""}
374
+ {"question_id":"gpt4_18c2b244","hypothesis":"Unable to answer: \"What is the order of the three events: 'I signed up for the rewards program at ShopRite', 'I used a Buy One Get One Free coupon on Luvs diapers at Walmart', and 'I redeemed $12 cashback for a $10 Amazon gift card from Ibotta'?\""}
375
+ {"question_id":"gpt4_a1b77f9c","hypothesis":"Unable to answer: \"How many weeks in total do I spent on reading 'The Nightingale' and listening to 'Sapiens: A Brief History of Humankind' and 'The Power'?\""}
376
+ {"question_id":"gpt4_1916e0ea","hypothesis":"Unable to answer: \"How many days passed between the day I cancelled my FarmFresh subscription and the day I did my online grocery shopping from Instacart?\""}
377
+ {"question_id":"gpt4_7a0daae1","hypothesis":"Unable to answer: \"How many weeks passed between the day I bought my new tennis racket and the day I received it?\""}
378
+ {"question_id":"gpt4_468eb063","hypothesis":"Unable to answer: \"How many days ago did I meet Emma?\""}
379
+ {"question_id":"gpt4_7abb270c","hypothesis":"Unable to answer: \"What is the order of the six museums I visited from earliest to latest?\""}
380
+ {"question_id":"gpt4_1e4a8aeb","hypothesis":"Unable to answer: \"How many days passed between the day I attended the gardening workshop and the day I planted the tomato saplings?\""}
381
+ {"question_id":"gpt4_4fc4f797","hypothesis":"Unable to answer: \"How many days passed between the day I received feedback about my car's suspension and the day I tested my new suspension setup?\""}
382
+ {"question_id":"4dfccbf7","hypothesis":"Unable to answer: \"How many days had passed since I started taking ukulele lessons when I decided to take my acoustic guitar to the guitar tech for servicing?\""}
383
+ {"question_id":"gpt4_61e13b3c","hypothesis":"Unable to answer: \"How many weeks passed between the time I sold homemade baked goods at the Farmers' Market for the last time and the time I participated in the Spring Fling Market?\""}
384
+ {"question_id":"gpt4_45189cb4","hypothesis":"Unable to answer: \"What is the order of the sports events I watched in January?\""}
385
+ {"question_id":"2ebe6c90","hypothesis":"Unable to answer: \"How many days did it take me to finish 'The Nightingale' by Kristin Hannah?\""}
386
+ {"question_id":"gpt4_e061b84f","hypothesis":"Unable to answer: \"What is the order of the three sports events I participated in during the past month, from earliest to latest?\""}
387
+ {"question_id":"370a8ff4","hypothesis":"Unable to answer: \"How many weeks had passed since I recovered from the flu when I went on my 10th jog outdoors?\""}
388
+ {"question_id":"gpt4_d6585ce8","hypothesis":"Unable to answer: \"What is the order of the concerts and musical events I attended in the past two months, starting from the earliest?\""}
389
+ {"question_id":"gpt4_4ef30696","hypothesis":"Unable to answer: \"How many days passed between the day I finished reading 'The Nightingale' and the day I started reading 'The Hitchhiker's Guide to the Galaxy'?\""}
390
+ {"question_id":"gpt4_ec93e27f","hypothesis":"Unable to answer: \"Which mode of transport did I use most recently, a bus or a train?\""}
391
+ {"question_id":"6e984301","hypothesis":"Unable to answer: \"How many weeks have I been taking sculpting classes when I invested in my own set of sculpting tools?\""}
392
+ {"question_id":"8077ef71","hypothesis":"Unable to answer: \"How many days ago did I attend a networking event?\""}
393
+ {"question_id":"gpt4_f420262c","hypothesis":"Unable to answer: \"What is the order of airlines I flew with from earliest to latest before today?\""}
394
+ {"question_id":"gpt4_8e165409","hypothesis":"Unable to answer: \"How many days passed between the day I repotted the previous spider plant and the day I gave my neighbor, Mrs. Johnson, a few cuttings from my spider plant?\""}
395
+ {"question_id":"gpt4_74aed68e","hypothesis":"Unable to answer: \"How many days passed between the day I replaced my spark plugs and the day I participated in the Turbocharged Tuesdays auto racking event?\""}
396
+ {"question_id":"bcbe585f","hypothesis":"Unable to answer: \"How many weeks ago did I attend a bird watching workshop at the local Audubon society?\""}
397
+ {"question_id":"gpt4_21adecb5","hypothesis":"Unable to answer: \"How many months passed between the completion of my undergraduate degree and the submission of my master's thesis?\""}
398
+ {"question_id":"5e1b23de","hypothesis":"Unable to answer: \"How many months ago did I attend the photography workshop?\""}
399
+ {"question_id":"gpt4_98f46fc6","hypothesis":"Unable to answer: \"Which event did I participate in first, the charity gala or the charity bake sale?\""}
400
+ {"question_id":"gpt4_af6db32f","hypothesis":"Unable to answer: \"How many days ago did I watch the Super Bowl?\""}
401
+ {"question_id":"eac54adc","hypothesis":"Unable to answer: \"How many days ago did I launch my website when I signed a contract with my first client?\""}
402
+ {"question_id":"gpt4_7ddcf75f","hypothesis":"Unable to answer: \"How many days ago did I go on a whitewater rafting trip in the Oregon mountains?\""}
403
+ {"question_id":"gpt4_a2d1d1f6","hypothesis":"Unable to answer: \"How many days ago did I harvest my first batch of fresh herbs from the herb garden kit?\""}
404
+ {"question_id":"gpt4_85da3956","hypothesis":"Unable to answer: \"How many weeks ago did I attend the 'Summer Nights' festival at Universal Studios Hollywood?\""}
405
+ {"question_id":"gpt4_b0863698","hypothesis":"Unable to answer: \"How many days ago did I participate in the 5K charity run?\""}
406
+ {"question_id":"gpt4_68e94287","hypothesis":"Unable to answer: \"Which event happened first, my participation in the #PlankChallenge or my post about vegan chili recipe?\""}
407
+ {"question_id":"gpt4_e414231e","hypothesis":"Unable to answer: \"How many days passed between the day I fixed my mountain bike and the day I decided to upgrade my road bike's pedals?\""}
408
+ {"question_id":"gpt4_7ca326fa","hypothesis":"Unable to answer: \"Who graduated first, second and third among Emma, Rachel and Alex?\""}
409
+ {"question_id":"gpt4_7bc6cf22","hypothesis":"Unable to answer: \"How many days ago did I read the March 15th issue of The New Yorker?\""}
410
+ {"question_id":"2ebe6c92","hypothesis":"Unable to answer: \"Which book did I finish a week ago?\""}
411
+ {"question_id":"gpt4_e061b84g","hypothesis":"Unable to answer: \"I mentioned participating in a sports event two weeks ago. What was the event?\""}
412
+ {"question_id":"71017277","hypothesis":"Unable to answer: \"I received a piece of jewelry last Saturday from whom?\""}
413
+ {"question_id":"b46e15ee","hypothesis":"Unable to answer: \"What charity event did I participate in a month ago?\""}
414
+ {"question_id":"gpt4_d6585ce9","hypothesis":"Unable to answer: \"Who did I go with to the music event last Saturday?\""}
415
+ {"question_id":"gpt4_1e4a8aec","hypothesis":"Unable to answer: \"What gardening-related activity did I do two weeks ago?\""}
416
+ {"question_id":"gpt4_f420262d","hypothesis":"Unable to answer: \"What was the airline that I flied with on Valentine's day?\""}
417
+ {"question_id":"gpt4_59149c78","hypothesis":"Unable to answer: \"I mentioned that I participated in an art-related event two weeks ago. Where was that event held at?\""}
418
+ {"question_id":"gpt4_e414231f","hypothesis":"Unable to answer: \"Which bike did I fixed or serviced the past weekend?\""}
419
+ {"question_id":"gpt4_4929293b","hypothesis":"Unable to answer: \"What was the the life event of one of my relatives that I participated in a week ago?\""}
420
+ {"question_id":"gpt4_468eb064","hypothesis":"Unable to answer: \"Who did I meet with during the lunch last Tuesday?\""}
421
+ {"question_id":"gpt4_fa19884d","hypothesis":"Unable to answer: \"What is the artist that I started to listen to last Friday?\""}
422
+ {"question_id":"9a707b82","hypothesis":"Unable to answer: \"I mentioned cooking something for my friend a couple of days ago. What was it?\""}
423
+ {"question_id":"eac54add","hypothesis":"Unable to answer: \"What was the significant buisiness milestone I mentioned four weeks ago?\""}
424
+ {"question_id":"4dfccbf8","hypothesis":"Unable to answer: \"What did I do with Rachel on the Wednesday two months ago?\""}
425
+ {"question_id":"0bc8ad93","hypothesis":"Unable to answer: \"I mentioned visiting a museum two months ago. Did I visit with a friend or not?\""}
426
+ {"question_id":"6e984302","hypothesis":"Unable to answer: \"I mentioned an investment for a competition four weeks ago? What did I buy?\""}
427
+ {"question_id":"gpt4_8279ba03","hypothesis":"Unable to answer: \"What kitchen appliance did I buy 10 days ago?\""}
428
+ {"question_id":"gpt4_b5700ca0","hypothesis":"Unable to answer: \"Where did I attend the religious activity last week?\""}
429
+ {"question_id":"gpt4_68e94288","hypothesis":"Unable to answer: \"What was the social media activity I participated 5 days ago?\""}
430
+ {"question_id":"d3ab962e","hypothesis":"Unable to answer: \"What is the total distance of the hikes I did on two consecutive weekends?\""}
431
+ {"question_id":"2311e44b","hypothesis":"Unable to answer: \"How many pages do I have left to read in 'The Nightingale'?\""}
432
+ {"question_id":"cc06de0d","hypothesis":"Unable to answer: \"For my daily commute, how much more expensive was the taxi ride compared to the train fare?\""}
433
+ {"question_id":"a11281a2","hypothesis":"Unable to answer: \"What was the approximate increase in Instagram followers I experienced in two weeks?\""}
434
+ {"question_id":"4f54b7c9","hypothesis":"Unable to answer: \"How many antique items did I inherit or acquire from my family members?\""}
435
+ {"question_id":"85fa3a3f","hypothesis":"Unable to answer: \"What is the total cost of the new food bowl, measuring cup, dental chews, and flea and tick collar I got for Max?\""}
436
+ {"question_id":"9aaed6a3","hypothesis":"Unable to answer: \"How much cashback did I earn at SaveMart last Thursday?\""}
437
+ {"question_id":"1f2b8d4f","hypothesis":"Unable to answer: \"What is the difference in price between my luxury boots and the similar pair found at the budget store?\""}
438
+ {"question_id":"e6041065","hypothesis":"Unable to answer: \"What percentage of packed shoes did I wear on my last trip?\""}
439
+ {"question_id":"51c32626","hypothesis":"Unable to answer: \"When did I submit my research paper on sentiment analysis?\""}
440
+ {"question_id":"d905b33f","hypothesis":"Unable to answer: \"What percentage discount did I get on the book from my favorite author?\""}
441
+ {"question_id":"7405e8b1","hypothesis":"Unable to answer: \"Did I receive a higher percentage discount on my first order from HelloFresh, compared to my first UberEats order?\""}
442
+ {"question_id":"f35224e0","hypothesis":"Unable to answer: \"What is the total number of episodes I've listened to from 'How I Built This' and 'My Favorite Murder'?\""}
443
+ {"question_id":"6456829e","hypothesis":"Unable to answer: \"How many plants did I initially plant for tomatoes and cucumbers?\""}
444
+ {"question_id":"a4996e51","hypothesis":"Unable to answer: \"How many hours do I work in a typical week during peak campaign seasons?\""}
445
+ {"question_id":"3c1045c8","hypothesis":"Unable to answer: \"How much older am I than the average age of employees in my department?\""}
446
+ {"question_id":"60036106","hypothesis":"Unable to answer: \"What was the total number of people reached by my Facebook ad campaign and Instagram influencer collaboration?\""}
447
+ {"question_id":"681a1674","hypothesis":"Unable to answer: \"How many Marvel movies did I re-watch?\""}
448
+ {"question_id":"e25c3b8d","hypothesis":"Unable to answer: \"How much did I save on the designer handbag at TK Maxx?\""}
449
+ {"question_id":"4adc0475","hypothesis":"Unable to answer: \"What is the total number of goals and assists I have in the recreational indoor soccer league?\""}
450
+ {"question_id":"4bc144e2","hypothesis":"Unable to answer: \"How much did I spend on car wash and parking ticket?\""}
451
+ {"question_id":"ef66a6e5","hypothesis":"Unable to answer: \"How many sports have I played competitively in the past?\""}
452
+ {"question_id":"5025383b","hypothesis":"Unable to answer: \"What are the two hobbies that led me to join online communities?\""}
453
+ {"question_id":"a1cc6108","hypothesis":"Unable to answer: \"How old was I when Alex was born?\""}
454
+ {"question_id":"9ee3ecd6","hypothesis":"Unable to answer: \"How many points do I need to earn to redeem a free skincare product at Sephora?\""}
455
+ {"question_id":"3fdac837","hypothesis":"Unable to answer: \"What is the total number of days I spent in Japan and Chicago?\""}
456
+ {"question_id":"91b15a6e","hypothesis":"Unable to answer: \"What is the minimum amount I could get if I sold the vintage diamond necklace and the antique vanity?\""}
457
+ {"question_id":"27016adc","hypothesis":"Unable to answer: \"What percentage of the countryside property's price is the cost of the renovations I plan to do on my current house?\""}
458
+ {"question_id":"720133ac","hypothesis":"Unable to answer: \"What is the total cost of Lola's vet visit and flea medication?\""}
459
+ {"question_id":"77eafa52","hypothesis":"Unable to answer: \"How much more did I have to pay for the trip after the initial quote?\""}
460
+ {"question_id":"8979f9ec","hypothesis":"Unable to answer: \"What is the total number of lunch meals I got from the chicken fajitas and lentil soup?\""}
461
+ {"question_id":"0100672e","hypothesis":"Unable to answer: \"How much did I spend on each coffee mug for my coworkers?\""}
462
+ {"question_id":"a96c20ee","hypothesis":"Unable to answer: \"At which university did I present a poster on my thesis research?\""}
463
+ {"question_id":"92a0aa75","hypothesis":"Unable to answer: \"How long have I been working in my current role?\""}
464
+ {"question_id":"3fe836c9","hypothesis":"Unable to answer: \"How much more was the pre-approval amount than the final sale price of the house?\""}
465
+ {"question_id":"1c549ce4","hypothesis":"Unable to answer: \"What is the total cost of the car cover and detailing spray I purchased?\""}
466
+ {"question_id":"6c49646a","hypothesis":"Unable to answer: \"What is the total distance I covered in my four road trips?\""}
467
+ {"question_id":"1192316e","hypothesis":"Unable to answer: \"What is the total time it takes I to get ready and commute to work?\""}
468
+ {"question_id":"0ea62687","hypothesis":"Unable to answer: \"How much more miles per gallon was my car getting a few months ago compared to now?\""}
469
+ {"question_id":"67e0d0f2","hypothesis":"Unable to answer: \"What is the total number of online courses I've completed?\""}
470
+ {"question_id":"bb7c3b45","hypothesis":"Unable to answer: \"How much did I save on the Jimmy Choo heels?\""}
471
+ {"question_id":"ba358f49","hypothesis":"Unable to answer: \"How many years will I be when my friend Rachel gets married?\""}
472
+ {"question_id":"61f8c8f8","hypothesis":"Unable to answer: \"How much faster did I finish the 5K run compared to my previous year's time?\""}
473
+ {"question_id":"60159905","hypothesis":"Unable to answer: \"How many dinner parties have I attended in the past month?\""}
474
+ {"question_id":"ef9cf60a","hypothesis":"Unable to answer: \"How much did I spend on gifts for my sister?\""}
475
+ {"question_id":"73d42213","hypothesis":"Unable to answer: \"What time did I reach the clinic on Monday?\""}
476
+ {"question_id":"bc149d6b","hypothesis":"Unable to answer: \"What is the total weight of the new feed I purchased in the past two months?\""}
477
+ {"question_id":"099778bb","hypothesis":"Unable to answer: \"What percentage of leadership positions do women hold in the my company?\""}
478
+ {"question_id":"09ba9854","hypothesis":"Unable to answer: \"How much will I save by taking the train from the airport to my hotel instead of a taxi?\""}
479
+ {"question_id":"d6062bb9","hypothesis":"Unable to answer: \"What is the total number of views on my most popular videos on YouTube and TikTok?\""}
480
+ {"question_id":"157a136e","hypothesis":"Unable to answer: \"How many years older is my grandma than me?\""}
481
+ {"question_id":"c18a7dc8","hypothesis":"Unable to answer: \"How many years older am I than when I graduated from college?\""}
482
+ {"question_id":"a3332713","hypothesis":"Unable to answer: \"What is the total amount I spent on gifts for my coworker and brother?\""}
483
+ {"question_id":"55241a1f","hypothesis":"Unable to answer: \"What is the total number of comments on my recent Facebook Live session and my most popular YouTube video?\""}
484
+ {"question_id":"a08a253f","hypothesis":"Unable to answer: \"How many days a week do I attend fitness classes?\""}
485
+ {"question_id":"f0e564bc","hypothesis":"Unable to answer: \"What is the total amount I spent on the designer handbag and high-end skincare products?\""}
486
+ {"question_id":"078150f1","hypothesis":"Unable to answer: \"How much more money did I raise than my initial goal in the charity cycling event?\""}
487
+ {"question_id":"8cf4d046","hypothesis":"Unable to answer: \"What is the average GPA of my undergraduate and graduate studies?\""}
488
+ {"question_id":"a346bb18","hypothesis":"Unable to answer: \"How many minutes did I exceed my target time by in the marathon?\""}
489
+ {"question_id":"37f165cf","hypothesis":"Unable to answer: \"What was the page count of the two novels I finished in January and March?\""}
490
+ {"question_id":"8e91e7d9","hypothesis":"Unable to answer: \"What is the total number of siblings I have?\""}
491
+ {"question_id":"87f22b4a","hypothesis":"Unable to answer: \"How much have I made from selling eggs this month?\""}
492
+ {"question_id":"e56a43b9","hypothesis":"Unable to answer: \"How much discount will I get on my next purchase at FreshMart?\""}
493
+ {"question_id":"efc3f7c2","hypothesis":"Unable to answer: \"How much earlier do I wake up on Fridays compared to other weekdays?\""}
494
+ {"question_id":"21d02d0d","hypothesis":"Unable to answer: \"How many fun runs did I miss in March due to work commitments?\""}
495
+ {"question_id":"2311e44b_abs","hypothesis":"Unable to answer: \"How many pages do I have left to read in 'Sapiens'?\""}
496
+ {"question_id":"6456829e_abs","hypothesis":"Unable to answer: \"How many plants did I initially plant for tomatoes and chili peppers?\""}
497
+ {"question_id":"e5ba910e_abs","hypothesis":"Unable to answer: \"What is the total cost of my recently purchased headphones and the iPad?\""}
498
+ {"question_id":"a96c20ee_abs","hypothesis":"Unable to answer: \"At which university did I present a poster for my undergrad course research project?\""}
499
+ {"question_id":"ba358f49_abs","hypothesis":"Unable to answer: \"How old will Rachel be when I get married?\""}
500
+ {"question_id":"09ba9854_abs","hypothesis":"Unable to answer: \"How much will I save by taking the bus from the airport to my hotel instead of a taxi?\""}
packages/benchmark/hf-space/Dockerfile ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =============================================================================
2
+ # Engram Benchmark - Hugging Face Spaces
3
+ # =============================================================================
4
+ # GPU-enabled container for running LongMemEval benchmarks with L4 GPU.
5
+ # Designed for Hugging Face Spaces Docker deployment.
6
+ #
7
+ # Usage:
8
+ # 1. Push this to HF Spaces (engram/benchmark)
9
+ # 2. Select L4 GPU hardware ($0.80/hr)
10
+ # 3. Access web UI to trigger benchmark runs
11
+ #
12
+ # =============================================================================
13
+
14
+ # -----------------------------------------------------------------------------
15
+ # Stage 1: Build dependencies
16
+ # -----------------------------------------------------------------------------
17
+ FROM node:22-bookworm-slim AS builder
18
+
19
+ WORKDIR /app
20
+
21
+ # Install build essentials for native modules
22
+ RUN apt-get update && apt-get install -y \
23
+ python3 \
24
+ make \
25
+ g++ \
26
+ git \
27
+ && rm -rf /var/lib/apt/lists/*
28
+
29
+ # Copy monorepo package files
30
+ COPY package*.json ./
31
+ COPY packages/benchmark/package.json packages/benchmark/
32
+ COPY packages/search/package.json packages/search/
33
+ COPY packages/graph/package.json packages/graph/
34
+ COPY packages/storage/package.json packages/storage/
35
+ COPY packages/logger/package.json packages/logger/
36
+ COPY packages/common/package.json packages/common/
37
+ COPY packages/temporal/package.json packages/temporal/
38
+
39
+ # Install all dependencies
40
+ RUN npm install --include=dev
41
+
42
+ # Copy source code
43
+ COPY packages/ packages/
44
+ COPY biome.json ./
45
+
46
+ # -----------------------------------------------------------------------------
47
+ # Stage 2: Runtime image with CUDA support
48
+ # -----------------------------------------------------------------------------
49
+ FROM nvidia/cuda:12.3.2-cudnn9-runtime-ubuntu22.04
50
+
51
+ # Install Node.js 22 LTS and system dependencies
52
+ RUN apt-get update && apt-get install -y \
53
+ curl \
54
+ ca-certificates \
55
+ wget \
56
+ jq \
57
+ && curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \
58
+ && apt-get install -y nodejs \
59
+ && rm -rf /var/lib/apt/lists/*
60
+
61
+ WORKDIR /app
62
+
63
+ # Copy built application from builder
64
+ COPY --from=builder /app/node_modules ./node_modules
65
+ COPY --from=builder /app/packages ./packages
66
+ COPY --from=builder /app/package*.json ./
67
+
68
+ # Reinstall native modules for the runtime platform
69
+ RUN npm install --os=linux --cpu=x64 sharp
70
+
71
+ # Model cache directory
72
+ ENV HF_HOME=/app/.cache
73
+ ENV TRANSFORMERS_CACHE=/app/.cache
74
+ ENV XDG_CACHE_HOME=/app/.cache
75
+
76
+ # Create cache directory for models (downloaded on first run)
77
+ # Skipping model preload during Docker build to avoid build failures
78
+ # Models will be cached after first run
79
+ RUN mkdir -p /app/.cache
80
+
81
+ # Install Qdrant for local vector search
82
+ RUN wget -q https://github.com/qdrant/qdrant/releases/download/v1.16.2/qdrant-x86_64-unknown-linux-gnu.tar.gz \
83
+ && tar xzf qdrant-x86_64-unknown-linux-gnu.tar.gz -C /usr/local/bin \
84
+ && rm qdrant-x86_64-unknown-linux-gnu.tar.gz \
85
+ && mkdir -p /app/qdrant-storage
86
+
87
+ # Install Redis 7.4+ for FalkorDB (Ubuntu 22.04 has old Redis, install from source)
88
+ RUN apt-get update && apt-get install -y \
89
+ libgomp1 \
90
+ build-essential \
91
+ && rm -rf /var/lib/apt/lists/* \
92
+ && mkdir -p /app/falkordb-data \
93
+ && wget -q https://github.com/redis/redis/archive/refs/tags/7.4.2.tar.gz \
94
+ && tar xzf 7.4.2.tar.gz \
95
+ && cd redis-7.4.2 && make -j$(nproc) && make install \
96
+ && cd .. && rm -rf redis-7.4.2 7.4.2.tar.gz
97
+
98
+ # Download FalkorDB module (v4.14.10 - latest)
99
+ RUN mkdir -p /opt/falkordb \
100
+ && wget -q https://github.com/FalkorDB/FalkorDB/releases/download/v4.14.10/falkordb-x64.so -O /opt/falkordb/falkordb.so \
101
+ && chmod +x /opt/falkordb/falkordb.so
102
+
103
+ # Copy HF Space runner script
104
+ COPY packages/benchmark/hf-space/run.sh /app/run.sh
105
+ RUN chmod +x /app/run.sh
106
+
107
+ # Create directories for data and results
108
+ RUN mkdir -p /data /results
109
+
110
+ # Environment configuration
111
+ ENV NODE_ENV=production
112
+ ENV BENCHMARK_VERBOSE=true
113
+ ENV NODE_OPTIONS="--max-old-space-size=24576"
114
+
115
+ # GPU mode with FP16 for L4
116
+ ENV EMBEDDER_DEVICE=cuda
117
+ ENV EMBEDDER_DTYPE=fp16
118
+ ENV QDRANT_URL=http://localhost:6333
119
+ ENV FALKORDB_URL=redis://localhost:6379
120
+
121
+ # HF Spaces requires port 7860
122
+ EXPOSE 7860
123
+
124
+ # Run the benchmark server
125
+ CMD ["/app/run.sh"]
packages/benchmark/hf-space/README.md ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Engram Benchmark
3
+ emoji: 🧠
4
+ colorFrom: purple
5
+ colorTo: blue
6
+ sdk: docker
7
+ app_port: 7860
8
+ suggested_hardware: l4x1
9
+ suggested_storage: small
10
+ ---
11
+
12
+ # Engram LongMemEval Benchmark
13
+
14
+ GPU-accelerated benchmark runner for evaluating the Engram memory retrieval system on LongMemEval dataset.
15
+
16
+ **Full Engram Stack:** FalkorDB (bitemporal graph) + Qdrant (vectors) running in-container.
17
+
18
+ ## Hardware
19
+
20
+ This Space requires **L4 GPU** ($0.80/hr) for optimal performance:
21
+ - 24GB VRAM for embedding models (E5-large, fp16)
22
+ - CUDA 12.3 with cuDNN 9 for ONNX Runtime
23
+
24
+ ## API Endpoints
25
+
26
+ | Endpoint | Method | Description |
27
+ |----------|--------|-------------|
28
+ | `/` | GET | Health check (shows FalkorDB + Qdrant status) |
29
+ | `/ingest` | POST | Ingest dataset into FalkorDB + Qdrant |
30
+ | `/start` | POST | Start benchmark (requires ingest first) |
31
+ | `/status` | GET | Get current status and output |
32
+ | `/results` | GET | Download results (when complete) |
33
+
34
+ ## Usage
35
+
36
+ ```bash
37
+ # Check health
38
+ curl https://engram-benchmark.hf.space/
39
+
40
+ # Step 1: Ingest data into FalkorDB (graph) + Qdrant (vectors)
41
+ curl -X POST https://engram-benchmark.hf.space/ingest
42
+
43
+ # Wait for ingest to complete...
44
+ curl https://engram-benchmark.hf.space/status
45
+
46
+ # Step 2: Run benchmark with full Engram pipeline
47
+ curl -X POST https://engram-benchmark.hf.space/start
48
+
49
+ # Check status
50
+ curl https://engram-benchmark.hf.space/status
51
+
52
+ # Step 3: Download results
53
+ curl https://engram-benchmark.hf.space/results > results.jsonl
54
+ ```
55
+
56
+ ## Architecture
57
+
58
+ The benchmark runs the **full Engram stack**:
59
+
60
+ ```
61
+ LongMemEval Dataset
62
+ ↓
63
+ FalkorDB (bitemporal graph)
64
+ - Session nodes with timestamps
65
+ - Turn nodes with content
66
+ - Memory nodes for retrieval
67
+ ↓
68
+ Qdrant (vector index)
69
+ - E5-large embeddings (fp16)
70
+ - Hybrid search (dense + sparse)
71
+ ↓
72
+ Engram Retrieval Pipeline
73
+ - Graph traversal + vector search
74
+ - Session-aware hierarchical retrieval
75
+ - Temporal query parsing
76
+ ↓
77
+ Gemini (answer generation)
78
+ ↓
79
+ Results
80
+ ```
81
+
82
+ ## Configuration
83
+
84
+ Set these secrets in the Space settings:
85
+
86
+ | Secret | Description |
87
+ |--------|-------------|
88
+ | `GOOGLE_GENERATIVE_AI_API_KEY` | Gemini API key for answer generation |
89
+
90
+ ## Benchmark Features
91
+
92
+ Full Engram pipeline with all optimizations:
93
+
94
+ **Retrieval:**
95
+ - Dense embeddings (E5-large, 1024d, fp16)
96
+ - Sparse embeddings (SPLADE)
97
+ - Hybrid search with RRF fusion
98
+ - Multi-query expansion
99
+ - Session-aware hierarchical retrieval
100
+ - Temporal query parsing
101
+
102
+ **Reranking:**
103
+ - Cross-encoder reranking (accurate tier)
104
+ - Deep candidate pool (50 docs)
105
+
106
+ **Reading:**
107
+ - Chain-of-Note structured reasoning
108
+ - Time-aware query expansion
109
+
110
+ **Abstention (3-layer):**
111
+ - Low retrieval confidence
112
+ - NLI answer grounding
113
+ - Hedging pattern detection
114
+
115
+ ## Results
116
+
117
+ Results are saved to `/results/benchmark-results.jsonl` and can be downloaded via the `/results` endpoint.
packages/benchmark/hf-space/deploy.sh ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # =============================================================================
3
+ # Deploy Engram Benchmark to Hugging Face Spaces
4
+ # =============================================================================
5
+ # Prerequisites:
6
+ # - huggingface-cli installed: pip install huggingface_hub
7
+ # - Logged in: huggingface-cli login
8
+ # - HF_TOKEN environment variable set (for programmatic access)
9
+ #
10
+ # Usage:
11
+ # ./deploy.sh # Deploy to ccheney/engram-benchmark
12
+ # ./deploy.sh myorg/myspace # Deploy to custom space
13
+ # =============================================================================
14
+
15
+ set -euo pipefail
16
+
17
+ SPACE_NAME="${1:-ccheney/engram-benchmark}"
18
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
19
+ REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
20
+
21
+ echo "=== Deploying Engram Benchmark to HF Spaces ==="
22
+ echo "Space: $SPACE_NAME"
23
+ echo "Repo root: $REPO_ROOT"
24
+ echo ""
25
+
26
+ # Check if hf CLI is installed
27
+ if ! command -v hf &> /dev/null; then
28
+ echo "Error: hf CLI not found"
29
+ echo "Install with: pip install huggingface_hub[cli]"
30
+ exit 1
31
+ fi
32
+
33
+ # Create temp directory for deployment
34
+ DEPLOY_DIR=$(mktemp -d)
35
+ trap "rm -rf $DEPLOY_DIR" EXIT
36
+
37
+ echo "Preparing deployment in $DEPLOY_DIR..."
38
+
39
+ # Copy HF Space files
40
+ cp "$SCRIPT_DIR/Dockerfile" "$DEPLOY_DIR/"
41
+ cp "$SCRIPT_DIR/README.md" "$DEPLOY_DIR/"
42
+ cp "$SCRIPT_DIR/run.sh" "$DEPLOY_DIR/"
43
+
44
+ # Copy monorepo files needed for Docker build
45
+ cp "$REPO_ROOT/package.json" "$DEPLOY_DIR/"
46
+ cp "$REPO_ROOT/package-lock.json" "$DEPLOY_DIR/" 2>/dev/null || true
47
+ cp "$REPO_ROOT/biome.json" "$DEPLOY_DIR/"
48
+
49
+ # Copy packages (only what's needed)
50
+ mkdir -p "$DEPLOY_DIR/packages"
51
+ for pkg in benchmark search graph storage logger common temporal; do
52
+ if [ -d "$REPO_ROOT/packages/$pkg" ]; then
53
+ echo " Copying packages/$pkg..."
54
+ cp -r "$REPO_ROOT/packages/$pkg" "$DEPLOY_DIR/packages/"
55
+ fi
56
+ done
57
+
58
+ # Remove node_modules and build artifacts to reduce size
59
+ find "$DEPLOY_DIR" -name "node_modules" -type d -exec rm -rf {} + 2>/dev/null || true
60
+ find "$DEPLOY_DIR" -name ".turbo" -type d -exec rm -rf {} + 2>/dev/null || true
61
+ find "$DEPLOY_DIR" -name "*.tsbuildinfo" -delete 2>/dev/null || true
62
+
63
+ # Copy benchmark dataset if available
64
+ if [ -f "$REPO_ROOT/packages/benchmark/data/longmemeval_oracle.json" ]; then
65
+ mkdir -p "$DEPLOY_DIR/packages/benchmark/data"
66
+ echo " Copying benchmark dataset..."
67
+ cp "$REPO_ROOT/packages/benchmark/data/longmemeval_oracle.json" "$DEPLOY_DIR/packages/benchmark/data/"
68
+ fi
69
+
70
+ echo ""
71
+ echo "Deployment directory prepared. Contents:"
72
+ ls -la "$DEPLOY_DIR"
73
+ echo ""
74
+
75
+ # Create or update the Space
76
+ echo "Pushing to Hugging Face Spaces..."
77
+ cd "$DEPLOY_DIR"
78
+
79
+ # Initialize git if needed
80
+ git init -q
81
+ git add -A
82
+ git commit -q -m "Deploy Engram Benchmark"
83
+
84
+ # Push to HF Spaces
85
+ hf upload "$SPACE_NAME" . . --repo-type space
86
+
87
+ echo ""
88
+ echo "=== Deployment Complete ==="
89
+ echo ""
90
+ echo "Space URL: https://huggingface.co/spaces/$SPACE_NAME"
91
+ echo ""
92
+ echo "Next steps:"
93
+ echo " 1. Go to Space settings and set GOOGLE_GENERATIVE_AI_API_KEY secret"
94
+ echo " 2. Select L4 GPU hardware (\$0.80/hr)"
95
+ echo " 3. Wait for build to complete"
96
+ echo " 4. POST to /start to run benchmark"
97
+ echo ""
packages/benchmark/hf-space/run.sh ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # =============================================================================
3
+ # Engram Benchmark Runner for HF Spaces
4
+ # =============================================================================
5
+ # Starts FalkorDB, Qdrant and runs the benchmark, serving status on port 7860
6
+ # Full Engram stack: FalkorDB (graph) + Qdrant (vectors)
7
+ # =============================================================================
8
+
9
+ set -euo pipefail
10
+
11
+ echo "=== Engram Benchmark Runner ==="
12
+ echo "Starting at $(date)"
13
+
14
+ # -----------------------------------------------------------------------------
15
+ # Start FalkorDB (Redis + FalkorDB module)
16
+ # -----------------------------------------------------------------------------
17
+ echo "Starting FalkorDB..."
18
+ mkdir -p /app/falkordb-data
19
+
20
+ # FalkorDB module path
21
+ FALKORDB_MODULE="/opt/falkordb/falkordb.so"
22
+ if [ ! -f "$FALKORDB_MODULE" ]; then
23
+ echo "ERROR: FalkorDB module not found at $FALKORDB_MODULE"
24
+ exit 1
25
+ fi
26
+
27
+ # Start Redis with FalkorDB module
28
+ echo "Starting redis-server with FalkorDB module..."
29
+ redis-server --daemonize yes \
30
+ --port 6379 \
31
+ --bind 127.0.0.1 \
32
+ --dir /app/falkordb-data \
33
+ --loadmodule "$FALKORDB_MODULE" \
34
+ --loglevel verbose \
35
+ --logfile /app/redis.log \
36
+ --save "" \
37
+ --appendonly no
38
+
39
+ # Check if redis started
40
+ sleep 2
41
+ if [ -f /app/redis.log ]; then
42
+ echo "Redis log (first 20 lines):"
43
+ head -20 /app/redis.log
44
+ fi
45
+
46
+ # Wait for FalkorDB to be ready
47
+ echo "Waiting for FalkorDB..."
48
+ FALKOR_READY=0
49
+ for i in $(seq 1 30); do
50
+ if redis-cli -h 127.0.0.1 ping 2>/dev/null | grep -q PONG; then
51
+ echo "FalkorDB is ready!"
52
+ redis-cli -h 127.0.0.1 MODULE LIST
53
+ FALKOR_READY=1
54
+ break
55
+ fi
56
+ echo " Attempt $i: waiting..."
57
+ sleep 1
58
+ done
59
+
60
+ if [ "$FALKOR_READY" -eq 0 ]; then
61
+ echo "ERROR: FalkorDB failed to start!"
62
+ echo "Redis log:"
63
+ cat /app/redis.log 2>/dev/null || echo "No log file"
64
+ echo "Checking redis process:"
65
+ ps aux | grep redis || echo "No redis process"
66
+ exit 1
67
+ fi
68
+
69
+ # -----------------------------------------------------------------------------
70
+ # Start Qdrant
71
+ # -----------------------------------------------------------------------------
72
+ echo "Starting Qdrant..."
73
+ mkdir -p /app/qdrant-storage
74
+ cat > /app/qdrant-config.yaml << 'EOF'
75
+ storage:
76
+ storage_path: /app/qdrant-storage
77
+ service:
78
+ http_port: 6333
79
+ grpc_port: 6334
80
+ telemetry_disabled: true
81
+ EOF
82
+
83
+ /usr/local/bin/qdrant --config-path /app/qdrant-config.yaml &
84
+ QDRANT_PID=$!
85
+
86
+ echo "Waiting for Qdrant..."
87
+ for i in {1..30}; do
88
+ if curl -s http://localhost:6333/readyz > /dev/null 2>&1; then
89
+ echo "Qdrant is ready!"
90
+ break
91
+ fi
92
+ sleep 2
93
+ done
94
+
95
+ # -----------------------------------------------------------------------------
96
+ # Check/Download Dataset
97
+ # -----------------------------------------------------------------------------
98
+ if [ ! -f /data/longmemeval_oracle.json ]; then
99
+ echo "Checking for benchmark dataset..."
100
+ if [ -f /app/packages/benchmark/data/longmemeval_oracle.json ]; then
101
+ cp /app/packages/benchmark/data/longmemeval_oracle.json /data/
102
+ echo "Dataset copied from app bundle"
103
+ else
104
+ echo "WARNING: No dataset found at /data/longmemeval_oracle.json"
105
+ echo "Upload dataset or include in packages/benchmark/data/"
106
+ fi
107
+ fi
108
+
109
+ # -----------------------------------------------------------------------------
110
+ # Create Server with Ingest + Benchmark APIs
111
+ # -----------------------------------------------------------------------------
112
+ cat > /app/server.js << 'SERVEREOF'
113
+ const http = require("http");
114
+ const { spawn } = require("child_process");
115
+ const fs = require("fs");
116
+
117
+ let status = "idle";
118
+ let ingestStatus = "not_started";
119
+ let output = [];
120
+ let currentProcess = null;
121
+
122
+ const server = http.createServer((req, res) => {
123
+ res.setHeader("Content-Type", "application/json");
124
+ res.setHeader("Access-Control-Allow-Origin", "*");
125
+
126
+ // Health check
127
+ if (req.url === "/health" || req.url === "/") {
128
+ res.end(JSON.stringify({
129
+ status: "ok",
130
+ benchmark: status,
131
+ ingest: ingestStatus,
132
+ falkordb: "redis://localhost:6379",
133
+ qdrant: "http://localhost:6333"
134
+ }));
135
+ return;
136
+ }
137
+
138
+ // Ingest data into FalkorDB
139
+ if (req.url === "/ingest" && req.method === "POST") {
140
+ if (ingestStatus === "running") {
141
+ res.statusCode = 400;
142
+ res.end(JSON.stringify({ error: "Ingest already running" }));
143
+ return;
144
+ }
145
+
146
+ ingestStatus = "running";
147
+ output = [];
148
+
149
+ // Run ingest script
150
+ const args = [
151
+ "tsx", "packages/benchmark/src/cli/index.ts",
152
+ "ingest",
153
+ "--dataset", "/data/longmemeval_oracle.json",
154
+ "--falkor-url", "redis://localhost:6379",
155
+ "--qdrant-url", "http://localhost:6333",
156
+ "--verbose"
157
+ ];
158
+
159
+ currentProcess = spawn("npx", args, { cwd: "/app" });
160
+
161
+ currentProcess.stdout.on("data", (data) => {
162
+ const line = data.toString();
163
+ output.push(line);
164
+ console.log("[ingest]", line);
165
+ });
166
+
167
+ currentProcess.stderr.on("data", (data) => {
168
+ const line = data.toString();
169
+ output.push(line);
170
+ console.error("[ingest]", line);
171
+ });
172
+
173
+ currentProcess.on("close", (code) => {
174
+ ingestStatus = code === 0 ? "completed" : "failed";
175
+ console.log(`Ingest finished with code ${code}`);
176
+ currentProcess = null;
177
+ });
178
+
179
+ res.end(JSON.stringify({ status: "ingest_started" }));
180
+ return;
181
+ }
182
+
183
+ // Start benchmark
184
+ if (req.url === "/start" && req.method === "POST") {
185
+ if (status === "running") {
186
+ res.statusCode = 400;
187
+ res.end(JSON.stringify({ error: "Benchmark already running" }));
188
+ return;
189
+ }
190
+
191
+ if (ingestStatus !== "completed") {
192
+ res.statusCode = 400;
193
+ res.end(JSON.stringify({
194
+ error: "Data not ingested. POST /ingest first.",
195
+ ingestStatus
196
+ }));
197
+ return;
198
+ }
199
+
200
+ status = "running";
201
+ output = [];
202
+
203
+ const args = [
204
+ "tsx", "packages/benchmark/src/cli/index.ts",
205
+ "run", "longmemeval",
206
+ "--dataset", "/data/longmemeval_oracle.json",
207
+ "--variant", "oracle",
208
+ "--embeddings", "engram",
209
+ "--llm", "gemini",
210
+ "--gemini-model", "gemini-2.5-flash-preview-05-20",
211
+ "--falkor-url", "redis://127.0.0.1:6379",
212
+ "--qdrant-url", "http://localhost:6333",
213
+ "--top-k", "10",
214
+ "--hybrid-search",
215
+ "--rerank",
216
+ "--rerank-tier", "accurate",
217
+ "--rerank-depth", "50",
218
+ "--multi-query",
219
+ "--session-aware",
220
+ "--temporal-aware",
221
+ "--abstention",
222
+ "--abstention-hedging",
223
+ "--abstention-nli",
224
+ "--key-expansion",
225
+ "--temporal-analysis",
226
+ "--chain-of-note",
227
+ "--time-aware",
228
+ "--embedding-model", "e5-large",
229
+ "--verbose",
230
+ "--output", "/results/benchmark-results.jsonl"
231
+ ];
232
+
233
+ currentProcess = spawn("npx", args, { cwd: "/app" });
234
+
235
+ currentProcess.stdout.on("data", (data) => {
236
+ const line = data.toString();
237
+ output.push(line);
238
+ console.log("[benchmark]", line);
239
+ });
240
+
241
+ currentProcess.stderr.on("data", (data) => {
242
+ const line = data.toString();
243
+ output.push(line);
244
+ console.error("[benchmark]", line);
245
+ });
246
+
247
+ currentProcess.on("close", (code) => {
248
+ status = code === 0 ? "completed" : "failed";
249
+ console.log(`Benchmark finished with code ${code}`);
250
+ currentProcess = null;
251
+ });
252
+
253
+ res.end(JSON.stringify({ status: "started" }));
254
+ return;
255
+ }
256
+
257
+ // Get status
258
+ if (req.url === "/status") {
259
+ res.end(JSON.stringify({
260
+ benchmark: status,
261
+ ingest: ingestStatus,
262
+ output: output.slice(-100).join(""),
263
+ resultsExist: fs.existsSync("/results/benchmark-results.jsonl")
264
+ }));
265
+ return;
266
+ }
267
+
268
+ // Download results
269
+ if (req.url === "/results" && status === "completed") {
270
+ if (fs.existsSync("/results/benchmark-results.jsonl")) {
271
+ res.setHeader("Content-Type", "application/jsonl");
272
+ fs.createReadStream("/results/benchmark-results.jsonl").pipe(res);
273
+ return;
274
+ }
275
+ res.statusCode = 404;
276
+ res.end(JSON.stringify({ error: "Results not found" }));
277
+ return;
278
+ }
279
+
280
+ // 404
281
+ res.statusCode = 404;
282
+ res.end(JSON.stringify({ error: "Not found" }));
283
+ });
284
+
285
+ server.listen(7860, "0.0.0.0", () => {
286
+ console.log("Engram Benchmark Server running on http://0.0.0.0:7860");
287
+ console.log("");
288
+ console.log("API Endpoints:");
289
+ console.log(" GET / - Health check");
290
+ console.log(" POST /ingest - Ingest dataset into FalkorDB + Qdrant");
291
+ console.log(" POST /start - Start benchmark (requires ingest first)");
292
+ console.log(" GET /status - Get current status");
293
+ console.log(" GET /results - Download results (when complete)");
294
+ console.log("");
295
+ console.log("Workflow:");
296
+ console.log(" 1. POST /ingest - Load data into graph + vectors");
297
+ console.log(" 2. POST /start - Run benchmark with full Engram pipeline");
298
+ console.log(" 3. GET /results - Download results");
299
+ });
300
+ SERVEREOF
301
+
302
+ echo "Starting benchmark server..."
303
+ node /app/server.js
packages/benchmark/package.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@engram/benchmark",
3
+ "version": "0.0.0",
4
+ "type": "module",
5
+ "main": "./src/index.ts",
6
+ "types": "./src/index.ts",
7
+ "bin": {
8
+ "engram-benchmark": "./src/cli/index.ts"
9
+ },
10
+ "devDependencies": {
11
+ "@engram/tsconfig": "*",
12
+ "@types/node": "^24.10.1",
13
+ "typescript": "^5.9.3"
14
+ },
15
+ "dependencies": {
16
+ "@ai-sdk/google": "^1.2.18",
17
+ "@engram/graph": "*",
18
+ "@engram/search": "*",
19
+ "@engram/storage": "*",
20
+ "@qdrant/js-client-rest": "^1.16.2",
21
+ "ai": "^4.3.16",
22
+ "commander": "^14.0.0",
23
+ "falkordb": "^6.4.1",
24
+ "zod": "^4.1.13"
25
+ },
26
+ "optionalDependencies": {
27
+ "@anthropic-ai/sdk": "^0.52.0",
28
+ "@google/genai": "^1.0.0"
29
+ },
30
+ "scripts": {
31
+ "build": "echo 'Build success'",
32
+ "typecheck": "tsc --noEmit",
33
+ "benchmark": "tsx src/cli/index.ts"
34
+ }
35
+ }
packages/benchmark/results/benchmark-50-gpt4o-report.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LongMemEval Benchmark Results
2
+
3
+ ## Overall
4
+ - Total: 50
5
+ - Correct: 36
6
+ - Accuracy: 72.0%
7
+
8
+ ## By Memory Ability
9
+
10
+ | Ability | Total | Correct | Accuracy |
11
+ |:--------|------:|--------:|---------:|
12
+ | Information Extraction (IE) | 0 | 0 | 0.0% |
13
+ | Multi-Session Reasoning (MR) | 0 | 0 | 0.0% |
14
+ | Temporal Reasoning (TR) | 50 | 36 | 72.0% |
15
+ | Knowledge Update (KU) | 0 | 0 | 0.0% |
16
+ | Abstention (ABS) | 0 | 0 | 0.0% |
17
+
18
+ ## Retrieval Metrics
19
+
20
+ - Turn Recall: 90.7%
21
+ - Session Recall: 90.7%
22
+ - MRR: 0.907
23
+
24
+ ### Recall@K
25
+
26
+ | K | Recall |
27
+ |--:|-------:|
28
+ | 1 | 0.0% |
29
+ | 5 | 0.0% |
30
+ | 10 | 90.7% |
31
+
32
+ ### NDCG@K
33
+
34
+ | K | NDCG |
35
+ |--:|-----:|
36
+ | 1 | 0.000 |
37
+ | 5 | 0.000 |
38
+ | 10 | 0.907 |
packages/benchmark/results/benchmark-50-gpt4o.jsonl ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"question_id":"gpt4_2655b836","hypothesis":"The first issue the user had with their new car after its first service was a GPS system issue."}
2
+ {"question_id":"gpt4_2487a7cb","hypothesis":"The 'Data Analysis using Python' webinar was attended first."}
3
+ {"question_id":"gpt4_76048e76","hypothesis":"The bike was taken care of first in February."}
4
+ {"question_id":"gpt4_2312f94c","hypothesis":"The Samsung Galaxy S22."}
5
+ {"question_id":"0bb5a684","hypothesis":"7 days"}
6
+ {"question_id":"08f4fc43","hypothesis":"30 days"}
7
+ {"question_id":"2c63a862","hypothesis":"It took 14 days for you to find a house you loved after starting to work with Rachel."}
8
+ {"question_id":"gpt4_385a5000","hypothesis":"There is no information on when the tomato seeds were started, so we cannot determine which seeds were started first."}
9
+ {"question_id":"2a1811e2","hypothesis":"21 days"}
10
+ {"question_id":"bbf86515","hypothesis":"4 days"}
11
+ {"question_id":"gpt4_5dcc0aab","hypothesis":"White Adidas sneakers"}
12
+ {"question_id":"gpt4_0b2f1d21","hypothesis":"The malfunction of the stand mixer happened first."}
13
+ {"question_id":"f0853d11","hypothesis":"14 days"}
14
+ {"question_id":"gpt4_6ed717ea","hypothesis":"The training pads for Luna were purchased first."}
15
+ {"question_id":"gpt4_70e84552","hypothesis":"You completed fixing the fence first."}
16
+ {"question_id":"a3838d2b","hypothesis":"2"}
17
+ {"question_id":"gpt4_93159ced","hypothesis":"The user has been working for 4 years and 9 months before starting at NovaTech."}
18
+ {"question_id":"gpt4_2d58bcd6","hypothesis":"'The Hate U Give'"}
19
+ {"question_id":"gpt4_65aabe59","hypothesis":"The smart thermostat was set up first."}
20
+ {"question_id":"982b5123","hypothesis":"5 months ago"}
21
+ {"question_id":"b9cfe692","hypothesis":"The user took a combined total of 5.5 weeks to finish 'The Seven Husbands of Evelyn Hugo' and 'The Nightingale'."}
22
+ {"question_id":"gpt4_4edbafa2","hypothesis":"The date on which you attended the first BBQ event in June was the 3rd of June."}
23
+ {"question_id":"c8090214","hypothesis":"The user attended the Holiday Market 7 days before purchasing the iPhone 13 Pro."}
24
+ {"question_id":"gpt4_483dd43c","hypothesis":"Cannot determine which show was started first based on the provided information."}
25
+ {"question_id":"e4e14d04","hypothesis":"The user had been a member of 'Book Lovers Unite' for two weeks when they attended the meetup."}
26
+ {"question_id":"c9f37c46","hypothesis":"The user had been watching stand-up comedy specials regularly for about 2 months when they attended the open mic night at the local comedy club."}
27
+ {"question_id":"gpt4_2c50253f","hypothesis":"6:45 AM"}
28
+ {"question_id":"dcfa8644","hypothesis":"14 days"}
29
+ {"question_id":"gpt4_b4a80587","hypothesis":"The arrival of the new prime lens happened first."}
30
+ {"question_id":"gpt4_9a159967","hypothesis":"United Airlines"}
31
+ {"question_id":"cc6d1ec1","hypothesis":"The user had been bird watching for about three months when they attended the bird watching workshop."}
32
+ {"question_id":"gpt4_8c8961ae","hypothesis":"The solo trip to Thailand was taken first."}
33
+ {"question_id":"gpt4_d9af6064","hypothesis":"The new router was set up first."}
34
+ {"question_id":"gpt4_7de946e7","hypothesis":"The persistent cough was dealt with first."}
35
+ {"question_id":"d01c6aa8","hypothesis":"You were 27 years old when you moved to the United States."}
36
+ {"question_id":"993da5e2","hypothesis":"You had been using the new area rug for about one week when you rearranged your living room furniture."}
37
+ {"question_id":"a3045048","hypothesis":"The user ordered the gift 7 days before the birthday party."}
38
+ {"question_id":"gpt4_d31cdae3","hypothesis":"The family road trip across the American Southwest was taken first."}
39
+ {"question_id":"gpt4_cd90e484","hypothesis":"The user used their new binoculars for two weeks before seeing the American goldfinches returning to the area."}
40
+ {"question_id":"gpt4_88806d6e","hypothesis":"You met Tom first."}
41
+ {"question_id":"gpt4_4cd9eba1","hypothesis":"1 week"}
42
+ {"question_id":"gpt4_93f6379c","hypothesis":"'Page Turners'"}
43
+ {"question_id":"b29f3365","hypothesis":"You had been taking guitar lessons for 4 weeks when you bought the new guitar amp."}
44
+ {"question_id":"gpt4_2f56ae70","hypothesis":"Apple TV+"}
45
+ {"question_id":"6613b389","hypothesis":"Rachel got engaged approximately two months before the user's anniversary."}
46
+ {"question_id":"gpt4_78cf46a3","hypothesis":"The narrator received their new phone case first."}
47
+ {"question_id":"gpt4_0a05b494","hypothesis":"The user met the woman selling jam at the farmer's market first."}
48
+ {"question_id":"gpt4_1a1dc16d","hypothesis":"The meeting with Rachel happened first."}
49
+ {"question_id":"gpt4_2f584639","hypothesis":"The photo album for your mom was bought first."}
50
+ {"question_id":"gpt4_213fd887","hypothesis":"You participated in the volleyball league first."}
packages/benchmark/results/full-run-20251218-report.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LongMemEval Benchmark Results
2
+
3
+ ## Overall
4
+ - Total: 500
5
+ - Correct: 379
6
+ - Accuracy: 75.8%
7
+
8
+ ## By Memory Ability
9
+
10
+ | Ability | Total | Correct | Accuracy |
11
+ |:--------|------:|--------:|---------:|
12
+ | Information Extraction (IE) | 150 | 140 | 93.3% |
13
+ | Multi-Session Reasoning (MR) | 121 | 90 | 74.4% |
14
+ | Temporal Reasoning (TR) | 127 | 91 | 71.7% |
15
+ | Knowledge Update (KU) | 72 | 55 | 76.4% |
16
+ | Abstention (ABS) | 30 | 3 | 10.0% |
17
+
18
+ ## Retrieval Metrics
19
+
20
+ - Turn Recall: 79.5%
21
+ - Session Recall: 79.5%
22
+ - MRR: 0.795
23
+
24
+ ### Recall@K
25
+
26
+ | K | Recall |
27
+ |--:|-------:|
28
+ | 1 | 0.0% |
29
+ | 5 | 0.0% |
30
+ | 10 | 79.5% |
31
+
32
+ ### NDCG@K
33
+
34
+ | K | NDCG |
35
+ |--:|-----:|
36
+ | 1 | 0.000 |
37
+ | 5 | 0.000 |
38
+ | 10 | 0.795 |
packages/benchmark/results/full-run-20251218.jsonl ADDED
@@ -0,0 +1,500 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"question_id":"gpt4_2655b836","hypothesis":"The car's GPS system failed (on 3/22), requiring the dealership to replace the entire system."}
2
+ {"question_id":"gpt4_2487a7cb","hypothesis":"The 'Data Analysis using Python' webinar was attended first (about two months ago); the 'Effective Time Management' workshop was attended more recently (last Saturday)."}
3
+ {"question_id":"gpt4_76048e76","hypothesis":"The bike"}
4
+ {"question_id":"gpt4_2312f94c","hypothesis":"Samsung Galaxy S22"}
5
+ {"question_id":"0bb5a684","hypothesis":"7 days"}
6
+ {"question_id":"08f4fc43","hypothesis":"30 days"}
7
+ {"question_id":"2c63a862","hypothesis":""}
8
+ {"question_id":"gpt4_385a5000","hypothesis":"Cannot determine from the conversation history (no start date given for tomato seeds)."}
9
+ {"question_id":"2a1811e2","hypothesis":"21 days"}
10
+ {"question_id":"bbf86515","hypothesis":"4 days"}
11
+ {"question_id":"gpt4_5dcc0aab","hypothesis":"white Adidas sneakers"}
12
+ {"question_id":"gpt4_0b2f1d21","hypothesis":"The malfunction of the stand mixer happened first."}
13
+ {"question_id":"f0853d11","hypothesis":"14 days"}
14
+ {"question_id":"gpt4_6ed717ea","hypothesis":"The training pads for Luna were purchased first."}
15
+ {"question_id":"gpt4_70e84552","hypothesis":"Fixing the fence was completed first."}
16
+ {"question_id":"a3838d2b","hypothesis":""}
17
+ {"question_id":"gpt4_93159ced","hypothesis":"Cannot be determined from the conversation history."}
18
+ {"question_id":"gpt4_2d58bcd6","hypothesis":"The Hate U Give"}
19
+ {"question_id":"gpt4_65aabe59","hypothesis":"Cannot determine from the conversation history which device was set up first (smart thermostat vs. mesh network)."}
20
+ {"question_id":"982b5123","hypothesis":"5 months ago"}
21
+ {"question_id":"b9cfe692","hypothesis":"5.5 weeks (about 38.5 days)."}
22
+ {"question_id":"gpt4_4edbafa2","hypothesis":"June 3rd"}
23
+ {"question_id":"c8090214","hypothesis":"7 days"}
24
+ {"question_id":"gpt4_483dd43c","hypothesis":""}
25
+ {"question_id":"e4e14d04","hypothesis":"Cannot be determined from the conversation history; no explicit information about how long you had been a member is provided."}
26
+ {"question_id":"c9f37c46","hypothesis":"Cannot determine from the conversation history. The user did not state how long they had been watching stand-up comedy specials regularly."}
27
+ {"question_id":"gpt4_2c50253f","hypothesis":"6:45 AM"}
28
+ {"question_id":"dcfa8644","hypothesis":"14 days"}
29
+ {"question_id":"gpt4_b4a80587","hypothesis":"The arrival of the new prime lens happened before the road trip to the coast."}
30
+ {"question_id":"gpt4_9a159967","hypothesis":""}
31
+ {"question_id":"cc6d1ec1","hypothesis":"I cannot determine how long you had been bird watching when you attended the workshop from the conversation history."}
32
+ {"question_id":"gpt4_8c8961ae","hypothesis":"The solo trip to Thailand was first."}
33
+ {"question_id":"gpt4_d9af6064","hypothesis":"The new router was set up first."}
34
+ {"question_id":"gpt4_7de946e7","hypothesis":"The persistent cough came first."}
35
+ {"question_id":"d01c6aa8","hypothesis":"Cannot determine from the conversation history; the user's age when they moved to the United States is not provided."}
36
+ {"question_id":"993da5e2","hypothesis":"About one week."}
37
+ {"question_id":"a3045048","hypothesis":"7 days"}
38
+ {"question_id":"gpt4_d31cdae3","hypothesis":"The family road trip across the American Southwest happened before the solo trip to Europe."}
39
+ {"question_id":"gpt4_cd90e484","hypothesis":""}
40
+ {"question_id":"gpt4_88806d6e","hypothesis":"Cannot be determined from the conversation history."}
41
+ {"question_id":"gpt4_4cd9eba1","hypothesis":"1 week"}
42
+ {"question_id":"gpt4_93f6379c","hypothesis":""}
43
+ {"question_id":"b29f3365","hypothesis":"4 weeks"}
44
+ {"question_id":"gpt4_2f56ae70","hypothesis":"Apple TV+"}
45
+ {"question_id":"6613b389","hypothesis":"About 2 months (roughly 2 months and 1 week)."}
46
+ {"question_id":"gpt4_78cf46a3","hypothesis":"The narrator receiving their new phone case happened first."}
47
+ {"question_id":"gpt4_0a05b494","hypothesis":"The woman (jam maker) at the farmer's market was met first."}
48
+ {"question_id":"gpt4_1a1dc16d","hypothesis":"The meeting with Rachel happened first (April 10), and the pride parade occurred later (May 1)."}
49
+ {"question_id":"gpt4_2f584639","hypothesis":"Cannot determine from the conversation. The photo album was ordered two weeks ago, but the conversation does not state when the Tiffany's necklace was purchased, so we cannot tell which was bought first."}
50
+ {"question_id":"gpt4_213fd887","hypothesis":"The volleyball league."}
51
+ {"question_id":"gpt4_5438fa52","hypothesis":"The start of your Spanish classes happened before your attendance at the cultural festival."}
52
+ {"question_id":"gpt4_c27434e8","hypothesis":"The Japanese Zero fighter plane model was started before the Ferrari model."}
53
+ {"question_id":"gpt4_fe651585","hypothesis":"Rachel"}
54
+ {"question_id":"8c18457d","hypothesis":"7 days"}
55
+ {"question_id":"gpt4_70e84552_abs","hypothesis":"Cannot determine — the conversation records the fence was fixed three weeks ago, but contains no information that you purchased three cows from Peter."}
56
+ {"question_id":"gpt4_93159ced_abs","hypothesis":"Cannot determine — the conversation history does not state any employment at Google or a start date there, so there is insufficient information to calculate how long you had been working before starting a job at Google."}
57
+ {"question_id":"982b5123_abs","hypothesis":"I cannot determine when you booked the Airbnb in Sacramento because the conversation history contains no information about an Airbnb in Sacramento or its booking date."}
58
+ {"question_id":"c8090214_abs","hypothesis":"Cannot answer — the conversation does not state when (or if) you bought an iPad."}
59
+ {"question_id":"gpt4_c27434e8_abs","hypothesis":"Cannot determine — the conversation contains a start date for the Ferrari 288 GTO (about three weeks ago) but contains no information about a Porsche 991 Turbo S project or when it was started."}
60
+ {"question_id":"gpt4_fe651585_abs","hypothesis":"Cannot determine from the conversation history — Alex's adoption in January is mentioned, but there is no information about Tom."}
61
+ {"question_id":"0a995998","hypothesis":""}
62
+ {"question_id":"6d550036","hypothesis":"Cannot determine from the conversation history — no information about the number of projects led or currently being led is provided."}
63
+ {"question_id":"gpt4_59c863d7","hypothesis":""}
64
+ {"question_id":"b5ef892d","hypothesis":"8 days"}
65
+ {"question_id":"e831120c","hypothesis":"Marvel Cinematic Universe: ~2 weeks; Main Star Wars films: ~1.5 weeks. Combined total: ~3.5 weeks."}
66
+ {"question_id":"3a704032","hypothesis":"3"}
67
+ {"question_id":"gpt4_d84a3211","hypothesis":"$65"}
68
+ {"question_id":"aae3761f","hypothesis":""}
69
+ {"question_id":"gpt4_f2262a51","hypothesis":""}
70
+ {"question_id":"dd2973ad","hypothesis":"2 AM"}
71
+ {"question_id":"c4a1ceb8","hypothesis":""}
72
+ {"question_id":"gpt4_a56e767c","hypothesis":""}
73
+ {"question_id":"6cb6f249","hypothesis":"17 days"}
74
+ {"question_id":"46a3abf7","hypothesis":"2"}
75
+ {"question_id":"36b9f61e","hypothesis":"$2,500"}
76
+ {"question_id":"28dc39ac","hypothesis":""}
77
+ {"question_id":"gpt4_2f8be40d","hypothesis":""}
78
+ {"question_id":"2e6d26dc","hypothesis":"5"}
79
+ {"question_id":"gpt4_15e38248","hypothesis":""}
80
+ {"question_id":"88432d0a","hypothesis":""}
81
+ {"question_id":"80ec1f4f","hypothesis":"1"}
82
+ {"question_id":"d23cf73b","hypothesis":""}
83
+ {"question_id":"gpt4_7fce9456","hypothesis":"One property (the 3-bedroom townhouse in Brookside)."}
84
+ {"question_id":"d682f1a2","hypothesis":"3"}
85
+ {"question_id":"7024f17c","hypothesis":""}
86
+ {"question_id":"gpt4_5501fe77","hypothesis":"TikTok"}
87
+ {"question_id":"gpt4_2ba83207","hypothesis":"Walmart (about $120)"}
88
+ {"question_id":"2318644b","hypothesis":"You spent more than $270 more per night in Hawaii than in Tokyo."}
89
+ {"question_id":"2ce6a0f2","hypothesis":""}
90
+ {"question_id":"gpt4_d12ceb0e","hypothesis":"59.6 years"}
91
+ {"question_id":"00ca467f","hypothesis":"2"}
92
+ {"question_id":"b3c15d39","hypothesis":"5 days"}
93
+ {"question_id":"gpt4_31ff4165","hypothesis":"1"}
94
+ {"question_id":"eeda8a6d","hypothesis":"Cannot determine total number of fish. The conversation only specifies one fish by number (Bubbles the betta). Counts for neon tetras, gouramis, pleco, and any others are not provided."}
95
+ {"question_id":"2788b940","hypothesis":""}
96
+ {"question_id":"60bf93ed","hypothesis":"5 days"}
97
+ {"question_id":"9d25d4e0","hypothesis":"2"}
98
+ {"question_id":"129d1232","hypothesis":""}
99
+ {"question_id":"60472f9c","hypothesis":"2"}
100
+ {"question_id":"gpt4_194be4b3","hypothesis":"3"}
101
+ {"question_id":"a9f6b44c","hypothesis":""}
102
+ {"question_id":"d851d5ba","hypothesis":"Over $3,500 total (at least $3,500 based on the reported amounts: $500 + $2,000 + over $1,000)."}
103
+ {"question_id":"5a7937c8","hypothesis":"3 days"}
104
+ {"question_id":"gpt4_ab202e7f","hypothesis":"2"}
105
+ {"question_id":"gpt4_e05b82a6","hypothesis":"7 rollercoaster rides"}
106
+ {"question_id":"gpt4_731e37d7","hypothesis":"Cannot determine — the conversation does not state any money amounts or prices for the workshops, so total spend in the last four months is unknown."}
107
+ {"question_id":"edced276","hypothesis":"Cannot determine total days because the duration of the Hawaii trip is not provided. The New York City trip was 5 days."}
108
+ {"question_id":"10d9b85a","hypothesis":"3 days"}
109
+ {"question_id":"e3038f8c","hypothesis":""}
110
+ {"question_id":"2b8f3739","hypothesis":"$495"}
111
+ {"question_id":"1a8a66a6","hypothesis":""}
112
+ {"question_id":"c2ac3c61","hypothesis":"5"}
113
+ {"question_id":"bf659f65","hypothesis":""}
114
+ {"question_id":"gpt4_372c3eed","hypothesis":""}
115
+ {"question_id":"gpt4_2f91af09","hypothesis":"23 pieces"}
116
+ {"question_id":"81507db6","hypothesis":""}
117
+ {"question_id":"88432d0a_abs","hypothesis":"Cannot determine — the conversation contains no information about how many times you baked egg tarts in the past two weeks."}
118
+ {"question_id":"80ec1f4f_abs","hypothesis":"Cannot determine — no visits in December are mentioned in the conversation history."}
119
+ {"question_id":"eeda8a6d_abs","hypothesis":""}
120
+ {"question_id":"60bf93ed_abs","hypothesis":"Cannot determine — the conversation history contains no information about an iPad case purchase or arrival."}
121
+ {"question_id":"edced276_abs","hypothesis":"Cannot determine total. The conversation implies the Hawaii family trip was 10 days, but the number of days spent in Seattle is not mentioned, so the combined total cannot be calculated from the given history."}
122
+ {"question_id":"gpt4_372c3eed_abs","hypothesis":"Cannot answer — the conversation does not provide the number of years spent in high school nor confirm completion or duration of a Master's degree, so total years cannot be determined."}
123
+ {"question_id":"6a1eabeb","hypothesis":"27:12"}
124
+ {"question_id":"6aeb4375","hypothesis":"4"}
125
+ {"question_id":"830ce83f","hypothesis":"Chicago"}
126
+ {"question_id":"852ce960","hypothesis":"Cannot determine from the conversation — the history contains two different explicit claims: $350,000 and $400,000."}
127
+ {"question_id":"945e3d21","hypothesis":"Three times a week."}
128
+ {"question_id":"d7c942c3","hypothesis":"Yes — according to the conversation, your mom is now using the same grocery list app as you."}
129
+ {"question_id":"71315a70","hypothesis":"10-12 hours"}
130
+ {"question_id":"89941a93","hypothesis":""}
131
+ {"question_id":"ce6d2d27","hypothesis":"Cannot determine from the conversation history (both Thursday and Friday are stated)."}
132
+ {"question_id":"9ea5eabc","hypothesis":"Paris"}
133
+ {"question_id":"07741c44","hypothesis":"Under the bed."}
134
+ {"question_id":"a1eacc2a","hypothesis":"7 short stories"}
135
+ {"question_id":"184da446","hypothesis":"220 pages"}
136
+ {"question_id":"031748ae","hypothesis":"When you just started your new role you led 4 engineers. Now you lead 5 engineers."}
137
+ {"question_id":"4d6b87c8","hypothesis":"25"}
138
+ {"question_id":"0f05491a","hypothesis":""}
139
+ {"question_id":"08e075c7","hypothesis":"9 months"}
140
+ {"question_id":"f9e8c073","hypothesis":"Cannot determine from the conversation history (user stated both 3 sessions and 5 sessions at different times)."}
141
+ {"question_id":"41698283","hypothesis":"50mm prime lens"}
142
+ {"question_id":"2698e78f","hypothesis":"You see Dr. Smith every week."}
143
+ {"question_id":"b6019101","hypothesis":"5 MCU films"}
144
+ {"question_id":"45dc21b6","hypothesis":"3"}
145
+ {"question_id":"5a4f22c0","hypothesis":"TechCorp"}
146
+ {"question_id":"6071bd76","hypothesis":"You switched to less water per tablespoon (from 6 oz/tbsp down to 5 oz/tbsp)."}
147
+ {"question_id":"e493bb7c","hypothesis":"Above the bed in the user's bedroom."}
148
+ {"question_id":"618f13b2","hypothesis":"6 times"}
149
+ {"question_id":"72e3ee87","hypothesis":"50"}
150
+ {"question_id":"c4ea545c","hypothesis":"Yes — you go to the gym more frequently now (4 times per week) than previously (3 times per week)."}
151
+ {"question_id":"01493427","hypothesis":"25 new postcards"}
152
+ {"question_id":"6a27ffc2","hypothesis":"30 videos"}
153
+ {"question_id":"2133c1b5","hypothesis":""}
154
+ {"question_id":"18bc8abd","hypothesis":"Kansas City Masterpiece BBQ sauce"}
155
+ {"question_id":"db467c8c","hypothesis":"Nine months."}
156
+ {"question_id":"7a87bd0c","hypothesis":"4 weeks"}
157
+ {"question_id":"e61a7584","hypothesis":"About 9 months (as of 2023-11-30)."}
158
+ {"question_id":"1cea1afa","hypothesis":"600 followers"}
159
+ {"question_id":"ed4ddc30","hypothesis":"20 dozen"}
160
+ {"question_id":"8fb83627","hypothesis":"3"}
161
+ {"question_id":"b01defab","hypothesis":"Yes — you finished reading 'The Nightingale' by Kristin Hannah."}
162
+ {"question_id":"22d2cb42","hypothesis":"At a music shop on Main St. (You mentioned 'Rhythm Central' as a likely shop, but you did not explicitly confirm it was the one that serviced your guitar.)"}
163
+ {"question_id":"0e4e4c46","hypothesis":"132 points"}
164
+ {"question_id":"4b24c848","hypothesis":"5"}
165
+ {"question_id":"7e974930","hypothesis":"$420"}
166
+ {"question_id":"603deb26","hypothesis":"10 times"}
167
+ {"question_id":"59524333","hypothesis":""}
168
+ {"question_id":"5831f84d","hypothesis":"15"}
169
+ {"question_id":"eace081b","hypothesis":"Oahu"}
170
+ {"question_id":"affe2881","hypothesis":"32 species"}
171
+ {"question_id":"50635ada","hypothesis":"Premier Silver"}
172
+ {"question_id":"e66b632c","hypothesis":""}
173
+ {"question_id":"0ddfec37","hypothesis":"15 autographed baseballs"}
174
+ {"question_id":"f685340e","hypothesis":""}
175
+ {"question_id":"cc5ded98","hypothesis":"About two hours each day (based on the user's most recent messages on 2023-05-27)."}
176
+ {"question_id":"dfde3500","hypothesis":"Wednesday"}
177
+ {"question_id":"69fee5aa","hypothesis":"37"}
178
+ {"question_id":"7401057b","hypothesis":"Two free nights"}
179
+ {"question_id":"cf22b7bf","hypothesis":"10 pounds"}
180
+ {"question_id":"a2f3aa27","hypothesis":"1250"}
181
+ {"question_id":"c7dc5443","hypothesis":"5-2"}
182
+ {"question_id":"06db6396","hypothesis":"5 projects"}
183
+ {"question_id":"3ba21379","hypothesis":"Ford F-150 pickup truck"}
184
+ {"question_id":"9bbe84a2","hypothesis":"Level 100"}
185
+ {"question_id":"10e09553","hypothesis":"7 largemouth bass"}
186
+ {"question_id":"dad224aa","hypothesis":"8:30 am"}
187
+ {"question_id":"ba61f0b9","hypothesis":"Cannot determine from conversation: the history contains conflicting statements (5 women and 6 women are both stated)."}
188
+ {"question_id":"42ec0761","hypothesis":"Yes — according to your later message (2023-08-15), you have a spare screwdriver available for opening your laptop."}
189
+ {"question_id":"5c40ec5b","hypothesis":"Twice (2 times)"}
190
+ {"question_id":"c6853660","hypothesis":"You most recently increased the limit (to two cups)."}
191
+ {"question_id":"26bdc477","hypothesis":"5 trips"}
192
+ {"question_id":"0977f2af","hypothesis":"Instant Pot"}
193
+ {"question_id":"6aeb4375_abs","hypothesis":"Cannot determine from the conversation history — no Italian restaurants are mentioned."}
194
+ {"question_id":"031748ae_abs","hypothesis":"4 engineers"}
195
+ {"question_id":"2698e78f_abs","hypothesis":"I cannot answer — there is no information in the conversation history about Dr. Johnson or how often you see them."}
196
+ {"question_id":"2133c1b5_abs","hypothesis":"Cannot determine from the conversation history — there is no information about the duration of living in a Shinjuku apartment."}
197
+ {"question_id":"0ddfec37_abs","hypothesis":"Cannot be determined from the conversation history (no mention of autographed footballs)."}
198
+ {"question_id":"f685340e_abs","hypothesis":"I cannot answer — the conversation contains no explicit information about how often you play table tennis at the local park. It only mentions (regular) tennis, with conflicting mentions of 'every other week' and 'weekly.'"}
199
+ {"question_id":"89941a94","hypothesis":"Yes. Before acquiring the later bike(s), you already had a road bike in addition to your mountain bike and commuter bike."}
200
+ {"question_id":"07741c45","hypothesis":"Under your bed."}
201
+ {"question_id":"8a2466db","hypothesis":"Recommended resources: 1) Adobe Premiere Pro official documentation and tutorials. 2) YouTube channels: Premiere Bro, Video Copilot, and Adobe Creative Cloud. 3) Online course platforms: Udemy, LinkedIn Learning, and Skillshare. 4) Communities/forums: Reddit's r/premierepro and Adobe's Premiere Pro forum. Also, practice and experiment with small projects as you learn."}
202
+ {"question_id":"06878be2","hypothesis":""}
203
+ {"question_id":"75832dbd","hypothesis":""}
204
+ {"question_id":"0edc2aef","hypothesis":"I cannot suggest a hotel in Miami based only on this conversation history, which contains information only about The Edgewater Hotel in Seattle. Please provide preferences or details about Miami (neighborhood, budget, desired amenities) or allow me to search for Miami hotels."}
205
+ {"question_id":"35a27287","hypothesis":""}
206
+ {"question_id":"32260d93","hypothesis":"Watch 'Hasan Minhaj: Homecoming King' — a Netflix stand-up special with strong, personal storytelling that should appeal if you like John Mulaney's narrative-driven style."}
207
+ {"question_id":"195a1a1b","hypothesis":""}
208
+ {"question_id":"afdc33df","hypothesis":""}
209
+ {"question_id":"caf03d32","hypothesis":""}
210
+ {"question_id":"54026fce","hypothesis":""}
211
+ {"question_id":"06f04340","hypothesis":""}
212
+ {"question_id":"6b7dfb22","hypothesis":""}
213
+ {"question_id":"1a1907b4","hypothesis":""}
214
+ {"question_id":"09d032c9","hypothesis":""}
215
+ {"question_id":"38146c39","hypothesis":""}
216
+ {"question_id":"d24813b1","hypothesis":""}
217
+ {"question_id":"57f827a0","hypothesis":""}
218
+ {"question_id":"95228167","hypothesis":""}
219
+ {"question_id":"505af2f5","hypothesis":""}
220
+ {"question_id":"75f70248","hypothesis":""}
221
+ {"question_id":"d6233ab6","hypothesis":"Yes — based on your positive memories (debate team, AP economics) and current nostalgia, attending your high school reunion would likely be a good idea as an opportunity to reconnect and reminisce. If you feel uncertain, you could plan to attend briefly or set a personal goal (e.g., talk to a few people) so it feels manageable."}
222
+ {"question_id":"1da05512","hypothesis":""}
223
+ {"question_id":"fca70973","hypothesis":""}
224
+ {"question_id":"b6025781","hypothesis":""}
225
+ {"question_id":"a89d7624","hypothesis":""}
226
+ {"question_id":"b0479f84","hypothesis":""}
227
+ {"question_id":"1d4e3b97","hypothesis":""}
228
+ {"question_id":"07b6f563","hypothesis":""}
229
+ {"question_id":"1c0ddc50","hypothesis":""}
230
+ {"question_id":"0a34ad58","hypothesis":""}
231
+ {"question_id":"7161e7e2","hypothesis":"Admon was assigned to the 8 am - 4 pm (Day Shift) on Sunday."}
232
+ {"question_id":"c4f10528","hypothesis":"Miss Bee Providore"}
233
+ {"question_id":"89527b6b","hypothesis":"blue"}
234
+ {"question_id":"e9327a54","hypothesis":"The Sugar Factory — a sweet shop at Icon Park known for its giant milkshakes."}
235
+ {"question_id":"4c36ccef","hypothesis":"Roscioli"}
236
+ {"question_id":"6ae235be","hypothesis":"The Lake Charles Refinery uses atmospheric distillation, fluid catalytic cracking (FCC), alkylation, and hydrotreating."}
237
+ {"question_id":"7e00a6cb","hypothesis":"International Budget Hostel"}
238
+ {"question_id":"1903aded","hypothesis":"Transcriptionist"}
239
+ {"question_id":"ceb54acb","hypothesis":"Sexual fixations; Problematic sexual behaviors; Sexual impulsivity; Compulsive sexuality"}
240
+ {"question_id":"f523d9fe","hypothesis":"Doc Martin"}
241
+ {"question_id":"0e5e2d1a","hypothesis":"38 subjects"}
242
+ {"question_id":"fea54f57","hypothesis":"The song was \"Evolution.\""}
243
+ {"question_id":"cc539528","hypothesis":"Ruby, Python, and PHP."}
244
+ {"question_id":"dc439ea3","hypothesis":"Hoop Dance"}
245
+ {"question_id":"18dcd5a5","hypothesis":"The party will face 4 mummies in the temple."}
246
+ {"question_id":"488d3006","hypothesis":"GR-90"}
247
+ {"question_id":"58470ed2","hypothesis":"Borges wrote: \"The Library is a sphere whose exact center is any one of its hexagons and whose circumference is inaccessible.\""}
248
+ {"question_id":"8cf51dda","hypothesis":"1. To identify molecular subtypes of endometrial cancer using a combination of genomic and transcriptomic approaches.\n2. To investigate the clinical and biological significance of the identified molecular subtypes, including their association with patient outcomes and response to therapy.\n3. To develop biomarkers for the early detection and prognosis of endometrial cancer based on the identified molecular subtypes."}
249
+ {"question_id":"1d4da289","hypothesis":"The assistant referred to biometric authentication (e.g., fingerprint or facial recognition) and one-time passwords (OTP) as two-factor authentication methods."}
250
+ {"question_id":"8464fc84","hypothesis":"Roscioli"}
251
+ {"question_id":"8aef76bc","hypothesis":"Mod Podge (or another sealant) to make the vase water-resistant."}
252
+ {"question_id":"71a3fd6b","hypothesis":"+49 (0) 62 32 / 14 23 - 0"}
253
+ {"question_id":"2bf43736","hypothesis":"Chapter 4 of Book 1 of the second part (titled \"Vocal Prayer and Meditation\")."}
254
+ {"question_id":"70b3e69b","hypothesis":"Manolo García"}
255
+ {"question_id":"8752c811","hypothesis":"Sound effects (e.g., ambient, diegetic, non-diegetic, etc.)"}
256
+ {"question_id":"3249768e","hypothesis":"Absinthe"}
257
+ {"question_id":"1b9b7252","hypothesis":"Mindful.org"}
258
+ {"question_id":"1568498a","hypothesis":""}
259
+ {"question_id":"6222b6eb","hypothesis":"6S (the 6S radiative transfer model) is implemented in the SIAC_GEE tool."}
260
+ {"question_id":"e8a79c70","hypothesis":"2-3 eggs"}
261
+ {"question_id":"d596882b","hypothesis":"By Chloe"}
262
+ {"question_id":"e3fc4d6e","hypothesis":"Dr. Arati Prabhakar"}
263
+ {"question_id":"51b23612","hypothesis":"The Soviet cartoon mentioned was \"Nu, pogodi!\", which the assistant said mocked Western culture and portrayed the Soviet Union as superior."}
264
+ {"question_id":"3e321797","hypothesis":"Leave it on for about 10 minutes, then wash it off with cold water."}
265
+ {"question_id":"e982271f","hypothesis":"Revolution Hall"}
266
+ {"question_id":"352ab8bd","hypothesis":"Approximately 20% average improvement in framerate when using the HAMT agent."}
267
+ {"question_id":"fca762bc","hypothesis":"Memrise"}
268
+ {"question_id":"7a8d0b71","hypothesis":"$2,000"}
269
+ {"question_id":"a40e080f","hypothesis":"Patagonia and Southwest Airlines"}
270
+ {"question_id":"8b9d4367","hypothesis":"Jaipur Rugs"}
271
+ {"question_id":"5809eb10","hypothesis":"2014"}
272
+ {"question_id":"41275add","hypothesis":"How to Sit Properly at a Desk to Avoid Back Pain — Mayo Clinic: https://www.youtube.com/watch?v=UfOvNlX9Hh0"}
273
+ {"question_id":"4388e9dd","hypothesis":"He was wearing an untidy, stained white shirt."}
274
+ {"question_id":"4baee567","hypothesis":"12"}
275
+ {"question_id":"561fabcd","hypothesis":"Fissionator"}
276
+ {"question_id":"b759caee","hypothesis":"@jessica_poole_jewellery"}
277
+ {"question_id":"ac031881","hypothesis":"LIV"}
278
+ {"question_id":"28bcfaac","hypothesis":"MusicTheory.net"}
279
+ {"question_id":"16c90bf4","hypothesis":"I recommended a light or medium-bodied beer — specifically a Pilsner or a lager (with the option of using a local beer from Ancash)."}
280
+ {"question_id":"c8f1aeed","hypothesis":"Pennsylvania"}
281
+ {"question_id":"eaca4986","hypothesis":"C D E F G A B A G F E D C"}
282
+ {"question_id":"c7cf7dfd","hypothesis":"Nostalgia"}
283
+ {"question_id":"e48988bc","hypothesis":"Patagonia."}
284
+ {"question_id":"1de5cff2","hypothesis":"Veja"}
285
+ {"question_id":"65240037","hypothesis":"Dilute tea tree oil with a carrier oil at a 1:10 ratio (one part tea tree oil to ten parts carrier oil)."}
286
+ {"question_id":"778164c6","hypothesis":""}
287
+ {"question_id":"e47becba","hypothesis":"Business Administration"}
288
+ {"question_id":"118b2229","hypothesis":"45 minutes each way."}
289
+ {"question_id":"51a45a95","hypothesis":"Not specified in the conversation history."}
290
+ {"question_id":"58bf7951","hypothesis":"The Glass Menagerie"}
291
+ {"question_id":"1e043500","hypothesis":"Summer Vibes"}
292
+ {"question_id":"c5e8278d","hypothesis":"Johnson"}
293
+ {"question_id":"6ade9755","hypothesis":"You take yoga at your local Serenity Yoga studio and at home using the Down Dog app."}
294
+ {"question_id":"6f9b354f","hypothesis":"A lighter shade of gray"}
295
+ {"question_id":"58ef2f1c","hypothesis":""}
296
+ {"question_id":"f8c5f88b","hypothesis":"A sports store downtown."}
297
+ {"question_id":"5d3d2817","hypothesis":"Marketing specialist at a small startup"}
298
+ {"question_id":"7527f7e2","hypothesis":"$800"}
299
+ {"question_id":"c960da58","hypothesis":"20"}
300
+ {"question_id":"3b6f954b","hypothesis":"University of Melbourne"}
301
+ {"question_id":"726462e0","hypothesis":"10%"}
302
+ {"question_id":"94f70d80","hypothesis":"4 hours"}
303
+ {"question_id":"66f24dbb","hypothesis":"A yellow dress and a pair of earrings that match the dress."}
304
+ {"question_id":"ad7109d1","hypothesis":"500 Mbps"}
305
+ {"question_id":"af8d2e46","hypothesis":"7 shirts"}
306
+ {"question_id":"dccbc061","hypothesis":"You used to be a staunch atheist."}
307
+ {"question_id":"c8c3f81d","hypothesis":"Nike"}
308
+ {"question_id":"8ebdbe50","hypothesis":"A Data Science certification."}
309
+ {"question_id":"6b168ec8","hypothesis":"3"}
310
+ {"question_id":"75499fd8","hypothesis":"Golden Retriever"}
311
+ {"question_id":"21436231","hypothesis":"12"}
312
+ {"question_id":"95bcc1c8","hypothesis":"10"}
313
+ {"question_id":"0862e8bf","hypothesis":"Luna"}
314
+ {"question_id":"853b0a1d","hypothesis":"18"}
315
+ {"question_id":"a06e4cfe","hypothesis":"3:1 (gin to vermouth)"}
316
+ {"question_id":"37d43f65","hypothesis":"16GB"}
317
+ {"question_id":"b86304ba","hypothesis":""}
318
+ {"question_id":"d52b4f67","hypothesis":"The Grand Ballroom"}
319
+ {"question_id":"25e5aa4f","hypothesis":"UCLA"}
320
+ {"question_id":"caf9ead2","hypothesis":"Around 5 hours."}
321
+ {"question_id":"8550ddae","hypothesis":"Lavender gin fizz"}
322
+ {"question_id":"60d45044","hypothesis":"Japanese short-grain rice"}
323
+ {"question_id":"3f1e9474","hypothesis":"Sarah"}
324
+ {"question_id":"86b68151","hypothesis":"IKEA"}
325
+ {"question_id":"577d4d32","hypothesis":"7 pm"}
326
+ {"question_id":"ec81a493","hypothesis":"500 copies worldwide"}
327
+ {"question_id":"15745da0","hypothesis":"Three months"}
328
+ {"question_id":"e01b8e2f","hypothesis":"Hawaii"}
329
+ {"question_id":"bc8a6e93","hypothesis":"Lemon blueberry cake"}
330
+ {"question_id":"ccb36322","hypothesis":"Spotify"}
331
+ {"question_id":"001be529","hypothesis":"Over a year."}
332
+ {"question_id":"b320f3f8","hypothesis":"A rare blue Snaggletooth action figure."}
333
+ {"question_id":"19b5f2b3","hypothesis":"Two weeks"}
334
+ {"question_id":"4fd1909e","hypothesis":"Xfinity Center"}
335
+ {"question_id":"545bd2b5","hypothesis":"About 2 hours per day."}
336
+ {"question_id":"8a137a7f","hypothesis":"Philips LED bulb"}
337
+ {"question_id":"76d63226","hypothesis":"55-inch"}
338
+ {"question_id":"86f00804","hypothesis":"The Seven Husbands of Evelyn Hugo"}
339
+ {"question_id":"8e9d538c","hypothesis":"17 skeins"}
340
+ {"question_id":"311778f1","hypothesis":"10 hours"}
341
+ {"question_id":"c19f7a0b","hypothesis":"Around 6:30 PM on weekdays."}
342
+ {"question_id":"4100d0a0","hypothesis":"Mixed ethnicity: Irish and Italian."}
343
+ {"question_id":"29f2956b","hypothesis":"30 minutes per day"}
344
+ {"question_id":"1faac195","hypothesis":"Emily lives in Denver."}
345
+ {"question_id":"faba32e5","hypothesis":"24 hours"}
346
+ {"question_id":"f4f1d8a4","hypothesis":"Your sister"}
347
+ {"question_id":"c14c00dd","hypothesis":"A lavender-scented shampoo purchased at Trader Joe's (no specific brand name was given)."}
348
+ {"question_id":"36580ce8","hypothesis":"Bronchitis"}
349
+ {"question_id":"3d86fd0a","hypothesis":"A coffee shop in the city."}
350
+ {"question_id":"a82c026e","hypothesis":"The last boss in the Dark Souls 3 DLC (Dark Souls 3 DLC)."}
351
+ {"question_id":"0862e8bf_abs","hypothesis":"I cannot answer — there is no information about a hamster or its name in the conversation history."}
352
+ {"question_id":"15745da0_abs","hypothesis":"I cannot determine how long you've been collecting vintage films because the conversation history contains no information about collecting vintage films."}
353
+ {"question_id":"bc8a6e93_abs","hypothesis":"Cannot be determined from the conversation — no information about an uncle's birthday or what was baked for it is provided."}
354
+ {"question_id":"19b5f2b3_abs","hypothesis":"Cannot be determined from the conversation history."}
355
+ {"question_id":"29f2956b_abs","hypothesis":"Cannot determine — the conversation history contains no information about daily violin practice."}
356
+ {"question_id":"f4f1d8a4_abs","hypothesis":"Cannot determine — the conversation does not say what, if anything, your dad gave you as a birthday gift."}
357
+ {"question_id":"gpt4_59149c77","hypothesis":"7 days"}
358
+ {"question_id":"gpt4_f49edff3","hypothesis":"First: helped friend prepare the nursery (2023-02-06); Second: helped cousin pick out stuff for her baby shower (2023-02-10); Third: ordered a customized phone case for a friend's birthday (2023-02-20)."}
359
+ {"question_id":"71017276","hypothesis":"About 4 weeks ago (approximately 29 days, ≈4.1 weeks)."}
360
+ {"question_id":"b46e15ed","hypothesis":""}
361
+ {"question_id":"gpt4_fa19884c","hypothesis":"7 days"}
362
+ {"question_id":"0bc8ad92","hypothesis":"About 5 months (5 months and 3 days, from 2022-10-22 to 2023-03-25)."}
363
+ {"question_id":"af082822","hypothesis":"2 weeks ago"}
364
+ {"question_id":"gpt4_4929293a","hypothesis":"Michael's engagement party happened before your cousin's wedding."}
365
+ {"question_id":"gpt4_b5700ca9","hypothesis":"3 days ago"}
366
+ {"question_id":"9a707b81","hypothesis":"21 days"}
367
+ {"question_id":"gpt4_1d4ab0c9","hypothesis":"24 days"}
368
+ {"question_id":"gpt4_e072b769","hypothesis":"About 3 weeks ago (approximately 2.9 weeks)."}
369
+ {"question_id":"0db4c65d","hypothesis":"18 days"}
370
+ {"question_id":"gpt4_1d80365e","hypothesis":""}
371
+ {"question_id":"gpt4_7f6b06db","hypothesis":""}
372
+ {"question_id":"gpt4_6dc9b45b","hypothesis":"4 months ago"}
373
+ {"question_id":"gpt4_8279ba02","hypothesis":"11 days ago"}
374
+ {"question_id":"gpt4_18c2b244","hypothesis":""}
375
+ {"question_id":"gpt4_a1b77f9c","hypothesis":"I cannot determine the total number of weeks because the conversation history does not state how long you spent on each book."}
376
+ {"question_id":"gpt4_1916e0ea","hypothesis":""}
377
+ {"question_id":"gpt4_7a0daae1","hypothesis":"1 week"}
378
+ {"question_id":"gpt4_468eb063","hypothesis":"9 days ago"}
379
+ {"question_id":"gpt4_7abb270c","hypothesis":""}
380
+ {"question_id":"gpt4_1e4a8aeb","hypothesis":"Cannot be determined from the conversation history: the exact date of the gardening workshop attendance is not stated."}
381
+ {"question_id":"gpt4_4fc4f797","hypothesis":""}
382
+ {"question_id":"4dfccbf7","hypothesis":"0 days"}
383
+ {"question_id":"gpt4_61e13b3c","hypothesis":""}
384
+ {"question_id":"gpt4_45189cb4","hypothesis":""}
385
+ {"question_id":"2ebe6c90","hypothesis":"21 days"}
386
+ {"question_id":"gpt4_e061b84f","hypothesis":""}
387
+ {"question_id":"370a8ff4","hypothesis":"11 weeks and 4 days (about 11.6 weeks)"}
388
+ {"question_id":"gpt4_d6585ce8","hypothesis":"I cannot determine an order because the conversation only mentions one attended event (a music festival in Brooklyn). No other past concerts/events or dates are provided."}
389
+ {"question_id":"gpt4_4ef30696","hypothesis":"1 day"}
390
+ {"question_id":"gpt4_ec93e27f","hypothesis":"train"}
391
+ {"question_id":"6e984301","hypothesis":""}
392
+ {"question_id":"8077ef71","hypothesis":"26 days ago"}
393
+ {"question_id":"gpt4_f420262c","hypothesis":""}
394
+ {"question_id":"gpt4_8e165409","hypothesis":"14 days"}
395
+ {"question_id":"gpt4_74aed68e","hypothesis":"29 days"}
396
+ {"question_id":"bcbe585f","hypothesis":"About 4.3 weeks ago (approximately 4 weeks and 2 days)."}
397
+ {"question_id":"gpt4_21adecb5","hypothesis":""}
398
+ {"question_id":"5e1b23de","hypothesis":"About 3 months ago (the workshop date was 2023-11-01)."}
399
+ {"question_id":"gpt4_98f46fc6","hypothesis":"The charity bake sale occurred first (on 2023-03-15), and the charity gala occurred later (around 2023-03-28)."}
400
+ {"question_id":"gpt4_af6db32f","hypothesis":"17 days ago"}
401
+ {"question_id":"eac54adc","hypothesis":"18 days"}
402
+ {"question_id":"gpt4_7ddcf75f","hypothesis":"2 days ago"}
403
+ {"question_id":"gpt4_a2d1d1f6","hypothesis":"3 days ago"}
404
+ {"question_id":"gpt4_85da3956","hypothesis":"Three weeks ago."}
405
+ {"question_id":"gpt4_b0863698","hypothesis":"7 days ago"}
406
+ {"question_id":"gpt4_68e94287","hypothesis":"The post about the vegan chili recipe happened first."}
407
+ {"question_id":"gpt4_e414231e","hypothesis":"4 days"}
408
+ {"question_id":"gpt4_7ca326fa","hypothesis":""}
409
+ {"question_id":"gpt4_7bc6cf22","hypothesis":"12 days ago"}
410
+ {"question_id":"2ebe6c92","hypothesis":""}
411
+ {"question_id":"gpt4_e061b84g","hypothesis":"The company's annual charity soccer tournament."}
412
+ {"question_id":"71017277","hypothesis":"Cannot be determined from the conversation history."}
413
+ {"question_id":"b46e15ee","hypothesis":"Walk for Hunger"}
414
+ {"question_id":"gpt4_d6585ce9","hypothesis":"I cannot determine who you went with last Saturday from the conversation history."}
415
+ {"question_id":"gpt4_1e4a8aec","hypothesis":""}
416
+ {"question_id":"gpt4_f420262d","hypothesis":"JetBlue"}
417
+ {"question_id":"gpt4_59149c78","hypothesis":""}
418
+ {"question_id":"gpt4_e414231f","hypothesis":""}
419
+ {"question_id":"gpt4_4929293b","hypothesis":"Cannot determine — the conversation states you were a bridesmaid at your cousin's wedding, but it does not say this (or any other mentioned event) occurred a week ago."}
420
+ {"question_id":"gpt4_468eb064","hypothesis":"Emma"}
421
+ {"question_id":"gpt4_fa19884d","hypothesis":"Unknown (the conversation says the user discovered a 'bluegrass band that features a banjo player' on 2023-03-31 but does not give the band's or artist's name)."}
422
+ {"question_id":"9a707b82","hypothesis":"You baked a chocolate cake for your friend's birthday party."}
423
+ {"question_id":"eac54add","hypothesis":"You mentioned that you landed your first client."}
424
+ {"question_id":"4dfccbf8","hypothesis":"You started taking ukulele lessons with your friend Rachel."}
425
+ {"question_id":"0bc8ad93","hypothesis":"Yes — you mentioned visiting the museum with a friend (a chemistry professor)."}
426
+ {"question_id":"6e984302","hypothesis":"You bought a set of sculpting tools: a modeling tool set, a wire cutter, and a sculpting mat."}
427
+ {"question_id":"gpt4_8279ba03","hypothesis":"Smoker"}
428
+ {"question_id":"gpt4_b5700ca0","hypothesis":"Episcopal Church"}
429
+ {"question_id":"gpt4_68e94288","hypothesis":"You participated in the social media #PlankChallenge."}
430
+ {"question_id":"d3ab962e","hypothesis":"8 miles"}
431
+ {"question_id":"2311e44b","hypothesis":"190 pages left"}
432
+ {"question_id":"cc06de0d","hypothesis":"The taxi ride was $6 more expensive than the train fare."}
433
+ {"question_id":"a11281a2","hypothesis":""}
434
+ {"question_id":"4f54b7c9","hypothesis":"2"}
435
+ {"question_id":"85fa3a3f","hypothesis":"$50"}
436
+ {"question_id":"9aaed6a3","hypothesis":"$0.75"}
437
+ {"question_id":"1f2b8d4f","hypothesis":"$750"}
438
+ {"question_id":"e6041065","hypothesis":"Cannot determine — the total number of shoes you packed on your last trip is not specified. If you tell me how many shoes you packed, I can calculate the percentage (percentage = 2 / total_packed * 100%)."}
439
+ {"question_id":"51c32626","hypothesis":"Cannot determine from the conversation history; no submission date is given."}
440
+ {"question_id":"d905b33f","hypothesis":"20%"}
441
+ {"question_id":"7405e8b1","hypothesis":""}
442
+ {"question_id":"f35224e0","hypothesis":"Approximately 27 episodes total (12 of 'My Favorite Murder' + around 15 of 'How I Built This')."}
443
+ {"question_id":"6456829e","hypothesis":"Tomatoes: 5 plants initially. Cucumbers: 3 plants."}
444
+ {"question_id":"a4996e51","hypothesis":""}
445
+ {"question_id":"3c1045c8","hypothesis":"You are 2.5 years older than the average employee in your department (about 2 years and 6 months)."}
446
+ {"question_id":"60036106","hypothesis":"12,000 people"}
447
+ {"question_id":"681a1674","hypothesis":"1"}
448
+ {"question_id":"e25c3b8d","hypothesis":"Cannot determine the amount saved. The conversation only states the purchase price ($200) and does not provide the original/retail price needed to calculate savings."}
449
+ {"question_id":"4adc0475","hypothesis":"5 (3 goals + 2 assists)"}
450
+ {"question_id":"4bc144e2","hypothesis":"$65"}
451
+ {"question_id":"ef66a6e5","hypothesis":"2"}
452
+ {"question_id":"5025383b","hypothesis":"Cooking and photography"}
453
+ {"question_id":"a1cc6108","hypothesis":"You were 11 years old when Alex was born."}
454
+ {"question_id":"9ee3ecd6","hypothesis":"You need 100 more points (300 points total) to redeem the free skincare product."}
455
+ {"question_id":"3fdac837","hypothesis":"12 days"}
456
+ {"question_id":"91b15a6e","hypothesis":"At least $5,150"}
457
+ {"question_id":"27016adc","hypothesis":"10%"}
458
+ {"question_id":"720133ac","hypothesis":"$75"}
459
+ {"question_id":"77eafa52","hypothesis":"$300"}
460
+ {"question_id":"8979f9ec","hypothesis":"8 lunches"}
461
+ {"question_id":"0100672e","hypothesis":"$12 per coffee mug"}
462
+ {"question_id":"a96c20ee","hypothesis":"Cannot be determined from the conversation history."}
463
+ {"question_id":"92a0aa75","hypothesis":"Cannot determine from the conversation history. The user said it took 2 years and 4 months to work up to the Senior Marketing Specialist role, but did not state how long they have held that role."}
464
+ {"question_id":"3fe836c9","hypothesis":"$25,000"}
465
+ {"question_id":"1c549ce4","hypothesis":"$140"}
466
+ {"question_id":"6c49646a","hypothesis":"3,000 miles"}
467
+ {"question_id":"1192316e","hypothesis":"90 minutes (1 hour 30 minutes)"}
468
+ {"question_id":"0ea62687","hypothesis":"2 miles per gallon"}
469
+ {"question_id":"67e0d0f2","hypothesis":"12"}
470
+ {"question_id":"bb7c3b45","hypothesis":"$300"}
471
+ {"question_id":"ba358f49","hypothesis":"I cannot determine your age when Rachel gets married because your current age or birthdate was not provided in the conversation."}
472
+ {"question_id":"61f8c8f8","hypothesis":"Cannot determine — the conversation only states last year's 5K time (45 minutes) and does not provide your current 5K finishing time."}
473
+ {"question_id":"60159905","hypothesis":""}
474
+ {"question_id":"ef9cf60a","hypothesis":"$300"}
475
+ {"question_id":"73d42213","hypothesis":"9:00 AM"}
476
+ {"question_id":"bc149d6b","hypothesis":"50 pounds"}
477
+ {"question_id":"099778bb","hypothesis":"20%"}
478
+ {"question_id":"09ba9854","hypothesis":""}
479
+ {"question_id":"d6062bb9","hypothesis":"1,998 views total (1,456 on TikTok + 542 on YouTube)."}
480
+ {"question_id":"157a136e","hypothesis":""}
481
+ {"question_id":"c18a7dc8","hypothesis":"7 years"}
482
+ {"question_id":"a3332713","hypothesis":"$200"}
483
+ {"question_id":"55241a1f","hypothesis":"Cannot determine total. Facebook Live = 12 comments; the number of comments on your most popular YouTube video is not specified in the conversation, so a total cannot be calculated."}
484
+ {"question_id":"a08a253f","hypothesis":"4 days per week"}
485
+ {"question_id":"f0e564bc","hypothesis":"$1,300"}
486
+ {"question_id":"078150f1","hypothesis":"$50"}
487
+ {"question_id":"8cf4d046","hypothesis":"The average GPA across your undergraduate and graduate studies is 3.83 out of 4.0."}
488
+ {"question_id":"a346bb18","hypothesis":"12 minutes"}
489
+ {"question_id":"37f165cf","hypothesis":"Cannot determine from the conversation: no novels are explicitly stated as having been finished in January or March."}
490
+ {"question_id":"8e91e7d9","hypothesis":"4"}
491
+ {"question_id":"87f22b4a","hypothesis":"$120"}
492
+ {"question_id":"e56a43b9","hypothesis":"$5 discount"}
493
+ {"question_id":"efc3f7c2","hypothesis":"You wake up 30 minutes earlier on Fridays."}
494
+ {"question_id":"21d02d0d","hypothesis":""}
495
+ {"question_id":"2311e44b_abs","hypothesis":"I cannot determine how many pages you have left in 'Sapiens' from the conversation history. Please tell me the book's total page count and your current page (or how many pages you've already read), and I will calculate the pages remaining."}
496
+ {"question_id":"6456829e_abs","hypothesis":"Tomatoes: 5. Chili peppers: unknown (not stated in the conversation)."}
497
+ {"question_id":"e5ba910e_abs","hypothesis":"Cannot determine total cost — the headphones cost $378, but no iPad purchase or price is provided in the conversation."}
498
+ {"question_id":"a96c20ee_abs","hypothesis":""}
499
+ {"question_id":"ba358f49_abs","hypothesis":"I cannot determine Rachel's age when you get married because the conversation does not include Rachel's current age or the date/year of your wedding."}
500
+ {"question_id":"09ba9854_abs","hypothesis":""}
packages/benchmark/src/cli/commands/evaluate.ts ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { readFile, writeFile } from "node:fs/promises";
2
+ import { Evaluator, formatMetricsReport, parseJsonlResults } from "../../longmemeval/evaluator.js";
3
+ import { loadDataset } from "../../longmemeval/loader.js";
4
+
5
+ interface EvaluateOptions {
6
+ hypothesis: string;
7
+ groundTruth: string;
8
+ output?: string;
9
+ llmEval: boolean;
10
+ }
11
+
12
+ export async function evaluateCommand(options: EvaluateOptions): Promise<void> {
13
+ console.log("📊 Evaluating benchmark results");
14
+ console.log("");
15
+ console.log(` Hypothesis file: ${options.hypothesis}`);
16
+ console.log(` Ground truth: ${options.groundTruth}`);
17
+ console.log(` LLM evaluation: ${options.llmEval}`);
18
+ console.log("");
19
+
20
+ try {
21
+ // Load hypothesis results
22
+ console.log("Loading hypothesis file...");
23
+ const hypothesisContent = await readFile(options.hypothesis, "utf-8");
24
+ const results = parseJsonlResults(hypothesisContent);
25
+ console.log(` Loaded ${results.length} results`);
26
+
27
+ // Load ground truth
28
+ console.log("Loading ground truth dataset...");
29
+ const { instances } = await loadDataset({ datasetPath: options.groundTruth });
30
+ console.log(` Loaded ${instances.length} instances`);
31
+
32
+ // Evaluate
33
+ console.log("Evaluating...");
34
+
35
+ // TODO: Add LLM provider for LLM-based evaluation
36
+ if (options.llmEval) {
37
+ console.warn("⚠️ LLM evaluation requested but no LLM provider configured");
38
+ console.warn(" Falling back to string matching");
39
+ }
40
+
41
+ const evaluator = new Evaluator({ useLLMEvaluation: false });
42
+ const { evaluated, metrics } = await evaluator.evaluateAll(results, instances);
43
+
44
+ // Print report
45
+ console.log("");
46
+ console.log("=".repeat(60));
47
+ console.log(formatMetricsReport(metrics));
48
+ console.log("=".repeat(60));
49
+
50
+ // Save metrics if output path specified
51
+ if (options.output) {
52
+ const outputData = {
53
+ metrics,
54
+ evaluated: evaluated.map((e) => ({
55
+ questionId: e.questionId,
56
+ questionType: e.questionType,
57
+ memoryAbility: e.memoryAbility,
58
+ correct: e.correct,
59
+ })),
60
+ };
61
+ await writeFile(options.output, JSON.stringify(outputData, null, 2), "utf-8");
62
+ console.log(`\n✅ Metrics saved to: ${options.output}`);
63
+ }
64
+
65
+ // Exit with appropriate code
66
+ const accuracy = metrics.overall.accuracy;
67
+ if (accuracy >= 0.7) {
68
+ console.log("\n✅ Benchmark passed (accuracy >= 70%)");
69
+ } else if (accuracy >= 0.5) {
70
+ console.log("\n⚠️ Benchmark marginal (50% <= accuracy < 70%)");
71
+ } else {
72
+ console.log("\n❌ Benchmark needs improvement (accuracy < 50%)");
73
+ }
74
+ } catch (error) {
75
+ console.error("\n❌ Evaluation failed:", error);
76
+ process.exit(1);
77
+ }
78
+ }
packages/benchmark/src/cli/commands/ingest.ts ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Ingest command - loads LongMemEval dataset into FalkorDB
3
+ */
4
+
5
+ import { readFile } from "node:fs/promises";
6
+ import { LongMemEvalDatasetSchema } from "../../longmemeval/types.js";
7
+
8
+ interface IngestOptions {
9
+ dataset: string;
10
+ falkorUrl: string;
11
+ qdrantUrl: string;
12
+ embeddingModel: string;
13
+ clear: boolean;
14
+ verbose: boolean;
15
+ }
16
+
17
+ export async function ingestCommand(options: IngestOptions): Promise<void> {
18
+ const { dataset, falkorUrl, verbose } = options;
19
+
20
+ console.log("=== Engram Benchmark Data Ingestion ===");
21
+ console.log(`Dataset: ${dataset}`);
22
+ console.log(`FalkorDB: ${falkorUrl}`);
23
+ console.log("");
24
+
25
+ // Load and parse dataset
26
+ console.log("Loading dataset...");
27
+ const raw = await readFile(dataset, "utf-8");
28
+ const data = LongMemEvalDatasetSchema.parse(JSON.parse(raw));
29
+ console.log(`Loaded ${data.length} instances\n`);
30
+
31
+ // Dynamic import of falkordb
32
+ const { FalkorDB } = await import("falkordb");
33
+
34
+ // Connect to FalkorDB
35
+ console.log("Connecting to FalkorDB...");
36
+ const url = new URL(falkorUrl);
37
+ const db = await FalkorDB.connect({
38
+ socket: { host: url.hostname, port: Number.parseInt(url.port) || 6379 },
39
+ });
40
+ const graph = db.selectGraph("engram_benchmark");
41
+
42
+ // Create indexes (FalkorDB syntax)
43
+ console.log("Creating indexes...");
44
+ try {
45
+ await graph.query("CREATE INDEX FOR (s:Session) ON (s.id)");
46
+ } catch {
47
+ /* exists */
48
+ }
49
+ try {
50
+ await graph.query("CREATE INDEX FOR (t:Turn) ON (t.id)");
51
+ } catch {
52
+ /* exists */
53
+ }
54
+ try {
55
+ await graph.query("CREATE INDEX FOR (m:Memory) ON (m.id)");
56
+ } catch {
57
+ /* exists */
58
+ }
59
+
60
+ // Track unique sessions
61
+ const processedSessions = new Set<string>();
62
+ let sessionsCreated = 0;
63
+ let turnsCreated = 0;
64
+ let memoriesCreated = 0;
65
+
66
+ const now = new Date().toISOString();
67
+
68
+ // Process each instance
69
+ console.log("Processing instances...");
70
+ for (const instance of data) {
71
+ for (let i = 0; i < instance.haystack_sessions.length; i++) {
72
+ const sessionId = instance.haystack_session_ids[i];
73
+ const sessionDate = instance.haystack_dates[i];
74
+ const session = instance.haystack_sessions[i];
75
+
76
+ if (processedSessions.has(sessionId)) continue;
77
+ processedSessions.add(sessionId);
78
+
79
+ // Create Session node using parameterized query
80
+ const sessionEpoch = new Date(sessionDate).getTime();
81
+ await graph.query(
82
+ `MERGE (s:Session {id: $id}) ON CREATE SET s.vt_start = $vtStart, s.vt_end = $vtEnd, s.tt_start = $ttStart, s.tt_end = $ttEnd, s.started_at = $startedAt, s.user_id = $userId, s.agent_type = $agentType`,
83
+ {
84
+ params: {
85
+ id: sessionId,
86
+ vtStart: sessionDate,
87
+ vtEnd: "9999-12-31T23:59:59.999Z",
88
+ ttStart: now,
89
+ ttEnd: "9999-12-31T23:59:59.999Z",
90
+ startedAt: sessionEpoch,
91
+ userId: "longmemeval",
92
+ agentType: "unknown",
93
+ },
94
+ },
95
+ );
96
+ sessionsCreated++;
97
+
98
+ // Process turns (pairs of user + assistant messages)
99
+ for (let turnIdx = 0; turnIdx < session.length - 1; turnIdx += 2) {
100
+ const userTurn = session[turnIdx];
101
+ const assistantTurn = session[turnIdx + 1];
102
+
103
+ if (!userTurn || userTurn.role !== "user") continue;
104
+
105
+ const userContent = userTurn.content.slice(0, 500);
106
+ const assistantContent = (assistantTurn?.content ?? "").slice(0, 500);
107
+ const turnId = `turn_${sessionId}_${turnIdx}`;
108
+
109
+ // Create Turn node using parameterized query
110
+ await graph.query(
111
+ `MERGE (t:Turn {id: $id}) ON CREATE SET t.vt_start = $vtStart, t.vt_end = $vtEnd, t.tt_start = $ttStart, t.tt_end = $ttEnd, t.user_content = $userContent, t.assistant_preview = $assistantPreview, t.sequence_index = $seqIdx`,
112
+ {
113
+ params: {
114
+ id: turnId,
115
+ vtStart: sessionDate,
116
+ vtEnd: "9999-12-31T23:59:59.999Z",
117
+ ttStart: now,
118
+ ttEnd: "9999-12-31T23:59:59.999Z",
119
+ userContent,
120
+ assistantPreview: assistantContent,
121
+ seqIdx: Math.floor(turnIdx / 2),
122
+ },
123
+ },
124
+ );
125
+
126
+ // Link Turn to Session
127
+ await graph.query(
128
+ `MATCH (s:Session {id: $sid}), (t:Turn {id: $tid}) MERGE (s)-[:HAS_TURN]->(t)`,
129
+ {
130
+ params: { sid: sessionId, tid: turnId },
131
+ },
132
+ );
133
+ turnsCreated++;
134
+
135
+ // Create Memory node
136
+ const memoryContent = `User: ${userTurn.content.slice(0, 200)} Assistant: ${(assistantTurn?.content ?? "").slice(0, 200)}`;
137
+ const memoryId = `mem_${sessionId}_${turnIdx}`;
138
+
139
+ await graph.query(
140
+ `MERGE (m:Memory {id: $id}) ON CREATE SET m.vt_start = $vtStart, m.vt_end = $vtEnd, m.tt_start = $ttStart, m.tt_end = $ttEnd, m.content = $content, m.type = $type, m.source_session_id = $srcSession, m.source_turn_id = $srcTurn, m.source = $source`,
141
+ {
142
+ params: {
143
+ id: memoryId,
144
+ vtStart: sessionDate,
145
+ vtEnd: "9999-12-31T23:59:59.999Z",
146
+ ttStart: now,
147
+ ttEnd: "9999-12-31T23:59:59.999Z",
148
+ content: memoryContent,
149
+ type: "turn",
150
+ srcSession: sessionId,
151
+ srcTurn: turnId,
152
+ source: "import",
153
+ },
154
+ },
155
+ );
156
+
157
+ // Link Memory to Turn
158
+ await graph.query(
159
+ `MATCH (t:Turn {id: $tid}), (m:Memory {id: $mid}) MERGE (t)-[:PRODUCES]->(m)`,
160
+ {
161
+ params: { tid: turnId, mid: memoryId },
162
+ },
163
+ );
164
+ memoriesCreated++;
165
+ }
166
+
167
+ if (verbose && sessionsCreated % 50 === 0) {
168
+ console.log(` Processed ${sessionsCreated} sessions...`);
169
+ }
170
+ }
171
+ }
172
+
173
+ console.log("\n=== Ingestion Complete ===");
174
+ console.log(`Sessions: ${sessionsCreated}`);
175
+ console.log(`Turns: ${turnsCreated}`);
176
+ console.log(`Memories: ${memoriesCreated}`);
177
+ }
packages/benchmark/src/cli/commands/run.ts ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { writeFile } from "node:fs/promises";
2
+ import {
3
+ BenchmarkPipeline,
4
+ type CustomRetriever,
5
+ type PipelineProgress,
6
+ type RetrievalDebugInfo,
7
+ } from "../../longmemeval/pipeline.js";
8
+ import {
9
+ AnthropicProvider,
10
+ GeminiProvider,
11
+ OllamaProvider,
12
+ OpenAICompatibleProvider,
13
+ } from "../../longmemeval/providers/anthropic-provider.js";
14
+ import { EngramRetriever } from "../../longmemeval/providers/engram-provider.js";
15
+ import { QdrantEmbeddingProvider } from "../../longmemeval/providers/qdrant-provider.js";
16
+ import type { LLMProvider } from "../../longmemeval/reader.js";
17
+ import { StubEmbeddingProvider, StubLLMProvider } from "../../longmemeval/reader.js";
18
+ import type { EmbeddingProvider } from "../../longmemeval/retriever.js";
19
+ import type { DatasetVariant } from "../../longmemeval/types.js";
20
+
21
+ interface RunOptions {
22
+ dataset: string;
23
+ variant: string;
24
+ output?: string;
25
+ limit?: number;
26
+ topK: number;
27
+ retriever: string;
28
+ chainOfNote: boolean;
29
+ timeAware: boolean;
30
+ verbose: boolean;
31
+ // Provider options
32
+ embeddings: string;
33
+ llm: string;
34
+ qdrantUrl?: string;
35
+ ollamaUrl?: string;
36
+ ollamaModel?: string;
37
+ // Gemini options
38
+ geminiModel?: string;
39
+ // Milestone 2 optimizations
40
+ keyExpansion: boolean;
41
+ temporalAnalysis: boolean;
42
+ // Engram full pipeline options
43
+ rerank: boolean;
44
+ rerankTier: string;
45
+ rerankDepth: number;
46
+ hybridSearch: boolean;
47
+ // Learned fusion options
48
+ learnedFusion: boolean;
49
+ fusionModel: string;
50
+ // Multi-query retrieval options
51
+ multiQuery: boolean;
52
+ multiQueryVariations: number;
53
+ // Abstention detection options
54
+ abstention: boolean;
55
+ abstentionThreshold: number;
56
+ abstentionHedging: boolean;
57
+ abstentionNli: boolean;
58
+ abstentionNliThreshold: number;
59
+ // Session-aware retrieval options
60
+ sessionAware: boolean;
61
+ topSessions: number;
62
+ turnsPerSession: number;
63
+ // Temporal query parsing options
64
+ temporalAware: boolean;
65
+ temporalConfidenceThreshold: number;
66
+ // Embedding model options
67
+ embeddingModel: string;
68
+ // Debug options
69
+ debugRetrieval: boolean;
70
+ }
71
+
72
+ export async function runCommand(benchmark: string, options: RunOptions): Promise<void> {
73
+ if (benchmark !== "longmemeval") {
74
+ console.error(`Unknown benchmark: ${benchmark}`);
75
+ console.error("Available benchmarks: longmemeval");
76
+ process.exit(1);
77
+ }
78
+
79
+ console.log("🚀 Starting LongMemEval benchmark");
80
+ console.log("");
81
+ console.log("Configuration:");
82
+ console.log(` Dataset: ${options.dataset}`);
83
+ console.log(` Variant: ${options.variant}`);
84
+ console.log(` Top-K: ${options.topK}`);
85
+ console.log(` Retriever: ${options.retriever}`);
86
+ console.log(` Chain-of-Note: ${options.chainOfNote}`);
87
+ console.log(` Time-Aware: ${options.timeAware}`);
88
+ console.log(` Embeddings: ${options.embeddings}`);
89
+ console.log(` LLM: ${options.llm}`);
90
+ console.log(` Key Expansion: ${options.keyExpansion}`);
91
+ console.log(` Temporal Analysis: ${options.temporalAnalysis}`);
92
+ if (options.embeddings === "engram") {
93
+ console.log(` Hybrid Search: ${options.hybridSearch}`);
94
+ console.log(` Learned Fusion: ${options.learnedFusion}`);
95
+ if (options.learnedFusion) {
96
+ console.log(` Fusion Model: ${options.fusionModel}`);
97
+ }
98
+ console.log(` Rerank: ${options.rerank}`);
99
+ if (options.rerank) {
100
+ console.log(` Rerank Tier: ${options.rerankTier}`);
101
+ console.log(` Rerank Depth: ${options.rerankDepth}`);
102
+ }
103
+ console.log(` Multi-Query: ${options.multiQuery}`);
104
+ if (options.multiQuery) {
105
+ console.log(` Multi-Query Variations: ${options.multiQueryVariations}`);
106
+ }
107
+ console.log(` Abstention Detection: ${options.abstention}`);
108
+ if (options.abstention) {
109
+ console.log(` Abstention Threshold: ${options.abstentionThreshold}`);
110
+ console.log(` Abstention Hedging (Layer 3): ${options.abstentionHedging}`);
111
+ console.log(` Abstention NLI (Layer 2): ${options.abstentionNli}`);
112
+ if (options.abstentionNli) {
113
+ console.log(` Abstention NLI Threshold: ${options.abstentionNliThreshold}`);
114
+ }
115
+ }
116
+ console.log(` Session-Aware Retrieval: ${options.sessionAware}`);
117
+ if (options.sessionAware) {
118
+ console.log(` Top Sessions (Stage 1): ${options.topSessions}`);
119
+ console.log(` Turns Per Session (Stage 2): ${options.turnsPerSession}`);
120
+ }
121
+ console.log(` Temporal Query Parsing: ${options.temporalAware}`);
122
+ if (options.temporalAware) {
123
+ console.log(` Temporal Confidence Threshold: ${options.temporalConfidenceThreshold}`);
124
+ }
125
+ console.log(` Embedding Model: ${options.embeddingModel}`);
126
+ }
127
+ if (options.limit) {
128
+ console.log(` Limit: ${options.limit} instances`);
129
+ }
130
+ console.log("");
131
+
132
+ // Initialize providers
133
+ const embeddings = createEmbeddingProvider(options);
134
+ const llm = createLLMProvider(options);
135
+ const customRetriever = createCustomRetriever(options);
136
+
137
+ const pipeline = new BenchmarkPipeline(embeddings, llm, {
138
+ loader: {
139
+ datasetPath: options.dataset,
140
+ variant: options.variant as DatasetVariant,
141
+ limit: options.limit,
142
+ },
143
+ retriever: {
144
+ method: options.retriever as "dense" | "bm25" | "hybrid",
145
+ topK: options.topK,
146
+ timeAwareExpansion: options.timeAware,
147
+ },
148
+ reader: {
149
+ chainOfNote: options.chainOfNote,
150
+ // Enable abstention detection in Reader if --abstention-hedging or --abstention-nli
151
+ abstentionDetection:
152
+ options.abstention && (options.abstentionHedging || options.abstentionNli),
153
+ abstentionNLI: options.abstentionNli,
154
+ abstentionNLIThreshold: options.abstentionNliThreshold,
155
+ },
156
+ // Milestone 2 optimizations
157
+ keyExpansion: {
158
+ enabled: options.keyExpansion,
159
+ types: ["keyphrase", "userfact"],
160
+ },
161
+ temporal: {
162
+ enabled: options.temporalAnalysis,
163
+ },
164
+ // Custom retriever for Engram full pipeline
165
+ customRetriever,
166
+ onProgress: (progress: PipelineProgress) => {
167
+ if (options.verbose) {
168
+ console.log(
169
+ `[${progress.stage}] ${progress.current}/${progress.total} - ${progress.message}`,
170
+ );
171
+ } else {
172
+ // Simple progress bar
173
+ const pct = Math.round((progress.current / progress.total) * 100);
174
+ process.stdout.write(`\r${progress.stage}: ${pct}%`);
175
+ }
176
+ },
177
+ // Debug retrieval callback
178
+ onRetrievalDebug: options.debugRetrieval ? logRetrievalDebug : undefined,
179
+ });
180
+
181
+ try {
182
+ const result = await pipeline.run();
183
+
184
+ console.log("\n");
185
+ console.log("=".repeat(60));
186
+ console.log(result.report);
187
+ console.log("=".repeat(60));
188
+
189
+ // Save results if output path specified
190
+ if (options.output) {
191
+ await writeFile(options.output, result.jsonl, "utf-8");
192
+ console.log(`\n✅ Results saved to: ${options.output}`);
193
+ }
194
+
195
+ // Save detailed report
196
+ const reportPath = options.output
197
+ ? options.output.replace(".jsonl", "-report.md")
198
+ : "longmemeval-report.md";
199
+ await writeFile(reportPath, result.report, "utf-8");
200
+ console.log(`📊 Report saved to: ${reportPath}`);
201
+
202
+ // ONNX runtime has threading issues that cause ugly errors at exit
203
+ // Suppress stderr briefly and force exit
204
+ const originalStderr = process.stderr.write.bind(process.stderr);
205
+ process.stderr.write = () => true; // Suppress ONNX mutex errors
206
+ setTimeout(() => {
207
+ process.stderr.write = originalStderr;
208
+ process.exit(0);
209
+ }, 100);
210
+ } catch (error) {
211
+ console.error("\n❌ Benchmark failed:", error);
212
+ process.exit(1);
213
+ }
214
+ }
215
+
216
+ /**
217
+ * Create embedding provider based on options
218
+ */
219
+ function createEmbeddingProvider(options: RunOptions): EmbeddingProvider {
220
+ switch (options.embeddings) {
221
+ case "engram":
222
+ // Engram uses custom retriever, but we still need a stub for pipeline init
223
+ console.log("🚀 Using Engram full pipeline (search-core)");
224
+ console.log(" - Dense: E5-small (384d)");
225
+ if (options.hybridSearch) {
226
+ console.log(" - Sparse: SPLADE");
227
+ console.log(" - Fusion: RRF");
228
+ }
229
+ if (options.rerank) {
230
+ console.log(` - Reranker: ${options.rerankTier} tier`);
231
+ }
232
+ return new StubEmbeddingProvider(); // Pipeline uses customRetriever instead
233
+
234
+ case "qdrant":
235
+ case "e5":
236
+ console.log("📦 Using Qdrant/E5 embeddings (HuggingFace transformers)");
237
+ return new QdrantEmbeddingProvider({
238
+ url: options.qdrantUrl ?? "http://localhost:6333",
239
+ });
240
+ default:
241
+ console.log("⚠️ Using stub embeddings (random vectors)");
242
+ return new StubEmbeddingProvider();
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Create custom retriever for Engram full pipeline
248
+ */
249
+ function createCustomRetriever(options: RunOptions): CustomRetriever | undefined {
250
+ if (options.embeddings !== "engram") {
251
+ return undefined;
252
+ }
253
+
254
+ return new EngramRetriever({
255
+ qdrantUrl: options.qdrantUrl ?? "http://localhost:6333",
256
+ hybridSearch: options.hybridSearch,
257
+ learnedFusion: options.learnedFusion,
258
+ fusionModel: options.fusionModel,
259
+ rerank: options.rerank,
260
+ rerankTier: options.rerankTier as "fast" | "accurate" | "code" | "colbert",
261
+ rerankDepth: options.rerankDepth,
262
+ topK: options.topK,
263
+ multiQuery: options.multiQuery,
264
+ multiQueryVariations: options.multiQueryVariations,
265
+ abstention: options.abstention,
266
+ abstentionThreshold: options.abstentionThreshold,
267
+ sessionAware: options.sessionAware,
268
+ topSessions: options.topSessions,
269
+ turnsPerSession: options.turnsPerSession,
270
+ temporalAware: options.temporalAware,
271
+ temporalConfidenceThreshold: options.temporalConfidenceThreshold,
272
+ embeddingModel: options.embeddingModel as
273
+ | "e5-small"
274
+ | "e5-base"
275
+ | "e5-large"
276
+ | "gte-base"
277
+ | "gte-large"
278
+ | "bge-small"
279
+ | "bge-base"
280
+ | "bge-large",
281
+ });
282
+ }
283
+
284
+ /**
285
+ * Create LLM provider based on options
286
+ */
287
+ function createLLMProvider(options: RunOptions): LLMProvider {
288
+ switch (options.llm) {
289
+ case "anthropic":
290
+ case "claude":
291
+ if (!process.env.ANTHROPIC_API_KEY) {
292
+ console.error("❌ ANTHROPIC_API_KEY environment variable required for Claude");
293
+ process.exit(1);
294
+ }
295
+ console.log("🤖 Using Anthropic Claude for answer generation");
296
+ return new AnthropicProvider();
297
+
298
+ case "openai":
299
+ case "gpt":
300
+ if (!process.env.OPENAI_API_KEY) {
301
+ console.error("❌ OPENAI_API_KEY environment variable required for OpenAI");
302
+ process.exit(1);
303
+ }
304
+ console.log("🤖 Using OpenAI GPT for answer generation");
305
+ return new OpenAICompatibleProvider();
306
+
307
+ case "ollama":
308
+ if (!options.ollamaModel) {
309
+ console.error("❌ --ollama-model is required when using Ollama");
310
+ process.exit(1);
311
+ }
312
+ console.log(`🤖 Using Ollama (${options.ollamaModel}) for answer generation`);
313
+ return new OllamaProvider({
314
+ baseUrl: options.ollamaUrl ?? "http://localhost:11434",
315
+ model: options.ollamaModel,
316
+ });
317
+
318
+ case "gemini":
319
+ case "google":
320
+ if (!process.env.GOOGLE_GENERATIVE_AI_API_KEY) {
321
+ console.error("❌ GOOGLE_GENERATIVE_AI_API_KEY environment variable required for Gemini");
322
+ process.exit(1);
323
+ }
324
+ console.log(
325
+ `🤖 Using Google Gemini (${options.geminiModel ?? "gemini-3-flash-preview"}) for answer generation`,
326
+ );
327
+ return new GeminiProvider({
328
+ model: options.geminiModel ?? "gemini-3-flash-preview",
329
+ });
330
+ default:
331
+ console.log("⚠️ Using stub LLM (no real generation)");
332
+ return new StubLLMProvider();
333
+ }
334
+ }
335
+
336
+ /**
337
+ * Log retrieval debug info to console
338
+ */
339
+ function logRetrievalDebug(debug: RetrievalDebugInfo): void {
340
+ const truncate = (s: string, len: number) => (s.length > len ? `${s.slice(0, len)}...` : s);
341
+
342
+ console.log(`\n${"─".repeat(80)}`);
343
+ console.log(`📋 RETRIEVAL DEBUG: ${debug.questionId}`);
344
+ console.log("─".repeat(80));
345
+
346
+ console.log(`\n❓ Question: ${debug.question}`);
347
+ console.log(`✅ Expected Answer: ${debug.expectedAnswer}`);
348
+ console.log(`📊 Recall: ${(debug.recall * 100).toFixed(1)}%`);
349
+
350
+ console.log(`\n🎯 EXPECTED EVIDENCE (${debug.evidenceDocs.length} docs):`);
351
+ for (const doc of debug.evidenceDocs) {
352
+ const found = debug.retrievedDocs.some((r) => r.id === doc.id);
353
+ const status = found ? "✅" : "❌";
354
+ console.log(` ${status} [${doc.sessionId}] ${truncate(doc.content, 100)}`);
355
+ }
356
+
357
+ console.log(`\n🔍 RETRIEVED (${debug.retrievedDocs.length} docs):`);
358
+ for (let i = 0; i < debug.retrievedDocs.length; i++) {
359
+ const doc = debug.retrievedDocs[i];
360
+ const marker = doc.isEvidence ? "🎯" : " ";
361
+ console.log(
362
+ ` ${i + 1}. ${marker} [score=${doc.score.toFixed(3)}] ${truncate(doc.content, 80)}`,
363
+ );
364
+ }
365
+
366
+ console.log(`${"─".repeat(80)}\n`);
367
+ }
packages/benchmark/src/cli/commands/train-fusion.ts ADDED
@@ -0,0 +1,495 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { writeFile } from "node:fs/promises";
2
+ import { QueryFeatureExtractor } from "@engram/search";
3
+ import { type LoaderConfig, loadDataset } from "../../longmemeval/loader.js";
4
+ import { type EngramDocument, mapInstance } from "../../longmemeval/mapper.js";
5
+ import { computeRetrievalMetrics, type RetrievalResult } from "../../longmemeval/retriever.js";
6
+ import type { DatasetVariant, ParsedInstance } from "../../longmemeval/types.js";
7
+
8
+ /**
9
+ * Training sample for fusion weight MLP.
10
+ */
11
+ interface FusionTrainingSample {
12
+ /** Unique identifier for this sample */
13
+ instanceId: string;
14
+ /** The question text */
15
+ question: string;
16
+ /** Normalized feature vector for model input */
17
+ features: number[];
18
+ /** Feature names for debugging */
19
+ featureNames: string[];
20
+ /** Optimal fusion weights found via grid search */
21
+ optimalWeights: {
22
+ dense: number;
23
+ sparse: number;
24
+ rerank: number;
25
+ };
26
+ /** Best recall achieved with optimal weights */
27
+ bestRecall: number;
28
+ /** Grid search results for analysis */
29
+ gridSearchResults: Array<{
30
+ weights: { dense: number; sparse: number; rerank: number };
31
+ recall: number;
32
+ }>;
33
+ }
34
+
35
+ /**
36
+ * Configuration for training data generation.
37
+ */
38
+ interface TrainFusionOptions {
39
+ dataset: string;
40
+ variant: string;
41
+ output: string;
42
+ limit?: number;
43
+ verbose: boolean;
44
+ qdrantUrl: string;
45
+ // Grid search parameters
46
+ denseSteps: number[];
47
+ sparseSteps: number[];
48
+ }
49
+
50
+ const DEFAULT_DENSE_STEPS = [0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8];
51
+ const DEFAULT_SPARSE_STEPS = [0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4];
52
+
53
+ /**
54
+ * Generate training data for fusion weight MLP via grid search.
55
+ *
56
+ * For each LongMemEval instance:
57
+ * 1. Extract query features
58
+ * 2. Run retrieval with each weight combination
59
+ * 3. Find weights that maximize recall
60
+ * 4. Save (features, optimal_weights) pairs
61
+ */
62
+ export async function trainFusionCommand(options: TrainFusionOptions): Promise<void> {
63
+ console.log("🔬 Generating Fusion Training Data");
64
+ console.log("");
65
+ console.log("Configuration:");
66
+ console.log(` Dataset: ${options.dataset}`);
67
+ console.log(` Variant: ${options.variant}`);
68
+ console.log(` Output: ${options.output}`);
69
+ console.log(` Dense steps: ${options.denseSteps.join(", ")}`);
70
+ console.log(` Sparse steps: ${options.sparseSteps.join(", ")}`);
71
+ if (options.limit) {
72
+ console.log(` Limit: ${options.limit} instances`);
73
+ }
74
+ console.log("");
75
+
76
+ // Initialize components
77
+ const featureExtractor = new QueryFeatureExtractor();
78
+ const weightedRetriever = await createWeightedRetriever(options.qdrantUrl);
79
+
80
+ // Load dataset
81
+ console.log("📂 Loading dataset...");
82
+ const loaderConfig: LoaderConfig = {
83
+ datasetPath: options.dataset,
84
+ variant: options.variant as DatasetVariant,
85
+ limit: options.limit,
86
+ };
87
+ const loadResult = await loadDataset(loaderConfig);
88
+ console.log(` Loaded ${loadResult.instances.length} instances`);
89
+
90
+ // Generate training samples
91
+ const samples: FusionTrainingSample[] = [];
92
+ const totalGridSize = options.denseSteps.length * options.sparseSteps.length;
93
+ console.log(` Grid size: ${totalGridSize} combinations per instance`);
94
+ console.log("");
95
+
96
+ for (let i = 0; i < loadResult.instances.length; i++) {
97
+ const instance = loadResult.instances[i];
98
+ const progress = `[${i + 1}/${loadResult.instances.length}]`;
99
+
100
+ if (options.verbose) {
101
+ console.log(`${progress} Processing: ${instance.question.substring(0, 50)}...`);
102
+ } else {
103
+ process.stdout.write(`\r${progress} Generating training data...`);
104
+ }
105
+
106
+ try {
107
+ const sample = await generateTrainingSample(
108
+ instance,
109
+ featureExtractor,
110
+ weightedRetriever,
111
+ options.denseSteps,
112
+ options.sparseSteps,
113
+ );
114
+ samples.push(sample);
115
+
116
+ if (options.verbose) {
117
+ console.log(
118
+ ` → Best weights: d=${sample.optimalWeights.dense.toFixed(2)}, ` +
119
+ `s=${sample.optimalWeights.sparse.toFixed(2)}, ` +
120
+ `r=${sample.optimalWeights.rerank.toFixed(2)} ` +
121
+ `(recall=${sample.bestRecall.toFixed(3)})`,
122
+ );
123
+ }
124
+ } catch (error) {
125
+ console.warn(`\n⚠️ Failed to process instance ${instance.questionId}:`, error);
126
+ }
127
+ }
128
+
129
+ console.log("\n");
130
+ console.log(`✅ Generated ${samples.length} training samples`);
131
+
132
+ // Analyze weight distribution
133
+ analyzeWeightDistribution(samples);
134
+
135
+ // Save to JSONL
136
+ const jsonlContent = samples.map((s) => JSON.stringify(s)).join("\n");
137
+ await writeFile(options.output, jsonlContent, "utf-8");
138
+ console.log(`\n📁 Saved training data to: ${options.output}`);
139
+
140
+ // Cleanup
141
+ await weightedRetriever.cleanup();
142
+ }
143
+
144
+ /**
145
+ * Generate a training sample for a single instance.
146
+ */
147
+ async function generateTrainingSample(
148
+ instance: ParsedInstance,
149
+ featureExtractor: QueryFeatureExtractor,
150
+ retriever: WeightedRetriever,
151
+ denseSteps: number[],
152
+ sparseSteps: number[],
153
+ ): Promise<FusionTrainingSample> {
154
+ // Map instance to documents
155
+ const mapped = mapInstance(instance);
156
+
157
+ // Index documents
158
+ await retriever.index(mapped.documents);
159
+
160
+ // Extract query features
161
+ const features = featureExtractor.extract(instance.question);
162
+ const normalized = featureExtractor.toNormalizedVector(features);
163
+
164
+ // Get evidence document IDs for recall calculation
165
+ const evidenceDocIds = mapped.evidenceDocIds;
166
+
167
+ // Grid search for optimal weights
168
+ const gridResults: Array<{
169
+ weights: { dense: number; sparse: number; rerank: number };
170
+ recall: number;
171
+ }> = [];
172
+
173
+ let bestRecall = 0;
174
+ let bestWeights = { dense: 0.4, sparse: 0.3, rerank: 0.3 };
175
+
176
+ for (const dense of denseSteps) {
177
+ for (const sparse of sparseSteps) {
178
+ const rerank = Math.max(0, 1 - dense - sparse);
179
+ if (rerank < 0 || dense + sparse > 1) continue;
180
+
181
+ const weights = { dense, sparse, rerank };
182
+
183
+ // Retrieve with weighted fusion
184
+ const result = await retriever.search(instance.question, weights, 10);
185
+
186
+ // Calculate recall
187
+ const metrics = computeRetrievalMetrics(result, evidenceDocIds);
188
+ const recall = metrics.recall;
189
+
190
+ gridResults.push({ weights, recall });
191
+
192
+ if (recall > bestRecall) {
193
+ bestRecall = recall;
194
+ bestWeights = weights;
195
+ }
196
+ }
197
+ }
198
+
199
+ // Clear index for next instance
200
+ retriever.clear();
201
+
202
+ return {
203
+ instanceId: instance.questionId,
204
+ question: instance.question,
205
+ features: normalized.vector,
206
+ featureNames: normalized.names,
207
+ optimalWeights: bestWeights,
208
+ bestRecall,
209
+ gridSearchResults: gridResults,
210
+ };
211
+ }
212
+
213
+ /**
214
+ * Analyze and report weight distribution in training data.
215
+ */
216
+ function analyzeWeightDistribution(samples: FusionTrainingSample[]): void {
217
+ console.log("\n📊 Weight Distribution Analysis:");
218
+
219
+ // Aggregate optimal weights
220
+ const denseWeights = samples.map((s) => s.optimalWeights.dense);
221
+ const sparseWeights = samples.map((s) => s.optimalWeights.sparse);
222
+ const rerankWeights = samples.map((s) => s.optimalWeights.rerank);
223
+
224
+ const mean = (arr: number[]) => arr.reduce((a, b) => a + b, 0) / arr.length;
225
+ const std = (arr: number[]) => {
226
+ const m = mean(arr);
227
+ return Math.sqrt(arr.reduce((sum, x) => sum + (x - m) ** 2, 0) / arr.length);
228
+ };
229
+
230
+ console.log(
231
+ ` Dense: mean=${mean(denseWeights).toFixed(3)}, std=${std(denseWeights).toFixed(3)}`,
232
+ );
233
+ console.log(
234
+ ` Sparse: mean=${mean(sparseWeights).toFixed(3)}, std=${std(sparseWeights).toFixed(3)}`,
235
+ );
236
+ console.log(
237
+ ` Rerank: mean=${mean(rerankWeights).toFixed(3)}, std=${std(rerankWeights).toFixed(3)}`,
238
+ );
239
+
240
+ // Show question type breakdown
241
+ console.log("\n By Question Type:");
242
+ const byType = new Map<string, FusionTrainingSample[]>();
243
+ for (const sample of samples) {
244
+ // Parse question type from features (index 3 in normalized vector)
245
+ const typeValue = sample.features[3];
246
+ let type = "other";
247
+ if (typeValue < 0.1) type = "factoid";
248
+ else if (typeValue < 0.2) type = "list";
249
+ else if (typeValue < 0.4) type = "comparison";
250
+ else if (typeValue < 0.5) type = "causal";
251
+ else if (typeValue < 0.7) type = "temporal";
252
+ else if (typeValue < 0.8) type = "opinion";
253
+
254
+ if (!byType.has(type)) byType.set(type, []);
255
+ byType.get(type)?.push(sample);
256
+ }
257
+
258
+ for (const [type, typeSamples] of byType) {
259
+ const avgDense = mean(typeSamples.map((s) => s.optimalWeights.dense));
260
+ const avgSparse = mean(typeSamples.map((s) => s.optimalWeights.sparse));
261
+ const avgRerank = mean(typeSamples.map((s) => s.optimalWeights.rerank));
262
+ console.log(
263
+ ` ${type.padEnd(12)}: d=${avgDense.toFixed(2)}, s=${avgSparse.toFixed(2)}, r=${avgRerank.toFixed(2)} (n=${typeSamples.length})`,
264
+ );
265
+ }
266
+ }
267
+
268
+ /**
269
+ * Weighted retriever that allows configurable fusion weights.
270
+ */
271
+ interface WeightedRetriever {
272
+ index(documents: EngramDocument[]): Promise<void>;
273
+ search(
274
+ query: string,
275
+ weights: { dense: number; sparse: number; rerank: number },
276
+ topK: number,
277
+ ): Promise<RetrievalResult>;
278
+ clear(): void;
279
+ cleanup(): Promise<void>;
280
+ }
281
+
282
+ /**
283
+ * Create a weighted retriever for grid search.
284
+ * This uses the Engram pipeline with configurable fusion weights.
285
+ */
286
+ async function createWeightedRetriever(qdrantUrl: string): Promise<WeightedRetriever> {
287
+ // Dynamic import to avoid circular dependencies
288
+ const searchCore = await import("@engram/search");
289
+ const { QdrantClient } = await import("@qdrant/js-client-rest");
290
+
291
+ const collectionName = "fusion_training";
292
+ const client = new QdrantClient({ url: qdrantUrl });
293
+ const textEmbedder = new searchCore.TextEmbedder();
294
+ const spladeEmbedder = new searchCore.SpladeEmbedder();
295
+ const reranker = searchCore.BatchedReranker.forTier("fast");
296
+
297
+ let indexed = false;
298
+ let documents: EngramDocument[] = [];
299
+
300
+ return {
301
+ async index(docs: EngramDocument[]): Promise<void> {
302
+ documents = docs;
303
+
304
+ // Ensure collection exists
305
+ try {
306
+ await client.deleteCollection(collectionName);
307
+ } catch {
308
+ // Ignore if doesn't exist
309
+ }
310
+
311
+ await client.createCollection(collectionName, {
312
+ vectors: {
313
+ dense: { size: 384, distance: "Cosine" },
314
+ },
315
+ sparse_vectors: {
316
+ sparse: { index: { on_disk: false } },
317
+ },
318
+ });
319
+
320
+ // Generate embeddings
321
+ const texts = docs.map((d) => d.content);
322
+ const denseEmbeddings = await Promise.all(texts.map((t) => textEmbedder.embed(t)));
323
+ const sparseEmbeddings = await Promise.all(texts.map((t) => spladeEmbedder.embed(t)));
324
+
325
+ // Index points
326
+ const points = docs.map((doc, i) => ({
327
+ id: hashId(doc.id),
328
+ vector: {
329
+ dense: Array.from(denseEmbeddings[i]),
330
+ sparse: sparseEmbeddings[i],
331
+ },
332
+ payload: {
333
+ doc_id: doc.id,
334
+ content: doc.content,
335
+ valid_time: doc.validTime.toISOString(),
336
+ has_answer: doc.metadata.hasAnswer,
337
+ },
338
+ }));
339
+
340
+ await client.upsert(collectionName, { wait: true, points });
341
+ indexed = true;
342
+ },
343
+
344
+ async search(
345
+ query: string,
346
+ weights: { dense: number; sparse: number; rerank: number },
347
+ topK: number,
348
+ ): Promise<RetrievalResult> {
349
+ if (!indexed) {
350
+ return { documents: [], scores: [], retrievedIds: [] };
351
+ }
352
+
353
+ // Get dense and sparse query embeddings
354
+ const denseQuery = await textEmbedder.embedQuery(query);
355
+ const sparseQuery = await spladeEmbedder.embedQuery(query);
356
+
357
+ // Fetch candidates for each method
358
+ const fetchLimit = 30;
359
+
360
+ // Dense search
361
+ const denseResults = await client.search(collectionName, {
362
+ vector: { name: "dense", vector: Array.from(denseQuery) },
363
+ limit: fetchLimit,
364
+ with_payload: true,
365
+ });
366
+
367
+ // Sparse search using query API
368
+ const sparseResults = await client.query(collectionName, {
369
+ query: {
370
+ indices: sparseQuery.indices,
371
+ values: sparseQuery.values,
372
+ },
373
+ using: "sparse",
374
+ limit: fetchLimit,
375
+ with_payload: true,
376
+ });
377
+
378
+ // Build score map for weighted fusion
379
+ const scoreMap = new Map<
380
+ string,
381
+ {
382
+ docId: string;
383
+ content: string;
384
+ denseScore: number;
385
+ sparseScore: number;
386
+ rerankScore: number;
387
+ }
388
+ >();
389
+
390
+ // Normalize dense scores to 0-1 range
391
+ const maxDense = Math.max(...denseResults.map((r) => r.score), 0.001);
392
+ for (const r of denseResults) {
393
+ const payload = r.payload as Record<string, unknown>;
394
+ const docId = payload.doc_id as string;
395
+ scoreMap.set(docId, {
396
+ docId,
397
+ content: payload.content as string,
398
+ denseScore: r.score / maxDense,
399
+ sparseScore: 0,
400
+ rerankScore: 0,
401
+ });
402
+ }
403
+
404
+ // Add sparse scores
405
+ const sparsePoints = sparseResults.points || [];
406
+ const maxSparse = Math.max(...sparsePoints.map((r) => r.score), 0.001);
407
+ for (const r of sparsePoints) {
408
+ const payload = r.payload as Record<string, unknown>;
409
+ const docId = payload.doc_id as string;
410
+ const existing = scoreMap.get(docId);
411
+ if (existing) {
412
+ existing.sparseScore = r.score / maxSparse;
413
+ } else {
414
+ scoreMap.set(docId, {
415
+ docId,
416
+ content: payload.content as string,
417
+ denseScore: 0,
418
+ sparseScore: r.score / maxSparse,
419
+ rerankScore: 0,
420
+ });
421
+ }
422
+ }
423
+
424
+ // Get rerank scores for top candidates
425
+ const candidates = Array.from(scoreMap.values()).map((s) => ({
426
+ id: s.docId,
427
+ content: s.content,
428
+ score: s.denseScore * weights.dense + s.sparseScore * weights.sparse,
429
+ }));
430
+
431
+ if (weights.rerank > 0 && candidates.length > 0) {
432
+ const reranked = await reranker.rerank(query, candidates, candidates.length);
433
+ const maxRerank = Math.max(...reranked.map((r: { score: number }) => r.score), 0.001);
434
+ for (const r of reranked) {
435
+ const existing = scoreMap.get(String(r.id));
436
+ if (existing) {
437
+ existing.rerankScore = r.score / maxRerank;
438
+ }
439
+ }
440
+ }
441
+
442
+ // Calculate final weighted scores
443
+ const results = Array.from(scoreMap.values())
444
+ .map((s) => ({
445
+ docId: s.docId,
446
+ content: s.content,
447
+ score:
448
+ s.denseScore * weights.dense +
449
+ s.sparseScore * weights.sparse +
450
+ s.rerankScore * weights.rerank,
451
+ }))
452
+ .sort((a, b) => b.score - a.score)
453
+ .slice(0, topK);
454
+
455
+ // Convert to RetrievalResult
456
+ const resultDocs = results
457
+ .map((r) => documents.find((d) => d.id === r.docId))
458
+ .filter((d): d is EngramDocument => d !== undefined);
459
+
460
+ return {
461
+ documents: resultDocs,
462
+ scores: results.map((r) => r.score),
463
+ retrievedIds: results.map((r) => r.docId),
464
+ };
465
+ },
466
+
467
+ clear(): void {
468
+ indexed = false;
469
+ documents = [];
470
+ },
471
+
472
+ async cleanup(): Promise<void> {
473
+ try {
474
+ await client.deleteCollection(collectionName);
475
+ } catch {
476
+ // Ignore
477
+ }
478
+ },
479
+ };
480
+ }
481
+
482
+ /**
483
+ * Generate numeric hash for Qdrant point ID.
484
+ */
485
+ function hashId(id: string): number {
486
+ let hash = 0;
487
+ for (let i = 0; i < id.length; i++) {
488
+ hash = (hash << 5) - hash + id.charCodeAt(i);
489
+ hash = hash >>> 0;
490
+ }
491
+ return hash;
492
+ }
493
+
494
+ export { DEFAULT_DENSE_STEPS, DEFAULT_SPARSE_STEPS };
495
+ export type { TrainFusionOptions, FusionTrainingSample };
packages/benchmark/src/cli/commands/validate.ts ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { validateDataset } from "../../longmemeval/loader.js";
2
+
3
+ export async function validateCommand(path: string): Promise<void> {
4
+ console.log(`🔍 Validating dataset: ${path}`);
5
+ console.log("");
6
+
7
+ const result = await validateDataset(path);
8
+
9
+ if (result.valid) {
10
+ console.log("✅ Dataset is valid");
11
+ console.log("");
12
+ console.log("Statistics:");
13
+ console.log(` Total instances: ${result.stats?.totalInstances}`);
14
+ console.log(` Total sessions: ${result.stats?.totalSessions}`);
15
+ console.log(` Total turns: ${result.stats?.totalTurns}`);
16
+ console.log(` Abstention questions: ${result.stats?.abstentionCount}`);
17
+ console.log("");
18
+ console.log("By Memory Ability:");
19
+ for (const [ability, count] of Object.entries(result.stats?.byAbility ?? {})) {
20
+ console.log(` ${ability}: ${count}`);
21
+ }
22
+ } else {
23
+ console.error("❌ Dataset validation failed");
24
+ console.error("");
25
+ console.error(`Error: ${result.error}`);
26
+ process.exit(1);
27
+ }
28
+ }
packages/benchmark/src/cli/index.ts ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+ import { Command } from "commander";
3
+ import { evaluateCommand } from "./commands/evaluate.js";
4
+ import { ingestCommand } from "./commands/ingest.js";
5
+ import { runCommand } from "./commands/run.js";
6
+ import {
7
+ DEFAULT_DENSE_STEPS,
8
+ DEFAULT_SPARSE_STEPS,
9
+ trainFusionCommand,
10
+ } from "./commands/train-fusion.js";
11
+ import { validateCommand } from "./commands/validate.js";
12
+
13
+ const program = new Command();
14
+
15
+ program
16
+ .name("engram-benchmark")
17
+ .description("Benchmark Engram memory system against industry benchmarks")
18
+ .version("0.0.1");
19
+
20
+ // Run benchmark command
21
+ program
22
+ .command("run")
23
+ .description("Run a benchmark against Engram")
24
+ .argument("<benchmark>", "Benchmark to run (longmemeval)")
25
+ .requiredOption("-d, --dataset <path>", "Path to dataset file or directory")
26
+ .option("-v, --variant <variant>", "Dataset variant (s, m, oracle)", "s")
27
+ .option("-o, --output <path>", "Output file for results (JSONL)")
28
+ .option("-l, --limit <n>", "Limit number of instances", Number.parseInt)
29
+ .option("-k, --top-k <n>", "Number of documents to retrieve", Number.parseInt, 10)
30
+ .option("--retriever <method>", "Retrieval method (dense, bm25, hybrid)", "dense")
31
+ .option("--chain-of-note", "Enable Chain-of-Note reading", false)
32
+ .option("--time-aware", "Enable time-aware query expansion", false)
33
+ .option("--verbose", "Show detailed progress", false)
34
+ // Provider options
35
+ .option("--embeddings <provider>", "Embedding provider (stub, qdrant, e5, engram)", "stub")
36
+ .option("--llm <provider>", "LLM provider (stub, anthropic, openai, ollama, gemini)", "stub")
37
+ .option("--qdrant-url <url>", "Qdrant server URL", "http://localhost:6333")
38
+ .option("--ollama-url <url>", "Ollama server URL", "http://localhost:11434")
39
+ .option("--ollama-model <model>", "Ollama model name")
40
+ .option("--gemini-model <model>", "Gemini model name", "gemini-3-flash-preview")
41
+ // Milestone 2 optimizations
42
+ .option("--key-expansion", "Enable key expansion with fact extraction (+9% recall)", false)
43
+ .option("--temporal-analysis", "Enable improved temporal query analysis (+7-11% on TR)", false)
44
+ // Engram full pipeline options (when --embeddings engram)
45
+ .option("--rerank", "Enable reranking (requires --embeddings engram)", true)
46
+ .option("--rerank-tier <tier>", "Reranker tier: fast, accurate, code, colbert", "fast")
47
+ .option("--rerank-depth <n>", "Candidates to fetch before reranking", Number.parseInt, 30)
48
+ .option("--hybrid-search", "Enable hybrid search with RRF (requires --embeddings engram)", true)
49
+ // Learned fusion options
50
+ .option("--learned-fusion", "Use learned fusion weights instead of fixed RRF", false)
51
+ .option("--fusion-model <path>", "Path to fusion MLP ONNX model", "models/fusion_mlp.onnx")
52
+ // Multi-query retrieval options
53
+ .option("--multi-query", "Enable multi-query expansion with RRF fusion", false)
54
+ .option(
55
+ "--multi-query-variations <n>",
56
+ "Number of query variations to generate",
57
+ Number.parseInt,
58
+ 3,
59
+ )
60
+ // Abstention detection options
61
+ .option("--abstention", "Enable retrieval confidence abstention detection (Layer 1)", false)
62
+ .option(
63
+ "--abstention-threshold <n>",
64
+ "Minimum retrieval score to proceed (0-1)",
65
+ Number.parseFloat,
66
+ 0.3,
67
+ )
68
+ .option(
69
+ "--abstention-hedging",
70
+ "Enable hedging pattern detection (Layer 3) - requires --abstention",
71
+ false,
72
+ )
73
+ .option(
74
+ "--abstention-nli",
75
+ "Enable NLI answer grounding check (Layer 2) - requires --abstention",
76
+ false,
77
+ )
78
+ .option(
79
+ "--abstention-nli-threshold <n>",
80
+ "NLI entailment threshold for abstention (0-1)",
81
+ Number.parseFloat,
82
+ 0.7,
83
+ )
84
+ // Session-aware retrieval options
85
+ .option("--session-aware", "Enable session-aware hierarchical retrieval", false)
86
+ .option("--top-sessions <n>", "Number of sessions to retrieve in stage 1", Number.parseInt, 5)
87
+ .option("--turns-per-session <n>", "Number of turns per session in stage 2", Number.parseInt, 3)
88
+ // Temporal query parsing options
89
+ .option("--temporal-aware", "Enable temporal query parsing with chrono-node", false)
90
+ .option(
91
+ "--temporal-confidence-threshold <n>",
92
+ "Minimum confidence to apply temporal filter (0-1)",
93
+ Number.parseFloat,
94
+ 0.5,
95
+ )
96
+ // Embedding model options
97
+ .option(
98
+ "--embedding-model <model>",
99
+ "Embedding model: e5-small, e5-base, e5-large, gte-base, gte-large, bge-small, bge-base, bge-large",
100
+ "e5-small",
101
+ )
102
+ // Debug options
103
+ .option("--debug-retrieval", "Log retrieved vs expected documents for each query", false)
104
+ .action(runCommand);
105
+
106
+ // Evaluate results command
107
+ program
108
+ .command("evaluate")
109
+ .description("Evaluate benchmark results against ground truth")
110
+ .requiredOption("-h, --hypothesis <path>", "Path to hypothesis JSONL file")
111
+ .requiredOption("-g, --ground-truth <path>", "Path to ground truth dataset")
112
+ .option("-o, --output <path>", "Output file for metrics (JSON)")
113
+ .option("--llm-eval", "Use LLM-based evaluation (more accurate)", false)
114
+ .action(evaluateCommand);
115
+
116
+ // Validate dataset command
117
+ program
118
+ .command("validate")
119
+ .description("Validate a benchmark dataset file")
120
+ .argument("<path>", "Path to dataset file")
121
+ .action(validateCommand);
122
+
123
+ // Ingest dataset into FalkorDB + Qdrant
124
+ program
125
+ .command("ingest")
126
+ .description("Ingest dataset into FalkorDB (graph) and Qdrant (vectors)")
127
+ .requiredOption("-d, --dataset <path>", "Path to dataset file")
128
+ .option("--falkor-url <url>", "FalkorDB (Redis) URL", "redis://localhost:6379")
129
+ .option("--qdrant-url <url>", "Qdrant server URL", "http://localhost:6333")
130
+ .option("--embedding-model <model>", "Embedding model: e5-small, e5-base, e5-large", "e5-large")
131
+ .option("--clear", "Clear existing data before ingesting", false)
132
+ .option("--verbose", "Show detailed progress", false)
133
+ .action(ingestCommand);
134
+
135
+ // Train fusion weights command
136
+ program
137
+ .command("train-fusion")
138
+ .description("Generate training data for learned fusion weights via grid search")
139
+ .requiredOption("-d, --dataset <path>", "Path to dataset file or directory")
140
+ .requiredOption("-o, --output <path>", "Output file for training data (JSONL)")
141
+ .option("-v, --variant <variant>", "Dataset variant (s, m, oracle)", "s")
142
+ .option("-l, --limit <n>", "Limit number of instances", Number.parseInt)
143
+ .option("--qdrant-url <url>", "Qdrant server URL", "http://localhost:6333")
144
+ .option("--verbose", "Show detailed progress", false)
145
+ .option(
146
+ "--dense-steps <values>",
147
+ "Comma-separated dense weight values to try",
148
+ (v) => v.split(",").map(Number),
149
+ DEFAULT_DENSE_STEPS,
150
+ )
151
+ .option(
152
+ "--sparse-steps <values>",
153
+ "Comma-separated sparse weight values to try",
154
+ (v) => v.split(",").map(Number),
155
+ DEFAULT_SPARSE_STEPS,
156
+ )
157
+ .action(trainFusionCommand);
158
+
159
+ program.parse();
packages/benchmark/src/core/config.ts ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Configuration builder for programmatic benchmark API
3
+ *
4
+ * Provides defaults and environment variable fallbacks for benchmark configuration.
5
+ *
6
+ * @module @engram/benchmark/core
7
+ */
8
+
9
+ import type { RunBenchmarkConfig } from "./types.js";
10
+
11
+ /**
12
+ * Default benchmark configuration values
13
+ */
14
+ export const DEFAULT_BENCHMARK_CONFIG: Omit<RunBenchmarkConfig, "dataset"> = {
15
+ // Dataset
16
+ variant: "oracle",
17
+ limit: undefined,
18
+
19
+ // Retrieval
20
+ topK: 10,
21
+ retriever: "hybrid",
22
+
23
+ // Engram pipeline
24
+ embeddings: "engram",
25
+ hybridSearch: true,
26
+ learnedFusion: false,
27
+ fusionModel: "",
28
+ rerank: true,
29
+ rerankTier: "accurate",
30
+ rerankDepth: 30,
31
+
32
+ // Multi-query
33
+ multiQuery: false,
34
+ multiQueryVariations: 3,
35
+
36
+ // Abstention
37
+ abstention: true,
38
+ abstentionThreshold: 0.3,
39
+
40
+ // Session-aware
41
+ sessionAware: false,
42
+ topSessions: 5,
43
+ turnsPerSession: 3,
44
+
45
+ // Temporal
46
+ temporalAware: false,
47
+ temporalConfidenceThreshold: 0.7,
48
+
49
+ // Model
50
+ embeddingModel: "e5-small",
51
+ llm: "stub",
52
+
53
+ // Ollama
54
+ ollamaUrl: "http://localhost:11434",
55
+ ollamaModel: "llama3.2",
56
+
57
+ // Infrastructure
58
+ qdrantUrl: "http://localhost:6333",
59
+ };
60
+
61
+ /**
62
+ * Build a complete benchmark configuration from partial options
63
+ *
64
+ * Uses defaults and environment variable fallbacks for missing values.
65
+ *
66
+ * @param options - Partial configuration options
67
+ * @returns Complete configuration with all required fields
68
+ *
69
+ * @example
70
+ * ```ts
71
+ * const config = buildBenchmarkConfig({
72
+ * dataset: "./data/longmemeval_oracle.json",
73
+ * limit: 50,
74
+ * llm: "anthropic",
75
+ * });
76
+ * ```
77
+ */
78
+ export function buildBenchmarkConfig(
79
+ options: Partial<RunBenchmarkConfig> & { dataset: string },
80
+ ): RunBenchmarkConfig {
81
+ return {
82
+ // Dataset (required)
83
+ dataset: options.dataset,
84
+ variant: options.variant ?? DEFAULT_BENCHMARK_CONFIG.variant,
85
+ limit: options.limit ?? DEFAULT_BENCHMARK_CONFIG.limit,
86
+
87
+ // Retrieval
88
+ topK: options.topK ?? DEFAULT_BENCHMARK_CONFIG.topK,
89
+ retriever: options.retriever ?? DEFAULT_BENCHMARK_CONFIG.retriever,
90
+
91
+ // Engram pipeline
92
+ embeddings: options.embeddings ?? DEFAULT_BENCHMARK_CONFIG.embeddings,
93
+ hybridSearch: options.hybridSearch ?? DEFAULT_BENCHMARK_CONFIG.hybridSearch,
94
+ learnedFusion: options.learnedFusion ?? DEFAULT_BENCHMARK_CONFIG.learnedFusion,
95
+ fusionModel: options.fusionModel ?? DEFAULT_BENCHMARK_CONFIG.fusionModel,
96
+ rerank: options.rerank ?? DEFAULT_BENCHMARK_CONFIG.rerank,
97
+ rerankTier: options.rerankTier ?? DEFAULT_BENCHMARK_CONFIG.rerankTier,
98
+ rerankDepth: options.rerankDepth ?? DEFAULT_BENCHMARK_CONFIG.rerankDepth,
99
+
100
+ // Multi-query
101
+ multiQuery: options.multiQuery ?? DEFAULT_BENCHMARK_CONFIG.multiQuery,
102
+ multiQueryVariations:
103
+ options.multiQueryVariations ?? DEFAULT_BENCHMARK_CONFIG.multiQueryVariations,
104
+
105
+ // Abstention
106
+ abstention: options.abstention ?? DEFAULT_BENCHMARK_CONFIG.abstention,
107
+ abstentionThreshold:
108
+ options.abstentionThreshold ?? DEFAULT_BENCHMARK_CONFIG.abstentionThreshold,
109
+
110
+ // Session-aware
111
+ sessionAware: options.sessionAware ?? DEFAULT_BENCHMARK_CONFIG.sessionAware,
112
+ topSessions: options.topSessions ?? DEFAULT_BENCHMARK_CONFIG.topSessions,
113
+ turnsPerSession: options.turnsPerSession ?? DEFAULT_BENCHMARK_CONFIG.turnsPerSession,
114
+
115
+ // Temporal
116
+ temporalAware: options.temporalAware ?? DEFAULT_BENCHMARK_CONFIG.temporalAware,
117
+ temporalConfidenceThreshold:
118
+ options.temporalConfidenceThreshold ?? DEFAULT_BENCHMARK_CONFIG.temporalConfidenceThreshold,
119
+
120
+ // Model
121
+ embeddingModel: options.embeddingModel ?? DEFAULT_BENCHMARK_CONFIG.embeddingModel,
122
+ llm: options.llm ?? DEFAULT_BENCHMARK_CONFIG.llm,
123
+
124
+ // Ollama
125
+ ollamaUrl: options.ollamaUrl ?? process.env.OLLAMA_URL ?? DEFAULT_BENCHMARK_CONFIG.ollamaUrl,
126
+ ollamaModel:
127
+ options.ollamaModel ?? process.env.OLLAMA_MODEL ?? DEFAULT_BENCHMARK_CONFIG.ollamaModel,
128
+
129
+ // Infrastructure
130
+ qdrantUrl: options.qdrantUrl ?? process.env.QDRANT_URL ?? DEFAULT_BENCHMARK_CONFIG.qdrantUrl,
131
+ };
132
+ }
packages/benchmark/src/core/index.ts ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Core programmatic API for @engram/benchmark
3
+ *
4
+ * This module provides a function-based API for running benchmarks
5
+ * programmatically, suitable for integration with the tuner and other
6
+ * automated systems.
7
+ *
8
+ * @module @engram/benchmark/core
9
+ */
10
+
11
+ export { buildBenchmarkConfig, DEFAULT_BENCHMARK_CONFIG } from "./config.js";
12
+ // Main API
13
+ export { type BenchmarkCallbacks, runBenchmark } from "./runner.js";
14
+
15
+ // Types
16
+ export type {
17
+ BenchmarkMetrics,
18
+ BenchmarkProgress,
19
+ BenchmarkRunResult,
20
+ EmbeddingModel,
21
+ LLMProviderType,
22
+ RerankerTier,
23
+ RunBenchmarkConfig,
24
+ } from "./types.js";
packages/benchmark/src/core/runner.ts ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Programmatic benchmark runner
3
+ *
4
+ * Provides a function-based API for running benchmarks, suitable for
5
+ * integration with the tuner and other automated systems.
6
+ *
7
+ * @module @engram/benchmark/core
8
+ */
9
+
10
+ import { BenchmarkPipeline, type CustomRetriever } from "../longmemeval/pipeline.js";
11
+ import {
12
+ AnthropicProvider,
13
+ OllamaProvider,
14
+ OpenAICompatibleProvider,
15
+ } from "../longmemeval/providers/anthropic-provider.js";
16
+ import { EngramRetriever } from "../longmemeval/providers/engram-provider.js";
17
+ import { QdrantEmbeddingProvider } from "../longmemeval/providers/qdrant-provider.js";
18
+ import type { LLMProvider } from "../longmemeval/reader.js";
19
+ import { StubEmbeddingProvider, StubLLMProvider } from "../longmemeval/reader.js";
20
+ import type { EmbeddingProvider } from "../longmemeval/retriever.js";
21
+ import type {
22
+ BenchmarkMetrics,
23
+ BenchmarkProgress,
24
+ BenchmarkRunResult,
25
+ RunBenchmarkConfig,
26
+ } from "./types.js";
27
+
28
+ /**
29
+ * Callbacks for monitoring benchmark execution
30
+ */
31
+ export interface BenchmarkCallbacks {
32
+ /** Called when progress is made */
33
+ onProgress?: (progress: BenchmarkProgress) => void;
34
+ }
35
+
36
+ /**
37
+ * Run a benchmark with the given configuration
38
+ *
39
+ * This is the main programmatic entry point for running benchmarks.
40
+ * Use `buildBenchmarkConfig` to create a complete configuration from partial options.
41
+ *
42
+ * @param config - Complete benchmark configuration
43
+ * @param callbacks - Optional callbacks for progress monitoring
44
+ * @returns Benchmark results including metrics, report, and JSONL output
45
+ *
46
+ * @example
47
+ * ```ts
48
+ * import { runBenchmark, buildBenchmarkConfig } from "@engram/benchmark";
49
+ *
50
+ * const config = buildBenchmarkConfig({
51
+ * dataset: "./data/longmemeval_oracle.json",
52
+ * limit: 50,
53
+ * });
54
+ *
55
+ * const result = await runBenchmark(config, {
56
+ * onProgress: (p) => console.log(`${p.stage}: ${p.current}/${p.total}`),
57
+ * });
58
+ *
59
+ * console.log(`Accuracy: ${result.metrics.accuracy}`);
60
+ * ```
61
+ */
62
+ export async function runBenchmark(
63
+ config: RunBenchmarkConfig,
64
+ callbacks?: BenchmarkCallbacks,
65
+ ): Promise<BenchmarkRunResult> {
66
+ const startTime = Date.now();
67
+
68
+ // Initialize providers
69
+ const embeddings = createEmbeddingProvider(config);
70
+ const llm = createLLMProvider(config);
71
+ const customRetriever = createCustomRetriever(config);
72
+
73
+ // Create pipeline
74
+ const pipeline = new BenchmarkPipeline(embeddings, llm, {
75
+ loader: {
76
+ datasetPath: config.dataset,
77
+ variant: config.variant,
78
+ limit: config.limit,
79
+ },
80
+ retriever: {
81
+ method: config.retriever,
82
+ topK: config.topK,
83
+ timeAwareExpansion: false,
84
+ },
85
+ reader: {
86
+ chainOfNote: false,
87
+ abstentionDetection: config.abstention,
88
+ abstentionNLI: false,
89
+ abstentionNLIThreshold: 0.5,
90
+ },
91
+ keyExpansion: {
92
+ enabled: false,
93
+ },
94
+ temporal: {
95
+ enabled: config.temporalAware,
96
+ },
97
+ customRetriever,
98
+ onProgress: callbacks?.onProgress,
99
+ });
100
+
101
+ // Run pipeline
102
+ const pipelineResult = await pipeline.run();
103
+
104
+ const totalDurationMs = Date.now() - startTime;
105
+
106
+ // Map pipeline result to BenchmarkMetrics
107
+ const metrics = mapToMetrics(pipelineResult, totalDurationMs);
108
+
109
+ return {
110
+ metrics,
111
+ report: pipelineResult.report,
112
+ jsonl: pipelineResult.jsonl,
113
+ };
114
+ }
115
+
116
+ /**
117
+ * Map pipeline result to BenchmarkMetrics format
118
+ */
119
+ function mapToMetrics(
120
+ result: Awaited<ReturnType<BenchmarkPipeline["run"]>>,
121
+ totalDurationMs: number,
122
+ ): BenchmarkMetrics {
123
+ const { metrics, latency } = result;
124
+ const retrieval = metrics.retrieval;
125
+ const abstention = metrics.abstention;
126
+
127
+ return {
128
+ // QA accuracy
129
+ accuracy: metrics.overall.accuracy,
130
+
131
+ // Retrieval metrics
132
+ recallAt1: retrieval?.recallAtK?.[1] ?? 0,
133
+ recallAt5: retrieval?.recallAtK?.[5] ?? 0,
134
+ recallAt10: retrieval?.recallAtK?.[10] ?? 0,
135
+ ndcgAt10: retrieval?.ndcgAtK?.[10] ?? 0,
136
+ mrr: retrieval?.mrr ?? 0,
137
+
138
+ // Abstention metrics
139
+ abstentionPrecision: abstention?.precision ?? 0,
140
+ abstentionRecall: abstention?.recall ?? 0,
141
+ abstentionF1: abstention?.f1 ?? 0,
142
+
143
+ // Latency metrics from pipeline
144
+ p50Latency: latency.p50,
145
+ p95Latency: latency.p95,
146
+ p99Latency: latency.p99,
147
+ totalDurationMs: latency.totalDurationMs || totalDurationMs,
148
+ };
149
+ }
150
+
151
+ /**
152
+ * Create embedding provider from config
153
+ */
154
+ function createEmbeddingProvider(config: RunBenchmarkConfig): EmbeddingProvider {
155
+ switch (config.embeddings) {
156
+ case "engram":
157
+ // Engram uses custom retriever, stub is fine for pipeline init
158
+ return new StubEmbeddingProvider();
159
+
160
+ case "qdrant":
161
+ return new QdrantEmbeddingProvider({
162
+ url: config.qdrantUrl ?? "http://localhost:6333",
163
+ });
164
+
165
+ default:
166
+ return new StubEmbeddingProvider();
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Create LLM provider from config
172
+ */
173
+ function createLLMProvider(config: RunBenchmarkConfig): LLMProvider {
174
+ switch (config.llm) {
175
+ case "anthropic":
176
+ if (!process.env.ANTHROPIC_API_KEY) {
177
+ throw new Error("ANTHROPIC_API_KEY environment variable required for Claude");
178
+ }
179
+ return new AnthropicProvider();
180
+
181
+ case "openai":
182
+ if (!process.env.OPENAI_API_KEY) {
183
+ throw new Error("OPENAI_API_KEY environment variable required for OpenAI");
184
+ }
185
+ return new OpenAICompatibleProvider();
186
+
187
+ case "ollama":
188
+ return new OllamaProvider({
189
+ baseUrl: config.ollamaUrl ?? "http://localhost:11434",
190
+ model: config.ollamaModel ?? "llama3.2",
191
+ });
192
+
193
+ default:
194
+ return new StubLLMProvider();
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Create custom retriever for Engram full pipeline
200
+ */
201
+ function createCustomRetriever(config: RunBenchmarkConfig): CustomRetriever | undefined {
202
+ if (config.embeddings !== "engram") {
203
+ return undefined;
204
+ }
205
+
206
+ return new EngramRetriever({
207
+ qdrantUrl: config.qdrantUrl ?? "http://localhost:6333",
208
+ hybridSearch: config.hybridSearch,
209
+ learnedFusion: config.learnedFusion,
210
+ fusionModel: config.fusionModel,
211
+ rerank: config.rerank,
212
+ rerankTier: config.rerankTier,
213
+ rerankDepth: config.rerankDepth,
214
+ topK: config.topK,
215
+ multiQuery: config.multiQuery,
216
+ multiQueryVariations: config.multiQueryVariations,
217
+ abstention: config.abstention,
218
+ abstentionThreshold: config.abstentionThreshold,
219
+ sessionAware: config.sessionAware,
220
+ topSessions: config.topSessions,
221
+ turnsPerSession: config.turnsPerSession,
222
+ temporalAware: config.temporalAware,
223
+ temporalConfidenceThreshold: config.temporalConfidenceThreshold,
224
+ embeddingModel: config.embeddingModel,
225
+ });
226
+ }
packages/benchmark/src/core/types.ts ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Shared types for programmatic benchmark API
3
+ *
4
+ * @module @engram/benchmark/core
5
+ */
6
+
7
+ import type { DatasetVariant } from "../longmemeval/types.js";
8
+
9
+ /**
10
+ * Embedding model options
11
+ */
12
+ export type EmbeddingModel =
13
+ | "e5-small"
14
+ | "e5-base"
15
+ | "e5-large"
16
+ | "gte-base"
17
+ | "gte-large"
18
+ | "bge-small"
19
+ | "bge-base"
20
+ | "bge-large";
21
+
22
+ /**
23
+ * LLM provider options
24
+ */
25
+ export type LLMProviderType = "stub" | "anthropic" | "openai" | "ollama";
26
+
27
+ /**
28
+ * Reranker tier options
29
+ */
30
+ export type RerankerTier = "fast" | "accurate" | "code" | "colbert" | "llm";
31
+
32
+ /**
33
+ * Configuration for running a benchmark programmatically
34
+ */
35
+ export interface RunBenchmarkConfig {
36
+ /** Path to the dataset file */
37
+ dataset: string;
38
+
39
+ /** Dataset variant (s, m, oracle) */
40
+ variant: DatasetVariant;
41
+
42
+ /** Limit number of instances to evaluate */
43
+ limit?: number;
44
+
45
+ // Retrieval settings
46
+ /** Number of documents to retrieve */
47
+ topK: number;
48
+
49
+ /** Retrieval method */
50
+ retriever: "dense" | "bm25" | "hybrid";
51
+
52
+ // Engram pipeline settings
53
+ /** Embedding provider (engram uses full pipeline) */
54
+ embeddings: "engram" | "qdrant" | "stub";
55
+
56
+ /** Enable hybrid search (dense + sparse) */
57
+ hybridSearch: boolean;
58
+
59
+ /** Enable learned fusion for hybrid search */
60
+ learnedFusion: boolean;
61
+
62
+ /** Fusion model path or name */
63
+ fusionModel: string;
64
+
65
+ /** Enable reranking */
66
+ rerank: boolean;
67
+
68
+ /** Reranker tier */
69
+ rerankTier: RerankerTier;
70
+
71
+ /** Number of candidates to rerank */
72
+ rerankDepth: number;
73
+
74
+ // Multi-query
75
+ /** Enable multi-query retrieval */
76
+ multiQuery: boolean;
77
+
78
+ /** Number of query variations to generate */
79
+ multiQueryVariations: number;
80
+
81
+ // Abstention
82
+ /** Enable abstention detection */
83
+ abstention: boolean;
84
+
85
+ /** Minimum score threshold for abstention */
86
+ abstentionThreshold: number;
87
+
88
+ // Session-aware
89
+ /** Enable session-aware retrieval */
90
+ sessionAware: boolean;
91
+
92
+ /** Number of top sessions for stage 1 */
93
+ topSessions: number;
94
+
95
+ /** Number of turns per session for stage 2 */
96
+ turnsPerSession: number;
97
+
98
+ // Temporal
99
+ /** Enable temporal-aware query parsing */
100
+ temporalAware: boolean;
101
+
102
+ /** Temporal confidence threshold */
103
+ temporalConfidenceThreshold: number;
104
+
105
+ // Embedding model
106
+ /** Embedding model to use */
107
+ embeddingModel: EmbeddingModel;
108
+
109
+ // LLM provider
110
+ /** LLM provider for answer generation and evaluation */
111
+ llm: LLMProviderType;
112
+
113
+ // Ollama settings (when llm = "ollama")
114
+ /** Ollama base URL */
115
+ ollamaUrl?: string;
116
+
117
+ /** Ollama model name */
118
+ ollamaModel?: string;
119
+
120
+ // Infrastructure
121
+ /** Qdrant URL */
122
+ qdrantUrl?: string;
123
+ }
124
+
125
+ /**
126
+ * Benchmark metrics returned from evaluation
127
+ */
128
+ export interface BenchmarkMetrics {
129
+ // QA accuracy
130
+ /** Overall accuracy (correct/total) */
131
+ accuracy: number;
132
+
133
+ // Retrieval metrics
134
+ /** Recall@1 */
135
+ recallAt1: number;
136
+
137
+ /** Recall@5 */
138
+ recallAt5: number;
139
+
140
+ /** Recall@10 */
141
+ recallAt10: number;
142
+
143
+ /** NDCG@10 */
144
+ ndcgAt10: number;
145
+
146
+ /** Mean Reciprocal Rank */
147
+ mrr: number;
148
+
149
+ // Abstention metrics
150
+ /** Precision for abstention detection */
151
+ abstentionPrecision: number;
152
+
153
+ /** Recall for abstention detection */
154
+ abstentionRecall: number;
155
+
156
+ /** F1 score for abstention detection */
157
+ abstentionF1: number;
158
+
159
+ // Latency metrics (ms)
160
+ /** 50th percentile query latency */
161
+ p50Latency: number;
162
+
163
+ /** 95th percentile query latency */
164
+ p95Latency: number;
165
+
166
+ /** 99th percentile query latency */
167
+ p99Latency: number;
168
+
169
+ /** Total benchmark duration */
170
+ totalDurationMs: number;
171
+ }
172
+
173
+ /**
174
+ * Progress information during benchmark execution
175
+ */
176
+ export interface BenchmarkProgress {
177
+ /** Current stage */
178
+ stage: "loading" | "indexing" | "retrieving" | "reading" | "evaluating";
179
+
180
+ /** Current item number */
181
+ current: number;
182
+
183
+ /** Total items */
184
+ total: number;
185
+
186
+ /** Human-readable message */
187
+ message: string;
188
+ }
189
+
190
+ /**
191
+ * Result from running a benchmark
192
+ */
193
+ export interface BenchmarkRunResult {
194
+ /** Computed metrics */
195
+ metrics: BenchmarkMetrics;
196
+
197
+ /** Human-readable report (markdown) */
198
+ report: string;
199
+
200
+ /** JSONL output (LongMemEval format) */
201
+ jsonl: string;
202
+ }
packages/benchmark/src/index.ts ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @engram/benchmark
3
+ *
4
+ * Benchmark adapters for evaluating Engram's memory system against
5
+ * industry-standard benchmarks.
6
+ *
7
+ * Currently supported:
8
+ * - LongMemEval (ICLR 2025)
9
+ *
10
+ * @see https://github.com/xiaowu0162/LongMemEval
11
+ */
12
+
13
+ // Programmatic API (primary exports for automation/tuning)
14
+ export {
15
+ type BenchmarkCallbacks,
16
+ type BenchmarkMetrics,
17
+ type BenchmarkProgress,
18
+ type BenchmarkRunResult,
19
+ buildBenchmarkConfig,
20
+ DEFAULT_BENCHMARK_CONFIG,
21
+ type EmbeddingModel,
22
+ type LLMProviderType,
23
+ type RerankerTier,
24
+ type RunBenchmarkConfig,
25
+ runBenchmark,
26
+ } from "./core/index.js";
27
+
28
+ // LongMemEval-specific exports
29
+ export * from "./longmemeval/index.js";
packages/benchmark/src/longmemeval/evaluator.ts ADDED
@@ -0,0 +1,582 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { LLMProvider } from "./reader.js";
2
+ import type {
3
+ AbilityMetrics,
4
+ AbstentionMetrics,
5
+ BenchmarkResult,
6
+ EvaluatedResult,
7
+ EvaluationMetrics,
8
+ MemoryAbility,
9
+ ParsedInstance,
10
+ RetrievalMetrics,
11
+ } from "./types.js";
12
+
13
+ /**
14
+ * Configuration for evaluation
15
+ */
16
+ export interface EvaluatorConfig {
17
+ /** Whether to use LLM-based evaluation (more accurate, higher cost) */
18
+ useLLMEvaluation: boolean;
19
+ /** Use GPT-4o style evaluation prompt (LongMemEval methodology) */
20
+ useGPT4oPrompt: boolean;
21
+ /** Strict string matching for non-LLM evaluation */
22
+ strictMatching: boolean;
23
+ /** K values for recall and NDCG computation */
24
+ kValues: number[];
25
+ }
26
+
27
+ /**
28
+ * Default evaluator configuration
29
+ */
30
+ export const DEFAULT_EVALUATOR_CONFIG: EvaluatorConfig = {
31
+ useLLMEvaluation: false,
32
+ useGPT4oPrompt: true,
33
+ strictMatching: false,
34
+ kValues: [1, 5, 10],
35
+ };
36
+
37
+ /**
38
+ * Per-instance retrieval data for metrics computation
39
+ */
40
+ export interface RetrievalData {
41
+ questionId: string;
42
+ /** IDs of retrieved documents in ranked order */
43
+ retrievedIds: string[];
44
+ /** Relevance scores for retrieved documents */
45
+ scores: number[];
46
+ /** IDs of ground truth evidence documents */
47
+ evidenceIds: string[];
48
+ }
49
+
50
+ /**
51
+ * Evaluator class for computing benchmark metrics
52
+ *
53
+ * Implements Milestone 4 enhancements:
54
+ * - GPT-4o style evaluation (97% human agreement per LongMemEval)
55
+ * - NDCG@K metrics for retrieval quality
56
+ * - Abstention precision/recall metrics
57
+ */
58
+ export class Evaluator {
59
+ private config: EvaluatorConfig;
60
+ private llm?: LLMProvider;
61
+
62
+ constructor(config?: Partial<EvaluatorConfig>, llm?: LLMProvider) {
63
+ this.config = { ...DEFAULT_EVALUATOR_CONFIG, ...config };
64
+ this.llm = llm;
65
+ }
66
+
67
+ /**
68
+ * Evaluate a single result against ground truth
69
+ */
70
+ async evaluateOne(
71
+ result: BenchmarkResult,
72
+ instance: ParsedInstance,
73
+ _abstained?: boolean,
74
+ ): Promise<EvaluatedResult> {
75
+ const correct =
76
+ this.config.useLLMEvaluation && this.llm
77
+ ? await this.llmJudge(result.hypothesis, instance.answer, instance.question)
78
+ : this.stringMatch(result.hypothesis, instance.answer);
79
+
80
+ return {
81
+ ...result,
82
+ answer: instance.answer,
83
+ questionType: instance.questionType,
84
+ memoryAbility: instance.memoryAbility,
85
+ correct,
86
+ };
87
+ }
88
+
89
+ /**
90
+ * Evaluate all results and compute aggregate metrics
91
+ */
92
+ async evaluateAll(
93
+ results: BenchmarkResult[],
94
+ instances: ParsedInstance[],
95
+ retrievalData?: RetrievalData[],
96
+ abstentionFlags?: Map<string, boolean>,
97
+ ): Promise<{
98
+ evaluated: EvaluatedResult[];
99
+ metrics: EvaluationMetrics;
100
+ }> {
101
+ // Create lookup map for instances
102
+ const instanceMap = new Map(instances.map((i) => [i.questionId, i]));
103
+
104
+ // Evaluate each result
105
+ const evaluated: EvaluatedResult[] = [];
106
+ for (const result of results) {
107
+ const instance = instanceMap.get(result.questionId);
108
+ if (!instance) {
109
+ console.warn(`No instance found for question: ${result.questionId}`);
110
+ continue;
111
+ }
112
+
113
+ const abstained = abstentionFlags?.get(result.questionId);
114
+ const evalResult = await this.evaluateOne(result, instance, abstained);
115
+ evaluated.push(evalResult);
116
+ }
117
+
118
+ // Compute metrics
119
+ const metrics = this.computeMetrics(evaluated);
120
+
121
+ // Compute retrieval metrics if data provided
122
+ if (retrievalData && retrievalData.length > 0) {
123
+ metrics.retrieval = this.computeRetrievalMetrics(retrievalData);
124
+ }
125
+
126
+ // Compute abstention metrics if flags provided
127
+ if (abstentionFlags) {
128
+ metrics.abstention = this.computeAbstentionMetrics(evaluated, abstentionFlags);
129
+ }
130
+
131
+ return { evaluated, metrics };
132
+ }
133
+
134
+ /**
135
+ * String-based matching (baseline evaluation)
136
+ */
137
+ private stringMatch(hypothesis: string, answer: string): boolean {
138
+ const normalizedHyp = this.normalize(hypothesis);
139
+ const normalizedAns = this.normalize(answer);
140
+
141
+ if (this.config.strictMatching) {
142
+ return normalizedHyp === normalizedAns;
143
+ }
144
+
145
+ // Fuzzy matching: check if answer is contained in hypothesis
146
+ // or if they share significant overlap
147
+ if (normalizedHyp.includes(normalizedAns)) {
148
+ return true;
149
+ }
150
+
151
+ if (normalizedAns.includes(normalizedHyp)) {
152
+ return true;
153
+ }
154
+
155
+ // Check word overlap
156
+ const hypWords = new Set(normalizedHyp.split(/\s+/));
157
+ const ansWords = normalizedAns.split(/\s+/);
158
+
159
+ const overlap = ansWords.filter((w) => hypWords.has(w)).length;
160
+ const overlapRatio = overlap / ansWords.length;
161
+
162
+ return overlapRatio >= 0.7;
163
+ }
164
+
165
+ /**
166
+ * Normalize text for comparison
167
+ */
168
+ private normalize(text: string): string {
169
+ return text
170
+ .toLowerCase()
171
+ .replace(/[^\w\s]/g, "") // Remove punctuation
172
+ .replace(/\s+/g, " ") // Normalize whitespace
173
+ .trim();
174
+ }
175
+
176
+ /**
177
+ * LLM-based evaluation using GPT-4o style prompt
178
+ * Based on LongMemEval's methodology (97% human agreement)
179
+ */
180
+ private async llmJudge(hypothesis: string, answer: string, question: string): Promise<boolean> {
181
+ if (!this.llm) {
182
+ throw new Error("LLM provider required for LLM evaluation");
183
+ }
184
+
185
+ const prompt = this.config.useGPT4oPrompt
186
+ ? this.buildGPT4oPrompt(hypothesis, answer, question)
187
+ : this.buildBasicPrompt(hypothesis, answer, question);
188
+
189
+ const response = await this.llm.complete(prompt, {
190
+ temperature: 0,
191
+ maxTokens: 50,
192
+ });
193
+
194
+ return this.parseJudgment(response.text);
195
+ }
196
+
197
+ /**
198
+ * GPT-4o style evaluation prompt (LongMemEval methodology)
199
+ * Achieves 97% agreement with human evaluation
200
+ */
201
+ private buildGPT4oPrompt(hypothesis: string, answer: string, question: string): string {
202
+ return `You are an expert evaluator for a memory-augmented AI system. Your task is to determine if a generated answer correctly addresses a question when compared to a ground-truth reference answer.
203
+
204
+ ## Evaluation Criteria
205
+
206
+ A generated answer is CORRECT if:
207
+ 1. It contains the essential information from the reference answer
208
+ 2. The factual claims match the reference (dates, names, numbers, etc.)
209
+ 3. Minor phrasing differences or additional context are acceptable
210
+ 4. Partial answers are correct if they include the key facts
211
+
212
+ A generated answer is INCORRECT if:
213
+ 1. It contradicts the reference answer
214
+ 2. It contains factually wrong information
215
+ 3. It is completely unrelated to the question
216
+ 4. It is a refusal/abstention when the information is available
217
+
218
+ Special cases:
219
+ - Abstention answers ("I don't know", "No information available") are CORRECT only if the reference indicates the question is unanswerable
220
+ - Numeric answers must match exactly or be semantically equivalent (e.g., "3" = "three")
221
+ - Date formats can vary as long as they refer to the same date
222
+
223
+ ## Question
224
+ ${question}
225
+
226
+ ## Reference Answer (Ground Truth)
227
+ ${answer}
228
+
229
+ ## Generated Answer
230
+ ${hypothesis}
231
+
232
+ ## Your Judgment
233
+ Analyze the generated answer against the reference. Consider semantic equivalence, not just string matching.
234
+
235
+ Output ONLY one of these two words on a single line:
236
+ CORRECT
237
+ INCORRECT`;
238
+ }
239
+
240
+ /**
241
+ * Basic evaluation prompt (fallback)
242
+ */
243
+ private buildBasicPrompt(hypothesis: string, answer: string, question: string): string {
244
+ return `You are evaluating whether a generated answer correctly addresses a question compared to a reference answer.
245
+
246
+ ## Question
247
+ ${question}
248
+
249
+ ## Reference Answer
250
+ ${answer}
251
+
252
+ ## Generated Answer
253
+ ${hypothesis}
254
+
255
+ ## Task
256
+ Determine if the generated answer is correct. Consider:
257
+ 1. The generated answer captures the key information from the reference
258
+ 2. Minor differences in wording are acceptable
259
+ 3. Additional correct information is acceptable
260
+ 4. Incorrect or contradictory information is NOT acceptable
261
+ 5. "I don't know" type answers are only correct if the reference also indicates unknown
262
+
263
+ Respond with ONLY "CORRECT" or "INCORRECT" on a single line.`;
264
+ }
265
+
266
+ /**
267
+ * Parse LLM judgment response
268
+ */
269
+ private parseJudgment(text: string): boolean {
270
+ const upper = text.trim().toUpperCase();
271
+ // Look for CORRECT not preceded by IN
272
+ if (upper.includes("INCORRECT")) {
273
+ return false;
274
+ }
275
+ return upper.includes("CORRECT");
276
+ }
277
+
278
+ /**
279
+ * Compute aggregate metrics from evaluated results
280
+ */
281
+ private computeMetrics(evaluated: EvaluatedResult[]): EvaluationMetrics {
282
+ const total = evaluated.length;
283
+ const correct = evaluated.filter((e) => e.correct).length;
284
+
285
+ // Initialize per-ability metrics
286
+ const byAbility: Record<MemoryAbility, AbilityMetrics> = {
287
+ IE: { total: 0, correct: 0, accuracy: 0 },
288
+ MR: { total: 0, correct: 0, accuracy: 0 },
289
+ TR: { total: 0, correct: 0, accuracy: 0 },
290
+ KU: { total: 0, correct: 0, accuracy: 0 },
291
+ ABS: { total: 0, correct: 0, accuracy: 0 },
292
+ };
293
+
294
+ // Aggregate by ability
295
+ for (const result of evaluated) {
296
+ const ability = result.memoryAbility;
297
+ byAbility[ability].total++;
298
+ if (result.correct) {
299
+ byAbility[ability].correct++;
300
+ }
301
+ }
302
+
303
+ // Compute accuracy per ability
304
+ for (const ability of Object.keys(byAbility) as MemoryAbility[]) {
305
+ const metrics = byAbility[ability];
306
+ metrics.accuracy = metrics.total > 0 ? metrics.correct / metrics.total : 0;
307
+ }
308
+
309
+ return {
310
+ overall: {
311
+ total,
312
+ correct,
313
+ accuracy: total > 0 ? correct / total : 0,
314
+ },
315
+ byAbility,
316
+ };
317
+ }
318
+
319
+ /**
320
+ * Compute retrieval metrics including NDCG
321
+ */
322
+ private computeRetrievalMetrics(retrievalData: RetrievalData[]): RetrievalMetrics {
323
+ const recallAtK: Record<number, number> = {};
324
+ const ndcgAtK: Record<number, number> = {};
325
+
326
+ // Initialize for each K value
327
+ for (const k of this.config.kValues) {
328
+ recallAtK[k] = 0;
329
+ ndcgAtK[k] = 0;
330
+ }
331
+
332
+ let totalTurnRecall = 0;
333
+ let totalSessionRecall = 0;
334
+ let totalMRR = 0;
335
+
336
+ for (const data of retrievalData) {
337
+ const evidenceSet = new Set(data.evidenceIds);
338
+
339
+ // Compute recall at K
340
+ for (const k of this.config.kValues) {
341
+ const topK = data.retrievedIds.slice(0, k);
342
+ const retrieved = topK.filter((id) => evidenceSet.has(id)).length;
343
+ const recall = evidenceSet.size > 0 ? retrieved / evidenceSet.size : 1;
344
+ recallAtK[k] += recall;
345
+ }
346
+
347
+ // Compute NDCG at K
348
+ for (const k of this.config.kValues) {
349
+ ndcgAtK[k] += this.computeNDCG(data.retrievedIds.slice(0, k), evidenceSet);
350
+ }
351
+
352
+ // Turn recall (all retrieved)
353
+ const allRetrieved = data.retrievedIds.filter((id) => evidenceSet.has(id)).length;
354
+ totalTurnRecall += evidenceSet.size > 0 ? allRetrieved / evidenceSet.size : 1;
355
+
356
+ // Session recall (simplified - treat as same for now)
357
+ totalSessionRecall += evidenceSet.size > 0 ? allRetrieved / evidenceSet.size : 1;
358
+
359
+ // MRR - reciprocal rank of first relevant document
360
+ totalMRR += this.computeReciprocalRank(data.retrievedIds, evidenceSet);
361
+ }
362
+
363
+ const n = retrievalData.length || 1;
364
+
365
+ // Average across all instances
366
+ for (const k of this.config.kValues) {
367
+ recallAtK[k] /= n;
368
+ ndcgAtK[k] /= n;
369
+ }
370
+
371
+ return {
372
+ turnRecall: totalTurnRecall / n,
373
+ sessionRecall: totalSessionRecall / n,
374
+ recallAtK,
375
+ ndcgAtK,
376
+ mrr: totalMRR / n,
377
+ };
378
+ }
379
+
380
+ /**
381
+ * Compute NDCG (Normalized Discounted Cumulative Gain)
382
+ *
383
+ * NDCG measures the quality of a ranking by comparing to ideal ranking.
384
+ * Uses binary relevance (1 if in evidence set, 0 otherwise).
385
+ */
386
+ private computeNDCG(rankedIds: string[], evidenceSet: Set<string>): number {
387
+ if (rankedIds.length === 0 || evidenceSet.size === 0) {
388
+ return evidenceSet.size === 0 ? 1 : 0;
389
+ }
390
+
391
+ // DCG: sum of relevance / log2(rank + 1)
392
+ let dcg = 0;
393
+ for (let i = 0; i < rankedIds.length; i++) {
394
+ const relevance = evidenceSet.has(rankedIds[i]) ? 1 : 0;
395
+ dcg += relevance / Math.log2(i + 2); // i+2 because log2(1) = 0
396
+ }
397
+
398
+ // IDCG: ideal DCG (all relevant items at top)
399
+ const idealRanking = Math.min(evidenceSet.size, rankedIds.length);
400
+ let idcg = 0;
401
+ for (let i = 0; i < idealRanking; i++) {
402
+ idcg += 1 / Math.log2(i + 2);
403
+ }
404
+
405
+ return idcg > 0 ? dcg / idcg : 0;
406
+ }
407
+
408
+ /**
409
+ * Compute reciprocal rank (1/rank of first relevant item)
410
+ */
411
+ private computeReciprocalRank(rankedIds: string[], evidenceSet: Set<string>): number {
412
+ for (let i = 0; i < rankedIds.length; i++) {
413
+ if (evidenceSet.has(rankedIds[i])) {
414
+ return 1 / (i + 1);
415
+ }
416
+ }
417
+ return 0;
418
+ }
419
+
420
+ /**
421
+ * Compute abstention-specific metrics
422
+ *
423
+ * For abstention questions (ABS), we want to measure:
424
+ * - Precision: Of all abstentions, how many were correct?
425
+ * - Recall: Of questions requiring abstention, how many abstained?
426
+ */
427
+ private computeAbstentionMetrics(
428
+ evaluated: EvaluatedResult[],
429
+ abstentionFlags: Map<string, boolean>,
430
+ ): AbstentionMetrics {
431
+ let truePositives = 0; // Correctly abstained on ABS questions
432
+ let falsePositives = 0; // Incorrectly abstained on non-ABS questions
433
+ let falseNegatives = 0; // Should have abstained but didn't
434
+ let trueNegatives = 0; // Correctly answered non-ABS questions
435
+
436
+ for (const result of evaluated) {
437
+ const didAbstain = abstentionFlags.get(result.questionId) ?? false;
438
+ const shouldAbstain = result.memoryAbility === "ABS";
439
+
440
+ if (shouldAbstain && didAbstain) {
441
+ truePositives++;
442
+ } else if (!shouldAbstain && didAbstain) {
443
+ falsePositives++;
444
+ } else if (shouldAbstain && !didAbstain) {
445
+ falseNegatives++;
446
+ } else {
447
+ trueNegatives++;
448
+ }
449
+ }
450
+
451
+ const precision =
452
+ truePositives + falsePositives > 0 ? truePositives / (truePositives + falsePositives) : 0;
453
+
454
+ const recall =
455
+ truePositives + falseNegatives > 0 ? truePositives / (truePositives + falseNegatives) : 0;
456
+
457
+ const f1 = precision + recall > 0 ? (2 * precision * recall) / (precision + recall) : 0;
458
+
459
+ return {
460
+ truePositives,
461
+ falsePositives,
462
+ falseNegatives,
463
+ trueNegatives,
464
+ precision,
465
+ recall,
466
+ f1,
467
+ };
468
+ }
469
+ }
470
+
471
+ /**
472
+ * Format metrics as a human-readable report
473
+ */
474
+ export function formatMetricsReport(metrics: EvaluationMetrics): string {
475
+ const lines: string[] = [
476
+ "# LongMemEval Benchmark Results",
477
+ "",
478
+ "## Overall",
479
+ `- Total: ${metrics.overall.total}`,
480
+ `- Correct: ${metrics.overall.correct}`,
481
+ `- Accuracy: ${(metrics.overall.accuracy * 100).toFixed(1)}%`,
482
+ "",
483
+ "## By Memory Ability",
484
+ "",
485
+ "| Ability | Total | Correct | Accuracy |",
486
+ "|:--------|------:|--------:|---------:|",
487
+ ];
488
+
489
+ const abilityNames: Record<MemoryAbility, string> = {
490
+ IE: "Information Extraction",
491
+ MR: "Multi-Session Reasoning",
492
+ TR: "Temporal Reasoning",
493
+ KU: "Knowledge Update",
494
+ ABS: "Abstention",
495
+ };
496
+
497
+ for (const [ability, name] of Object.entries(abilityNames) as [MemoryAbility, string][]) {
498
+ const m = metrics.byAbility[ability];
499
+ lines.push(
500
+ `| ${name} (${ability}) | ${m.total} | ${m.correct} | ${(m.accuracy * 100).toFixed(1)}% |`,
501
+ );
502
+ }
503
+
504
+ if (metrics.retrieval) {
505
+ lines.push("");
506
+ lines.push("## Retrieval Metrics");
507
+ lines.push("");
508
+ lines.push(`- Turn Recall: ${((metrics.retrieval.turnRecall ?? 0) * 100).toFixed(1)}%`);
509
+ lines.push(`- Session Recall: ${((metrics.retrieval.sessionRecall ?? 0) * 100).toFixed(1)}%`);
510
+ if (metrics.retrieval.mrr !== undefined) {
511
+ lines.push(`- MRR: ${metrics.retrieval.mrr.toFixed(3)}`);
512
+ }
513
+ lines.push("");
514
+ lines.push("### Recall@K");
515
+ lines.push("");
516
+ lines.push("| K | Recall |");
517
+ lines.push("|--:|-------:|");
518
+ if (metrics.retrieval.recallAtK) {
519
+ for (const [k, recall] of Object.entries(metrics.retrieval.recallAtK)) {
520
+ lines.push(`| ${k} | ${((recall ?? 0) * 100).toFixed(1)}% |`);
521
+ }
522
+ }
523
+ if (metrics.retrieval.ndcgAtK) {
524
+ lines.push("");
525
+ lines.push("### NDCG@K");
526
+ lines.push("");
527
+ lines.push("| K | NDCG |");
528
+ lines.push("|--:|-----:|");
529
+ for (const [k, ndcg] of Object.entries(metrics.retrieval.ndcgAtK)) {
530
+ lines.push(`| ${k} | ${(ndcg ?? 0).toFixed(3)} |`);
531
+ }
532
+ }
533
+ }
534
+
535
+ if (metrics.abstention) {
536
+ lines.push("");
537
+ lines.push("## Abstention Metrics");
538
+ lines.push("");
539
+ lines.push(`- Precision: ${(metrics.abstention.precision * 100).toFixed(1)}%`);
540
+ lines.push(`- Recall: ${(metrics.abstention.recall * 100).toFixed(1)}%`);
541
+ lines.push(`- F1 Score: ${(metrics.abstention.f1 * 100).toFixed(1)}%`);
542
+ lines.push("");
543
+ lines.push("### Confusion Matrix");
544
+ lines.push("");
545
+ lines.push("| | Abstained | Answered |");
546
+ lines.push("|:--|----------:|---------:|");
547
+ lines.push(
548
+ `| Should Abstain | ${metrics.abstention.truePositives} (TP) | ${metrics.abstention.falseNegatives} (FN) |`,
549
+ );
550
+ lines.push(
551
+ `| Should Answer | ${metrics.abstention.falsePositives} (FP) | ${metrics.abstention.trueNegatives} (TN) |`,
552
+ );
553
+ }
554
+
555
+ return lines.join("\n");
556
+ }
557
+
558
+ /**
559
+ * Save results to JSONL format (LongMemEval output format)
560
+ */
561
+ export function resultsToJsonl(results: BenchmarkResult[]): string {
562
+ return results
563
+ .map((r) => JSON.stringify({ question_id: r.questionId, hypothesis: r.hypothesis }))
564
+ .join("\n");
565
+ }
566
+
567
+ /**
568
+ * Parse results from JSONL format
569
+ */
570
+ export function parseJsonlResults(jsonl: string): BenchmarkResult[] {
571
+ return jsonl
572
+ .trim()
573
+ .split("\n")
574
+ .filter((line) => line.trim())
575
+ .map((line) => {
576
+ const parsed = JSON.parse(line);
577
+ return {
578
+ questionId: parsed.question_id,
579
+ hypothesis: parsed.hypothesis,
580
+ };
581
+ });
582
+ }
packages/benchmark/src/longmemeval/index.ts ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * LongMemEval Benchmark Adapter
3
+ *
4
+ * Evaluates Engram's memory system against the LongMemEval benchmark (ICLR 2025).
5
+ *
6
+ * @see https://github.com/xiaowu0162/LongMemEval
7
+ * @see https://arxiv.org/abs/2410.10813
8
+ */
9
+
10
+ export * from "./evaluator.js";
11
+ // Optimizations (Milestone 2)
12
+ export * from "./key-expansion.js";
13
+ // Core components
14
+ export * from "./loader.js";
15
+ export * from "./mapper.js";
16
+ // Pipeline
17
+ export * from "./pipeline.js";
18
+ // Providers (real implementations)
19
+ export * from "./providers/index.js";
20
+ export * from "./reader.js";
21
+ export * from "./retriever.js";
22
+ export * from "./temporal.js";
23
+ // Types
24
+ export * from "./types.js";
packages/benchmark/src/longmemeval/key-expansion.ts ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { EngramDocument } from "./mapper.js";
2
+ import type { LLMProvider } from "./reader.js";
3
+
4
+ /**
5
+ * Key Expansion for improved retrieval
6
+ *
7
+ * Based on LongMemEval findings:
8
+ * - Fact-augmented key expansion improves recall by 9.4%
9
+ * - Extracting summaries, keyphrases, user facts, and timestamped events
10
+ *
11
+ * @see https://arxiv.org/abs/2410.10813
12
+ */
13
+
14
+ /**
15
+ * Types of key expansion supported
16
+ */
17
+ export type ExpansionType = "summary" | "keyphrase" | "userfact" | "event";
18
+
19
+ /**
20
+ * Configuration for key expansion
21
+ */
22
+ export interface KeyExpansionConfig {
23
+ /** Which expansion types to use */
24
+ types: ExpansionType[];
25
+ /** LLM for extraction (optional - uses heuristics if not provided) */
26
+ llm?: LLMProvider;
27
+ /** Maximum tokens per extraction */
28
+ maxTokens: number;
29
+ }
30
+
31
+ const DEFAULT_CONFIG: KeyExpansionConfig = {
32
+ types: ["keyphrase", "userfact"],
33
+ maxTokens: 256,
34
+ };
35
+
36
+ /**
37
+ * Expanded document with additional keys for retrieval
38
+ */
39
+ export interface ExpandedDocument extends EngramDocument {
40
+ /** Original content */
41
+ originalContent: string;
42
+ /** Expanded content for indexing */
43
+ expandedContent: string;
44
+ /** Extracted metadata */
45
+ expansion: {
46
+ summary?: string;
47
+ keyphrases?: string[];
48
+ userFacts?: string[];
49
+ events?: TimestampedEvent[];
50
+ };
51
+ }
52
+
53
+ /**
54
+ * A timestamped event extracted from content
55
+ */
56
+ export interface TimestampedEvent {
57
+ description: string;
58
+ date?: Date;
59
+ dateText?: string;
60
+ }
61
+
62
+ /**
63
+ * Key expander that augments documents with extracted facts
64
+ */
65
+ export class KeyExpander {
66
+ private config: KeyExpansionConfig;
67
+
68
+ constructor(config: Partial<KeyExpansionConfig> = {}) {
69
+ this.config = { ...DEFAULT_CONFIG, ...config };
70
+ }
71
+
72
+ /**
73
+ * Expand a batch of documents
74
+ */
75
+ async expandBatch(documents: EngramDocument[]): Promise<ExpandedDocument[]> {
76
+ const expanded: ExpandedDocument[] = [];
77
+
78
+ for (const doc of documents) {
79
+ expanded.push(await this.expand(doc));
80
+ }
81
+
82
+ return expanded;
83
+ }
84
+
85
+ /**
86
+ * Expand a single document
87
+ */
88
+ async expand(document: EngramDocument): Promise<ExpandedDocument> {
89
+ const expansion: ExpandedDocument["expansion"] = {};
90
+
91
+ // Extract based on configured types
92
+ for (const type of this.config.types) {
93
+ switch (type) {
94
+ case "summary":
95
+ expansion.summary = await this.extractSummary(document.content);
96
+ break;
97
+ case "keyphrase":
98
+ expansion.keyphrases = await this.extractKeyphrases(document.content);
99
+ break;
100
+ case "userfact":
101
+ expansion.userFacts = await this.extractUserFacts(document.content);
102
+ break;
103
+ case "event":
104
+ expansion.events = await this.extractEvents(document.content, document.validTime);
105
+ break;
106
+ }
107
+ }
108
+
109
+ // Build expanded content
110
+ const expandedContent = this.buildExpandedContent(document.content, expansion);
111
+
112
+ return {
113
+ ...document,
114
+ originalContent: document.content,
115
+ expandedContent,
116
+ content: expandedContent, // Replace content for indexing
117
+ expansion,
118
+ };
119
+ }
120
+
121
+ /**
122
+ * Extract a summary from content
123
+ */
124
+ private async extractSummary(content: string): Promise<string> {
125
+ if (this.config.llm) {
126
+ return this.llmExtractSummary(content);
127
+ }
128
+ return this.heuristicSummary(content);
129
+ }
130
+
131
+ /**
132
+ * Extract keyphrases from content
133
+ */
134
+ private async extractKeyphrases(content: string): Promise<string[]> {
135
+ if (this.config.llm) {
136
+ return this.llmExtractKeyphrases(content);
137
+ }
138
+ return this.heuristicKeyphrases(content);
139
+ }
140
+
141
+ /**
142
+ * Extract user facts from content
143
+ */
144
+ private async extractUserFacts(content: string): Promise<string[]> {
145
+ if (this.config.llm) {
146
+ return this.llmExtractUserFacts(content);
147
+ }
148
+ return this.heuristicUserFacts(content);
149
+ }
150
+
151
+ /**
152
+ * Extract timestamped events from content
153
+ */
154
+ private async extractEvents(content: string, baseDate: Date): Promise<TimestampedEvent[]> {
155
+ if (this.config.llm) {
156
+ return this.llmExtractEvents(content, baseDate);
157
+ }
158
+ return this.heuristicEvents(content, baseDate);
159
+ }
160
+
161
+ /**
162
+ * Build expanded content from original + extracted facts
163
+ */
164
+ private buildExpandedContent(original: string, expansion: ExpandedDocument["expansion"]): string {
165
+ const parts = [original];
166
+
167
+ if (expansion.summary) {
168
+ parts.push(`[Summary: ${expansion.summary}]`);
169
+ }
170
+
171
+ if (expansion.keyphrases && expansion.keyphrases.length > 0) {
172
+ parts.push(`[Keywords: ${expansion.keyphrases.join(", ")}]`);
173
+ }
174
+
175
+ if (expansion.userFacts && expansion.userFacts.length > 0) {
176
+ parts.push(`[Facts: ${expansion.userFacts.join("; ")}]`);
177
+ }
178
+
179
+ if (expansion.events && expansion.events.length > 0) {
180
+ const eventStrs = expansion.events.map(
181
+ (e) => `${e.description}${e.dateText ? ` (${e.dateText})` : ""}`,
182
+ );
183
+ parts.push(`[Events: ${eventStrs.join("; ")}]`);
184
+ }
185
+
186
+ return parts.join("\n");
187
+ }
188
+
189
+ // ========== LLM-based extraction ==========
190
+
191
+ private async llmExtractSummary(content: string): Promise<string> {
192
+ const prompt = `Summarize the following conversation turn in one sentence. Focus on the key information shared.
193
+
194
+ Content:
195
+ ${content}
196
+
197
+ Summary (one sentence):`;
198
+
199
+ const response = await this.config.llm?.complete(prompt, { maxTokens: 100 });
200
+ return response?.text.trim() ?? "";
201
+ }
202
+
203
+ private async llmExtractKeyphrases(content: string): Promise<string[]> {
204
+ const prompt = `Extract 3-5 key phrases from the following text. Return only the phrases, one per line.
205
+
206
+ Content:
207
+ ${content}
208
+
209
+ Key phrases:`;
210
+
211
+ const response = await this.config.llm?.complete(prompt, { maxTokens: 100 });
212
+ if (!response) return [];
213
+ return response.text
214
+ .split("\n")
215
+ .map((line) => line.trim().replace(/^[-•*]\s*/, ""))
216
+ .filter((line) => line.length > 0);
217
+ }
218
+
219
+ private async llmExtractUserFacts(content: string): Promise<string[]> {
220
+ const prompt = `Extract any personal facts about the user from this conversation. Include preferences, biographical info, habits, etc. Return facts as simple statements, one per line.
221
+
222
+ Content:
223
+ ${content}
224
+
225
+ User facts (if any):`;
226
+
227
+ const response = await this.config.llm?.complete(prompt, { maxTokens: 150 });
228
+ if (!response) return [];
229
+ return response.text
230
+ .split("\n")
231
+ .map((line) => line.trim().replace(/^[-•*]\s*/, ""))
232
+ .filter(
233
+ (line) =>
234
+ line.length > 0 &&
235
+ !line.toLowerCase().includes("no ") &&
236
+ !line.toLowerCase().includes("none"),
237
+ );
238
+ }
239
+
240
+ private async llmExtractEvents(content: string, baseDate: Date): Promise<TimestampedEvent[]> {
241
+ const prompt = `Extract any events or activities mentioned in this text. For each event, note if a specific date or time is mentioned. Return as JSON array.
242
+
243
+ Content:
244
+ ${content}
245
+
246
+ Base date for relative references: ${baseDate.toISOString().split("T")[0]}
247
+
248
+ Return JSON array of objects with "description" and optional "dateText" fields:`;
249
+
250
+ const response = await this.config.llm?.complete(prompt, { maxTokens: 200 });
251
+ if (!response) return [];
252
+
253
+ try {
254
+ const jsonMatch = response.text.match(/\[[\s\S]*\]/);
255
+ if (jsonMatch) {
256
+ return JSON.parse(jsonMatch[0]);
257
+ }
258
+ } catch {
259
+ // Fall back to heuristic
260
+ }
261
+
262
+ return this.heuristicEvents(content, baseDate);
263
+ }
264
+
265
+ // ========== Heuristic-based extraction ==========
266
+
267
+ private heuristicSummary(content: string): string {
268
+ // Take first sentence or first 100 chars
269
+ const firstSentence = content.match(/^[^.!?]+[.!?]/);
270
+ if (firstSentence && firstSentence[0].length < 200) {
271
+ return firstSentence[0].trim();
272
+ }
273
+ return `${content.slice(0, 100).trim()}...`;
274
+ }
275
+
276
+ private heuristicKeyphrases(content: string): string[] {
277
+ const keyphrases: string[] = [];
278
+
279
+ // Extract noun phrases (simplified)
280
+ const words = content.toLowerCase().split(/\s+/);
281
+ const stopwords = new Set([
282
+ "the",
283
+ "a",
284
+ "an",
285
+ "is",
286
+ "are",
287
+ "was",
288
+ "were",
289
+ "be",
290
+ "been",
291
+ "being",
292
+ "have",
293
+ "has",
294
+ "had",
295
+ "do",
296
+ "does",
297
+ "did",
298
+ "will",
299
+ "would",
300
+ "could",
301
+ "should",
302
+ "may",
303
+ "might",
304
+ "must",
305
+ "shall",
306
+ "can",
307
+ "need",
308
+ "dare",
309
+ "ought",
310
+ "used",
311
+ "to",
312
+ "of",
313
+ "in",
314
+ "for",
315
+ "on",
316
+ "with",
317
+ "at",
318
+ "by",
319
+ "from",
320
+ "as",
321
+ "into",
322
+ "through",
323
+ "during",
324
+ "before",
325
+ "after",
326
+ "above",
327
+ "below",
328
+ "between",
329
+ "under",
330
+ "again",
331
+ "further",
332
+ "then",
333
+ "once",
334
+ "here",
335
+ "there",
336
+ "when",
337
+ "where",
338
+ "why",
339
+ "how",
340
+ "all",
341
+ "each",
342
+ "few",
343
+ "more",
344
+ "most",
345
+ "other",
346
+ "some",
347
+ "such",
348
+ "no",
349
+ "nor",
350
+ "not",
351
+ "only",
352
+ "own",
353
+ "same",
354
+ "so",
355
+ "than",
356
+ "too",
357
+ "very",
358
+ "just",
359
+ "i",
360
+ "me",
361
+ "my",
362
+ "myself",
363
+ "we",
364
+ "our",
365
+ "ours",
366
+ "you",
367
+ "your",
368
+ "he",
369
+ "him",
370
+ "his",
371
+ "she",
372
+ "her",
373
+ "it",
374
+ "its",
375
+ "they",
376
+ "them",
377
+ "their",
378
+ "what",
379
+ "which",
380
+ "who",
381
+ "whom",
382
+ "this",
383
+ "that",
384
+ "these",
385
+ "those",
386
+ "am",
387
+ "and",
388
+ "but",
389
+ "if",
390
+ "or",
391
+ "because",
392
+ "until",
393
+ "while",
394
+ ]);
395
+
396
+ // Find significant words
397
+ const significantWords = words.filter(
398
+ (w) => w.length > 3 && !stopwords.has(w) && /^[a-z]+$/.test(w),
399
+ );
400
+
401
+ // Count frequency
402
+ const freq = new Map<string, number>();
403
+ for (const word of significantWords) {
404
+ freq.set(word, (freq.get(word) ?? 0) + 1);
405
+ }
406
+
407
+ // Get top words
408
+ const sorted = [...freq.entries()].sort((a, b) => b[1] - a[1]);
409
+ keyphrases.push(...sorted.slice(0, 5).map(([word]) => word));
410
+
411
+ return keyphrases;
412
+ }
413
+
414
+ private heuristicUserFacts(content: string): string[] {
415
+ const facts: string[] = [];
416
+ const _lowerContent = content.toLowerCase();
417
+
418
+ // Patterns for user facts
419
+ const patterns = [
420
+ /my (?:favorite|favourite) (\w+) is ([^.!?,]+)/gi,
421
+ /i (?:am|'m) (?:a |an )?([^.!?,]+)/gi,
422
+ /i (?:live|work|study) (?:in|at) ([^.!?,]+)/gi,
423
+ /i (?:like|love|enjoy|prefer) ([^.!?,]+)/gi,
424
+ /i (?:have|own|got) (?:a |an )?([^.!?,]+)/gi,
425
+ /my (?:name|job|occupation|hobby) is ([^.!?,]+)/gi,
426
+ /i (?:was born|grew up) (?:in|on) ([^.!?,]+)/gi,
427
+ ];
428
+
429
+ for (const pattern of patterns) {
430
+ for (const match of content.matchAll(pattern)) {
431
+ const fact = match[0].trim();
432
+ if (fact.length > 5 && fact.length < 100) {
433
+ facts.push(fact);
434
+ }
435
+ }
436
+ }
437
+
438
+ return [...new Set(facts)].slice(0, 5);
439
+ }
440
+
441
+ private heuristicEvents(content: string, _baseDate: Date): TimestampedEvent[] {
442
+ const events: TimestampedEvent[] = [];
443
+
444
+ // Patterns for events with dates
445
+ const datePatterns = [
446
+ /(?:on|at|during|last|next|this) (monday|tuesday|wednesday|thursday|friday|saturday|sunday)/gi,
447
+ /(?:on|in|during) (january|february|march|april|may|june|july|august|september|october|november|december)(?: \d{1,2})?(?:,? \d{4})?/gi,
448
+ /(yesterday|today|tomorrow|last week|next week|last month|next month)/gi,
449
+ /(\d{1,2}\/\d{1,2}(?:\/\d{2,4})?)/g,
450
+ /(\d{4}-\d{2}-\d{2})/g,
451
+ ];
452
+
453
+ // Activity patterns
454
+ const activityPatterns = [
455
+ /i (?:went|visited|attended|saw|met|had) ([^.!?]+)/gi,
456
+ /(?:going|planning|scheduled) to ([^.!?]+)/gi,
457
+ /(?:bought|purchased|ordered|received) ([^.!?]+)/gi,
458
+ ];
459
+
460
+ // Extract date mentions
461
+ const dateMentions: string[] = [];
462
+ for (const pattern of datePatterns) {
463
+ for (const match of content.matchAll(pattern)) {
464
+ dateMentions.push(match[1]);
465
+ }
466
+ }
467
+
468
+ // Extract activities
469
+ for (const pattern of activityPatterns) {
470
+ for (const match of content.matchAll(pattern)) {
471
+ const description = match[0].trim();
472
+ if (description.length > 10 && description.length < 150) {
473
+ events.push({
474
+ description,
475
+ dateText: dateMentions[0], // Associate with first date mention
476
+ });
477
+ }
478
+ }
479
+ }
480
+
481
+ return events.slice(0, 5);
482
+ }
483
+ }
484
+
485
+ /**
486
+ * Apply key expansion to documents before indexing
487
+ */
488
+ export async function expandDocuments(
489
+ documents: EngramDocument[],
490
+ config?: Partial<KeyExpansionConfig>,
491
+ ): Promise<ExpandedDocument[]> {
492
+ const expander = new KeyExpander(config);
493
+ return expander.expandBatch(documents);
494
+ }
packages/benchmark/src/longmemeval/loader.ts ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import {
4
+ type DatasetVariant,
5
+ getMemoryAbility,
6
+ type LongMemEvalDataset,
7
+ LongMemEvalDatasetSchema,
8
+ type LongMemEvalInstance,
9
+ type ParsedInstance,
10
+ type ParsedSession,
11
+ type ParsedTurn,
12
+ } from "./types.js";
13
+
14
+ /**
15
+ * Configuration for the dataset loader
16
+ */
17
+ export interface LoaderConfig {
18
+ /** Path to the dataset directory or file */
19
+ datasetPath: string;
20
+ /** Dataset variant to load */
21
+ variant?: DatasetVariant;
22
+ /** Limit number of instances to load (for testing) */
23
+ limit?: number;
24
+ /** Filter by question types */
25
+ questionTypes?: string[];
26
+ }
27
+
28
+ /**
29
+ * Result of loading a dataset
30
+ */
31
+ export interface LoadResult {
32
+ /** Parsed instances ready for processing */
33
+ instances: ParsedInstance[];
34
+ /** Raw dataset for reference */
35
+ raw: LongMemEvalDataset;
36
+ /** Statistics about the loaded dataset */
37
+ stats: LoadStats;
38
+ }
39
+
40
+ /**
41
+ * Statistics about the loaded dataset
42
+ */
43
+ export interface LoadStats {
44
+ totalInstances: number;
45
+ totalSessions: number;
46
+ totalTurns: number;
47
+ byAbility: Record<string, number>;
48
+ abstentionCount: number;
49
+ }
50
+
51
+ /**
52
+ * Loads and parses a LongMemEval dataset
53
+ */
54
+ export async function loadDataset(config: LoaderConfig): Promise<LoadResult> {
55
+ const datasetPath = resolveDatasetPath(config);
56
+ const rawContent = await readFile(datasetPath, "utf-8");
57
+ const rawData = JSON.parse(rawContent);
58
+
59
+ // Validate with Zod
60
+ const dataset = LongMemEvalDatasetSchema.parse(rawData);
61
+
62
+ // Apply filters
63
+ let filteredDataset = dataset;
64
+
65
+ if (config.questionTypes && config.questionTypes.length > 0) {
66
+ filteredDataset = filteredDataset.filter((instance) =>
67
+ config.questionTypes?.includes(instance.question_type),
68
+ );
69
+ }
70
+
71
+ if (config.limit && config.limit > 0) {
72
+ filteredDataset = filteredDataset.slice(0, config.limit);
73
+ }
74
+
75
+ // Parse instances
76
+ const instances = filteredDataset.map(parseInstance);
77
+
78
+ // Compute statistics
79
+ const stats = computeStats(instances);
80
+
81
+ return {
82
+ instances,
83
+ raw: filteredDataset,
84
+ stats,
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Resolves the dataset path based on variant
90
+ */
91
+ function resolveDatasetPath(config: LoaderConfig): string {
92
+ const { datasetPath, variant } = config;
93
+
94
+ // If path ends with .json, use it directly
95
+ if (datasetPath.endsWith(".json")) {
96
+ return datasetPath;
97
+ }
98
+
99
+ // Otherwise, construct path from variant
100
+ const filename = variant ? `longmemeval_${variant}_cleaned.json` : "longmemeval_s_cleaned.json";
101
+
102
+ return join(datasetPath, filename);
103
+ }
104
+
105
+ /**
106
+ * Parses a raw LongMemEval instance into a normalized format
107
+ */
108
+ function parseInstance(raw: LongMemEvalInstance): ParsedInstance {
109
+ const isAbstention = raw.question_id.endsWith("_abs");
110
+ const memoryAbility = getMemoryAbility(raw.question_type, raw.question_id);
111
+
112
+ // Parse sessions with timestamps
113
+ const sessions: ParsedSession[] = raw.haystack_sessions.map((session, sessionIndex) => {
114
+ const sessionId = raw.haystack_session_ids[sessionIndex];
115
+ const timestamp = parseTimestamp(raw.haystack_dates[sessionIndex]);
116
+
117
+ const turns: ParsedTurn[] = session.map((turn, turnIndex) => ({
118
+ role: turn.role,
119
+ content: turn.content,
120
+ hasAnswer: turn.has_answer ?? false,
121
+ sequenceIndex: turnIndex,
122
+ }));
123
+
124
+ return {
125
+ sessionId,
126
+ timestamp,
127
+ turns,
128
+ };
129
+ });
130
+
131
+ return {
132
+ questionId: raw.question_id,
133
+ questionType: raw.question_type,
134
+ memoryAbility,
135
+ question: raw.question,
136
+ answer: raw.answer,
137
+ questionDate: parseTimestamp(raw.question_date),
138
+ sessions,
139
+ answerSessionIds: raw.answer_session_ids,
140
+ isAbstention,
141
+ };
142
+ }
143
+
144
+ /**
145
+ * Parses a timestamp string into a Date object
146
+ * Handles various formats from the dataset
147
+ */
148
+ function parseTimestamp(timestamp: string): Date {
149
+ // Try ISO 8601 first
150
+ const date = new Date(timestamp);
151
+
152
+ if (!Number.isNaN(date.getTime())) {
153
+ return date;
154
+ }
155
+
156
+ // Try other formats if needed
157
+ // The dataset uses ISO format, so this should generally work
158
+ throw new Error(`Unable to parse timestamp: ${timestamp}`);
159
+ }
160
+
161
+ /**
162
+ * Computes statistics about the loaded instances
163
+ */
164
+ function computeStats(instances: ParsedInstance[]): LoadStats {
165
+ const byAbility: Record<string, number> = {
166
+ IE: 0,
167
+ MR: 0,
168
+ TR: 0,
169
+ KU: 0,
170
+ ABS: 0,
171
+ };
172
+
173
+ let totalSessions = 0;
174
+ let totalTurns = 0;
175
+ let abstentionCount = 0;
176
+
177
+ for (const instance of instances) {
178
+ byAbility[instance.memoryAbility]++;
179
+
180
+ if (instance.isAbstention) {
181
+ abstentionCount++;
182
+ }
183
+
184
+ totalSessions += instance.sessions.length;
185
+
186
+ for (const session of instance.sessions) {
187
+ totalTurns += session.turns.length;
188
+ }
189
+ }
190
+
191
+ return {
192
+ totalInstances: instances.length,
193
+ totalSessions,
194
+ totalTurns,
195
+ byAbility,
196
+ abstentionCount,
197
+ };
198
+ }
199
+
200
+ /**
201
+ * Loads a single instance by question ID
202
+ */
203
+ export async function loadInstance(
204
+ config: LoaderConfig,
205
+ questionId: string,
206
+ ): Promise<ParsedInstance | null> {
207
+ const { instances } = await loadDataset(config);
208
+ return instances.find((i) => i.questionId === questionId) ?? null;
209
+ }
210
+
211
+ /**
212
+ * Validates that a dataset file exists and is valid
213
+ */
214
+ export async function validateDataset(
215
+ datasetPath: string,
216
+ ): Promise<{ valid: boolean; error?: string; stats?: LoadStats }> {
217
+ try {
218
+ const result = await loadDataset({ datasetPath });
219
+ return { valid: true, stats: result.stats };
220
+ } catch (error) {
221
+ return {
222
+ valid: false,
223
+ error: error instanceof Error ? error.message : String(error),
224
+ };
225
+ }
226
+ }
packages/benchmark/src/longmemeval/mapper.ts ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { ParsedInstance, ParsedSession } from "./types.js";
2
+
3
+ /**
4
+ * Configuration for mapping LongMemEval data to Engram format
5
+ */
6
+ export interface MapperConfig {
7
+ /** Granularity for indexing (turn is recommended by LongMemEval paper) */
8
+ granularity: "session" | "turn";
9
+ /** Whether to include assistant turns in embeddings */
10
+ includeAssistant: boolean;
11
+ }
12
+
13
+ /**
14
+ * Default mapper configuration based on LongMemEval findings
15
+ * - Turn granularity is optimal (Finding 1 from paper)
16
+ * - Include both user and assistant (recommended setting)
17
+ */
18
+ export const DEFAULT_MAPPER_CONFIG: MapperConfig = {
19
+ granularity: "turn",
20
+ includeAssistant: true,
21
+ };
22
+
23
+ /**
24
+ * Represents a document ready for indexing in Engram
25
+ */
26
+ export interface EngramDocument {
27
+ /** Unique identifier */
28
+ id: string;
29
+ /** Instance this document belongs to */
30
+ instanceId: string;
31
+ /** Original session ID from LongMemEval */
32
+ sessionId: string;
33
+ /** Content to embed */
34
+ content: string;
35
+ /** Valid time - when this conversation occurred */
36
+ validTime: Date;
37
+ /** Metadata for filtering and evaluation */
38
+ metadata: EngramDocumentMetadata;
39
+ }
40
+
41
+ export interface EngramDocumentMetadata {
42
+ /** Original question ID */
43
+ questionId: string;
44
+ /** Role of the speaker */
45
+ role: "user" | "assistant" | "combined";
46
+ /** Whether this document contains answer evidence */
47
+ hasAnswer: boolean;
48
+ /** Turn index within the session */
49
+ turnIndex?: number;
50
+ /** Session index within the instance */
51
+ sessionIndex: number;
52
+ }
53
+
54
+ /**
55
+ * Result of mapping an instance to Engram documents
56
+ */
57
+ export interface MappedInstance {
58
+ /** The original parsed instance */
59
+ instance: ParsedInstance;
60
+ /** Documents ready for indexing */
61
+ documents: EngramDocument[];
62
+ /** Evidence document IDs for evaluation */
63
+ evidenceDocIds: string[];
64
+ }
65
+
66
+ /**
67
+ * Maps a LongMemEval instance to Engram documents
68
+ */
69
+ export function mapInstance(
70
+ instance: ParsedInstance,
71
+ config: MapperConfig = DEFAULT_MAPPER_CONFIG,
72
+ ): MappedInstance {
73
+ const documents: EngramDocument[] = [];
74
+ const evidenceDocIds: string[] = [];
75
+
76
+ for (let sessionIndex = 0; sessionIndex < instance.sessions.length; sessionIndex++) {
77
+ const session = instance.sessions[sessionIndex];
78
+ const sessionDocs = mapSession(instance.questionId, session, sessionIndex, config);
79
+
80
+ documents.push(...sessionDocs);
81
+
82
+ // Track evidence documents
83
+ for (const doc of sessionDocs) {
84
+ if (doc.metadata.hasAnswer) {
85
+ evidenceDocIds.push(doc.id);
86
+ }
87
+ }
88
+ }
89
+
90
+ return {
91
+ instance,
92
+ documents,
93
+ evidenceDocIds,
94
+ };
95
+ }
96
+
97
+ /**
98
+ * Maps a session to Engram documents based on granularity
99
+ */
100
+ function mapSession(
101
+ questionId: string,
102
+ session: ParsedSession,
103
+ sessionIndex: number,
104
+ config: MapperConfig,
105
+ ): EngramDocument[] {
106
+ if (config.granularity === "session") {
107
+ return [mapSessionAsDocument(questionId, session, sessionIndex, config)];
108
+ }
109
+
110
+ return mapTurnsAsDocuments(questionId, session, sessionIndex, config);
111
+ }
112
+
113
+ /**
114
+ * Maps an entire session as a single document
115
+ */
116
+ function mapSessionAsDocument(
117
+ questionId: string,
118
+ session: ParsedSession,
119
+ sessionIndex: number,
120
+ config: MapperConfig,
121
+ ): EngramDocument {
122
+ const relevantTurns = config.includeAssistant
123
+ ? session.turns
124
+ : session.turns.filter((t) => t.role === "user");
125
+
126
+ const content = relevantTurns.map((t) => `${t.role}: ${t.content}`).join("\n\n");
127
+
128
+ const hasAnswer = session.turns.some((t) => t.hasAnswer);
129
+
130
+ return {
131
+ id: `${questionId}:${session.sessionId}`,
132
+ instanceId: questionId,
133
+ sessionId: session.sessionId,
134
+ content,
135
+ validTime: session.timestamp,
136
+ metadata: {
137
+ questionId,
138
+ role: "combined",
139
+ hasAnswer,
140
+ sessionIndex,
141
+ },
142
+ };
143
+ }
144
+
145
+ /**
146
+ * Maps each turn as a separate document (recommended by LongMemEval)
147
+ */
148
+ function mapTurnsAsDocuments(
149
+ questionId: string,
150
+ session: ParsedSession,
151
+ sessionIndex: number,
152
+ config: MapperConfig,
153
+ ): EngramDocument[] {
154
+ const documents: EngramDocument[] = [];
155
+
156
+ for (const turn of session.turns) {
157
+ // Skip assistant turns if not included
158
+ if (!config.includeAssistant && turn.role === "assistant") {
159
+ continue;
160
+ }
161
+
162
+ documents.push({
163
+ id: `${questionId}:${session.sessionId}:${turn.sequenceIndex}`,
164
+ instanceId: questionId,
165
+ sessionId: session.sessionId,
166
+ content: turn.content,
167
+ validTime: session.timestamp,
168
+ metadata: {
169
+ questionId,
170
+ role: turn.role,
171
+ hasAnswer: turn.hasAnswer,
172
+ turnIndex: turn.sequenceIndex,
173
+ sessionIndex,
174
+ },
175
+ });
176
+ }
177
+
178
+ return documents;
179
+ }
180
+
181
+ /**
182
+ * Formats documents for retrieval context
183
+ * Uses structured JSON format (recommended by LongMemEval)
184
+ */
185
+ export function formatDocumentsForContext(
186
+ documents: EngramDocument[],
187
+ options: { includeTimestamp?: boolean; maxLength?: number } = {},
188
+ ): string {
189
+ const { includeTimestamp = true, maxLength } = options;
190
+
191
+ const formatted = documents.map((doc, index) => {
192
+ const entry: Record<string, unknown> = {
193
+ index: index + 1,
194
+ content: doc.content,
195
+ };
196
+
197
+ if (includeTimestamp) {
198
+ entry.date = doc.validTime.toISOString().split("T")[0];
199
+ }
200
+
201
+ if (doc.metadata.role !== "combined") {
202
+ entry.role = doc.metadata.role;
203
+ }
204
+
205
+ return entry;
206
+ });
207
+
208
+ let result = JSON.stringify(formatted, null, 2);
209
+
210
+ // Truncate if needed
211
+ if (maxLength && result.length > maxLength) {
212
+ result = `${result.slice(0, maxLength)}\n... (truncated)`;
213
+ }
214
+
215
+ return result;
216
+ }
217
+
218
+ /**
219
+ * Groups documents by session for session-level evaluation
220
+ */
221
+ export function groupBySession(documents: EngramDocument[]): Map<string, EngramDocument[]> {
222
+ const groups = new Map<string, EngramDocument[]>();
223
+
224
+ for (const doc of documents) {
225
+ const existing = groups.get(doc.sessionId);
226
+ if (existing) {
227
+ existing.push(doc);
228
+ } else {
229
+ groups.set(doc.sessionId, [doc]);
230
+ }
231
+ }
232
+
233
+ return groups;
234
+ }
packages/benchmark/src/longmemeval/pipeline.ts ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ DEFAULT_EVALUATOR_CONFIG,
3
+ Evaluator,
4
+ type EvaluatorConfig,
5
+ formatMetricsReport,
6
+ resultsToJsonl,
7
+ } from "./evaluator.js";
8
+ import { KeyExpander, type KeyExpansionConfig } from "./key-expansion.js";
9
+ import { type LoaderConfig, loadDataset } from "./loader.js";
10
+ import {
11
+ DEFAULT_MAPPER_CONFIG,
12
+ type EngramDocument,
13
+ type MappedInstance,
14
+ type MapperConfig,
15
+ mapInstance,
16
+ } from "./mapper.js";
17
+ import { DEFAULT_READER_CONFIG, type LLMProvider, Reader, type ReaderConfig } from "./reader.js";
18
+ import {
19
+ computeRetrievalMetrics,
20
+ DEFAULT_RETRIEVER_CONFIG,
21
+ type EmbeddingProvider,
22
+ type RetrievalResult,
23
+ Retriever,
24
+ type RetrieverConfig,
25
+ } from "./retriever.js";
26
+ import { filterByTimeRange, TemporalAnalyzer, type TemporalConfig } from "./temporal.js";
27
+ import type { BenchmarkResult, EvaluationMetrics } from "./types.js";
28
+
29
+ /**
30
+ * Interface for custom retrievers (e.g., EngramRetriever)
31
+ */
32
+ export interface CustomRetriever {
33
+ indexInstance(mapped: MappedInstance): Promise<void>;
34
+ retrieve(question: string, questionDate?: Date): Promise<RetrievalResult>;
35
+ clear(): void;
36
+ }
37
+
38
+ /**
39
+ * Debug info for retrieval analysis
40
+ */
41
+ export interface RetrievalDebugInfo {
42
+ questionId: string;
43
+ question: string;
44
+ expectedAnswer: string;
45
+ evidenceDocIds: string[];
46
+ evidenceDocs: Array<{ id: string; content: string; sessionId: string }>;
47
+ retrievedDocs: Array<{ id: string; content: string; score: number; isEvidence: boolean }>;
48
+ recall: number;
49
+ }
50
+
51
+ /**
52
+ * Full pipeline configuration
53
+ */
54
+ export interface PipelineConfig {
55
+ /** Dataset loading configuration */
56
+ loader: LoaderConfig;
57
+ /** Mapper configuration */
58
+ mapper?: Partial<MapperConfig>;
59
+ /** Retriever configuration */
60
+ retriever?: Partial<RetrieverConfig>;
61
+ /** Reader configuration */
62
+ reader?: Partial<ReaderConfig>;
63
+ /** Evaluator configuration */
64
+ evaluator?: Partial<EvaluatorConfig>;
65
+ /** Key expansion configuration (Milestone 2) */
66
+ keyExpansion?: Partial<KeyExpansionConfig> & { enabled?: boolean };
67
+ /** Temporal analysis configuration (Milestone 2) */
68
+ temporal?: Partial<TemporalConfig> & { enabled?: boolean };
69
+ /** Progress callback */
70
+ onProgress?: (progress: PipelineProgress) => void;
71
+ /** Optional custom retriever (overrides default) */
72
+ customRetriever?: CustomRetriever;
73
+ /** Debug retrieval callback - called after each retrieval with detailed info */
74
+ onRetrievalDebug?: (debug: RetrievalDebugInfo) => void;
75
+ }
76
+
77
+ /**
78
+ * Progress information during pipeline execution
79
+ */
80
+ export interface PipelineProgress {
81
+ stage: "loading" | "indexing" | "retrieving" | "reading" | "evaluating";
82
+ current: number;
83
+ total: number;
84
+ message: string;
85
+ }
86
+
87
+ /**
88
+ * Latency metrics computed from per-query timings
89
+ */
90
+ export interface LatencyMetrics {
91
+ /** Per-query latencies in ms (for computing percentiles) */
92
+ perQueryLatencies: number[];
93
+ /** 50th percentile latency in ms */
94
+ p50: number;
95
+ /** 95th percentile latency in ms */
96
+ p95: number;
97
+ /** 99th percentile latency in ms */
98
+ p99: number;
99
+ /** Mean latency in ms */
100
+ mean: number;
101
+ /** Total pipeline duration in ms */
102
+ totalDurationMs: number;
103
+ }
104
+
105
+ /**
106
+ * Result of running the full pipeline
107
+ */
108
+ export interface PipelineResult {
109
+ /** All benchmark results */
110
+ results: BenchmarkResult[];
111
+ /** Evaluation metrics */
112
+ metrics: EvaluationMetrics;
113
+ /** Human-readable report */
114
+ report: string;
115
+ /** JSONL output (LongMemEval format) */
116
+ jsonl: string;
117
+ /** Per-instance details for debugging */
118
+ details: InstanceDetail[];
119
+ /** Latency metrics */
120
+ latency: LatencyMetrics;
121
+ }
122
+
123
+ /**
124
+ * Details for a single instance (for debugging)
125
+ */
126
+ export interface InstanceDetail {
127
+ questionId: string;
128
+ question: string;
129
+ answer: string;
130
+ hypothesis: string;
131
+ correct: boolean;
132
+ retrievedCount: number;
133
+ evidenceRetrieved: number;
134
+ retrievalRecall: number;
135
+ /** Query latency in ms (retrieval + reading time) */
136
+ latencyMs: number;
137
+ }
138
+
139
+ /**
140
+ * Main benchmark pipeline
141
+ */
142
+ export class BenchmarkPipeline {
143
+ private embeddings: EmbeddingProvider;
144
+ private llm: LLMProvider;
145
+ private config: PipelineConfig;
146
+
147
+ constructor(embeddings: EmbeddingProvider, llm: LLMProvider, config: PipelineConfig) {
148
+ this.embeddings = embeddings;
149
+ this.llm = llm;
150
+ this.config = config;
151
+ }
152
+
153
+ /**
154
+ * Run the full benchmark pipeline
155
+ */
156
+ async run(): Promise<PipelineResult> {
157
+ const pipelineStartTime = Date.now();
158
+ const { onProgress } = this.config;
159
+
160
+ // Stage 1: Load dataset
161
+ onProgress?.({
162
+ stage: "loading",
163
+ current: 0,
164
+ total: 1,
165
+ message: "Loading dataset...",
166
+ });
167
+
168
+ const { instances, stats } = await loadDataset(this.config.loader);
169
+
170
+ onProgress?.({
171
+ stage: "loading",
172
+ current: 1,
173
+ total: 1,
174
+ message: `Loaded ${stats.totalInstances} instances`,
175
+ });
176
+
177
+ // Initialize components
178
+ const mapperConfig = { ...DEFAULT_MAPPER_CONFIG, ...this.config.mapper };
179
+ const retrieverConfig = { ...DEFAULT_RETRIEVER_CONFIG, ...this.config.retriever };
180
+ const readerConfig = { ...DEFAULT_READER_CONFIG, ...this.config.reader };
181
+ const evaluatorConfig = { ...DEFAULT_EVALUATOR_CONFIG, ...this.config.evaluator };
182
+
183
+ // Use custom retriever if provided, otherwise create default
184
+ const retriever =
185
+ this.config.customRetriever ?? new Retriever(this.embeddings, retrieverConfig);
186
+ const reader = new Reader(this.llm, readerConfig);
187
+ const evaluator = new Evaluator(evaluatorConfig, this.llm);
188
+
189
+ // Initialize optional Milestone 2 components
190
+ const keyExpander = this.config.keyExpansion?.enabled
191
+ ? new KeyExpander({ ...this.config.keyExpansion, llm: this.llm })
192
+ : null;
193
+ const temporalAnalyzer = this.config.temporal?.enabled
194
+ ? new TemporalAnalyzer({ ...this.config.temporal, llm: this.llm })
195
+ : null;
196
+
197
+ // Process each instance
198
+ const results: BenchmarkResult[] = [];
199
+ const details: InstanceDetail[] = [];
200
+ const perQueryLatencies: number[] = [];
201
+ const total = instances.length;
202
+
203
+ for (let i = 0; i < instances.length; i++) {
204
+ const instance = instances[i];
205
+ const queryStartTime = Date.now();
206
+
207
+ // Stage 2: Map and index
208
+ onProgress?.({
209
+ stage: "indexing",
210
+ current: i + 1,
211
+ total,
212
+ message: `Indexing instance ${i + 1}/${total}`,
213
+ });
214
+
215
+ const mapped = mapInstance(instance, mapperConfig);
216
+
217
+ // Apply key expansion if enabled (Milestone 2)
218
+ let documentsToIndex: EngramDocument[] = mapped.documents;
219
+ if (keyExpander) {
220
+ const expanded = await keyExpander.expandBatch(mapped.documents);
221
+ documentsToIndex = expanded;
222
+ }
223
+
224
+ await retriever.indexInstance({ ...mapped, documents: documentsToIndex });
225
+
226
+ // Stage 3: Retrieve
227
+ onProgress?.({
228
+ stage: "retrieving",
229
+ current: i + 1,
230
+ total,
231
+ message: `Retrieving for ${instance.questionId}`,
232
+ });
233
+
234
+ // Apply temporal analysis if enabled (Milestone 2)
235
+ let queryForRetrieval = instance.question;
236
+ let temporalTimeRange: { start: Date; end: Date } | undefined;
237
+
238
+ if (temporalAnalyzer) {
239
+ const temporalAnalysis = await temporalAnalyzer.analyze(
240
+ instance.question,
241
+ instance.questionDate,
242
+ );
243
+ queryForRetrieval = temporalAnalysis.expandedQuery;
244
+ temporalTimeRange = temporalAnalysis.timeRange;
245
+ }
246
+
247
+ let retrieved = await retriever.retrieve(queryForRetrieval, instance.questionDate);
248
+
249
+ // Apply temporal filtering if we have a time range
250
+ if (temporalTimeRange && retrieved.documents.length > 0) {
251
+ const filtered = filterByTimeRange(retrieved.documents, temporalTimeRange);
252
+ // Only use filtered if we have enough results
253
+ if (filtered.length >= Math.min(3, retrieved.documents.length / 2)) {
254
+ retrieved = {
255
+ ...retrieved,
256
+ documents: filtered,
257
+ retrievedIds: filtered.map((d) => d.id),
258
+ scores: retrieved.scores.slice(0, filtered.length),
259
+ };
260
+ }
261
+ }
262
+
263
+ const retrievalMetrics = computeRetrievalMetrics(retrieved, mapped.evidenceDocIds);
264
+
265
+ // Debug callback for retrieval analysis
266
+ if (this.config.onRetrievalDebug) {
267
+ const evidenceDocs = mapped.documents
268
+ .filter((d) => mapped.evidenceDocIds.includes(d.id))
269
+ .map((d) => ({ id: d.id, content: d.content, sessionId: d.sessionId }));
270
+
271
+ const retrievedDocs = retrieved.documents.map((d, idx) => ({
272
+ id: d.id,
273
+ content: d.content,
274
+ score: retrieved.scores[idx] ?? 0,
275
+ isEvidence: mapped.evidenceDocIds.includes(d.id),
276
+ }));
277
+
278
+ this.config.onRetrievalDebug({
279
+ questionId: instance.questionId,
280
+ question: instance.question,
281
+ expectedAnswer: instance.answer,
282
+ evidenceDocIds: mapped.evidenceDocIds,
283
+ evidenceDocs,
284
+ retrievedDocs,
285
+ recall: retrievalMetrics.recall,
286
+ });
287
+ }
288
+
289
+ // Stage 4: Read/Generate answer
290
+ onProgress?.({
291
+ stage: "reading",
292
+ current: i + 1,
293
+ total,
294
+ message: `Generating answer for ${instance.questionId}`,
295
+ });
296
+
297
+ const readResult = await reader.read(
298
+ instance.question,
299
+ retrieved.documents,
300
+ instance.questionDate,
301
+ retrieved.scores,
302
+ );
303
+
304
+ // Compute query latency (indexing + retrieval + reading)
305
+ const queryLatencyMs = Date.now() - queryStartTime;
306
+ perQueryLatencies.push(queryLatencyMs);
307
+
308
+ // Store result
309
+ results.push({
310
+ questionId: instance.questionId,
311
+ hypothesis: readResult.hypothesis,
312
+ });
313
+
314
+ // Store detail
315
+ details.push({
316
+ questionId: instance.questionId,
317
+ question: instance.question,
318
+ answer: instance.answer,
319
+ hypothesis: readResult.hypothesis,
320
+ correct: false, // Will be set during evaluation
321
+ retrievedCount: retrieved.documents.length,
322
+ evidenceRetrieved: mapped.evidenceDocIds.filter((id) => retrieved.retrievedIds.includes(id))
323
+ .length,
324
+ retrievalRecall: retrievalMetrics.recall,
325
+ latencyMs: queryLatencyMs,
326
+ });
327
+
328
+ // Clear index for next instance
329
+ retriever.clear();
330
+ }
331
+
332
+ // Stage 5: Evaluate
333
+ onProgress?.({
334
+ stage: "evaluating",
335
+ current: 0,
336
+ total: 1,
337
+ message: "Evaluating results...",
338
+ });
339
+
340
+ const { evaluated, metrics } = await evaluator.evaluateAll(results, instances);
341
+
342
+ // Update details with evaluation results
343
+ for (const evalResult of evaluated) {
344
+ const detail = details.find((d) => d.questionId === evalResult.questionId);
345
+ if (detail) {
346
+ detail.correct = evalResult.correct;
347
+ }
348
+ }
349
+
350
+ // Add retrieval metrics
351
+ const avgRetrievalRecall =
352
+ details.reduce((sum, d) => sum + d.retrievalRecall, 0) / details.length;
353
+ metrics.retrieval = {
354
+ turnRecall: avgRetrievalRecall,
355
+ sessionRecall: avgRetrievalRecall, // Simplified for MVP
356
+ recallAtK: { 1: 0, 5: 0, 10: avgRetrievalRecall }, // Simplified for MVP
357
+ ndcgAtK: { 1: 0, 5: 0, 10: avgRetrievalRecall }, // Simplified for MVP
358
+ mrr: avgRetrievalRecall, // Simplified for MVP
359
+ };
360
+
361
+ onProgress?.({
362
+ stage: "evaluating",
363
+ current: 1,
364
+ total: 1,
365
+ message: "Evaluation complete",
366
+ });
367
+
368
+ // Compute latency metrics
369
+ const totalDurationMs = Date.now() - pipelineStartTime;
370
+ const latency = computeLatencyMetrics(perQueryLatencies, totalDurationMs);
371
+
372
+ return {
373
+ results,
374
+ metrics,
375
+ report: formatMetricsReport(metrics),
376
+ jsonl: resultsToJsonl(results),
377
+ details,
378
+ latency,
379
+ };
380
+ }
381
+ }
382
+
383
+ /**
384
+ * Compute latency percentiles from an array of latencies
385
+ */
386
+ function computeLatencyMetrics(latencies: number[], totalDurationMs: number): LatencyMetrics {
387
+ if (latencies.length === 0) {
388
+ return {
389
+ perQueryLatencies: [],
390
+ p50: 0,
391
+ p95: 0,
392
+ p99: 0,
393
+ mean: 0,
394
+ totalDurationMs,
395
+ };
396
+ }
397
+
398
+ const sorted = [...latencies].sort((a, b) => a - b);
399
+ const len = sorted.length;
400
+
401
+ // Compute percentile indices
402
+ const p50Index = Math.floor(len * 0.5);
403
+ const p95Index = Math.min(Math.floor(len * 0.95), len - 1);
404
+ const p99Index = Math.min(Math.floor(len * 0.99), len - 1);
405
+
406
+ // Compute mean
407
+ const sum = latencies.reduce((acc, val) => acc + val, 0);
408
+ const mean = sum / len;
409
+
410
+ return {
411
+ perQueryLatencies: latencies,
412
+ p50: sorted[p50Index],
413
+ p95: sorted[p95Index],
414
+ p99: sorted[p99Index],
415
+ mean: Math.round(mean),
416
+ totalDurationMs,
417
+ };
418
+ }
419
+
420
+ /**
421
+ * Quick evaluation of existing results file
422
+ */
423
+ export async function evaluateResults(
424
+ resultsPath: string,
425
+ datasetPath: string,
426
+ llm?: LLMProvider,
427
+ ): Promise<{ metrics: EvaluationMetrics; report: string }> {
428
+ const { readFile } = await import("node:fs/promises");
429
+
430
+ // Load results
431
+ const resultsContent = await readFile(resultsPath, "utf-8");
432
+ const { parseJsonlResults } = await import("./evaluator.js");
433
+ const results = parseJsonlResults(resultsContent);
434
+
435
+ // Load dataset
436
+ const { instances } = await loadDataset({ datasetPath });
437
+
438
+ // Evaluate
439
+ const evaluator = new Evaluator({ useLLMEvaluation: !!llm }, llm);
440
+ const { metrics } = await evaluator.evaluateAll(results, instances);
441
+
442
+ return {
443
+ metrics,
444
+ report: formatMetricsReport(metrics),
445
+ };
446
+ }
packages/benchmark/src/longmemeval/providers/anthropic-provider.ts ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { LLMOptions, LLMProvider, LLMResponse } from "../reader.js";
2
+
3
+ /**
4
+ * Configuration for the Anthropic LLM provider
5
+ */
6
+ export interface AnthropicProviderConfig {
7
+ /** Anthropic API key (defaults to ANTHROPIC_API_KEY env var) */
8
+ apiKey?: string;
9
+ /** Model to use */
10
+ model: string;
11
+ /** Maximum tokens for response */
12
+ maxTokens: number;
13
+ }
14
+
15
+ const DEFAULT_CONFIG: AnthropicProviderConfig = {
16
+ model: "claude-sonnet-4-20250514",
17
+ maxTokens: 1024,
18
+ };
19
+
20
+ /**
21
+ * Anthropic Claude provider for LLM operations
22
+ *
23
+ * Used for:
24
+ * - Answer generation (reading stage)
25
+ * - LLM-based evaluation (QA correctness)
26
+ * - Fact extraction (key expansion)
27
+ */
28
+ export class AnthropicProvider implements LLMProvider {
29
+ private config: AnthropicProviderConfig;
30
+ private client: AnthropicClient | null = null;
31
+
32
+ constructor(config: Partial<AnthropicProviderConfig> = {}) {
33
+ this.config = { ...DEFAULT_CONFIG, ...config };
34
+ }
35
+
36
+ /**
37
+ * Initialize the Anthropic client (lazy loading)
38
+ */
39
+ private async getClient(): Promise<AnthropicClient> {
40
+ if (this.client) {
41
+ return this.client;
42
+ }
43
+
44
+ const apiKey = this.config.apiKey ?? process.env.ANTHROPIC_API_KEY;
45
+
46
+ if (!apiKey) {
47
+ throw new Error(
48
+ "Anthropic API key required. Set ANTHROPIC_API_KEY environment variable or pass apiKey in config.",
49
+ );
50
+ }
51
+
52
+ try {
53
+ // Try to import the Anthropic SDK
54
+ const { default: Anthropic } = await import("@anthropic-ai/sdk");
55
+ this.client = new Anthropic({ apiKey }) as unknown as AnthropicClient;
56
+ } catch {
57
+ throw new Error("@anthropic-ai/sdk not installed. Run: npm install @anthropic-ai/sdk");
58
+ }
59
+
60
+ return this.client;
61
+ }
62
+
63
+ /**
64
+ * Generate a completion
65
+ */
66
+ async complete(prompt: string, options?: LLMOptions): Promise<LLMResponse> {
67
+ const client = await this.getClient();
68
+
69
+ const response = await client.messages.create({
70
+ model: this.config.model,
71
+ max_tokens: options?.maxTokens ?? this.config.maxTokens,
72
+ messages: [{ role: "user", content: prompt }],
73
+ });
74
+
75
+ // Extract text from response
76
+ const textContent = response.content.find((block: { type: string }) => block.type === "text") as
77
+ | { text: string }
78
+ | undefined;
79
+
80
+ return {
81
+ text: textContent?.text ?? "",
82
+ usage: {
83
+ inputTokens: response.usage.input_tokens,
84
+ outputTokens: response.usage.output_tokens,
85
+ },
86
+ };
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Interface for Anthropic client (to avoid importing types)
92
+ */
93
+ interface AnthropicClient {
94
+ messages: {
95
+ create(params: {
96
+ model: string;
97
+ max_tokens: number;
98
+ messages: Array<{ role: string; content: string }>;
99
+ }): Promise<{
100
+ content: Array<{ type: string; text?: string }>;
101
+ usage: { input_tokens: number; output_tokens: number };
102
+ }>;
103
+ };
104
+ }
105
+
106
+ /**
107
+ * OpenAI-compatible provider for LLM operations
108
+ *
109
+ * Works with OpenAI API or compatible endpoints (e.g., Ollama, vLLM)
110
+ */
111
+ export class OpenAICompatibleProvider implements LLMProvider {
112
+ private baseUrl: string;
113
+ private apiKey: string;
114
+ private model: string;
115
+
116
+ constructor(
117
+ config: {
118
+ baseUrl?: string;
119
+ apiKey?: string;
120
+ model?: string;
121
+ } = {},
122
+ ) {
123
+ this.baseUrl = config.baseUrl ?? "https://api.openai.com/v1";
124
+ this.apiKey = config.apiKey ?? process.env.OPENAI_API_KEY ?? "";
125
+ this.model = config.model ?? "gpt-5-mini";
126
+ }
127
+
128
+ async complete(prompt: string, options?: LLMOptions): Promise<LLMResponse> {
129
+ // GPT-5+ models use max_completion_tokens instead of max_tokens, and don't support temperature
130
+ const isGpt5Plus = this.model.startsWith("gpt-5") || this.model.startsWith("gpt-5.");
131
+ const maxTokensParam = isGpt5Plus ? "max_completion_tokens" : "max_tokens";
132
+
133
+ const requestBody: Record<string, unknown> = {
134
+ model: this.model,
135
+ messages: [{ role: "user", content: prompt }],
136
+ [maxTokensParam]: options?.maxTokens ?? 4096,
137
+ };
138
+
139
+ // GPT-5 mini doesn't support temperature parameter
140
+ if (!isGpt5Plus) {
141
+ requestBody.temperature = options?.temperature ?? 0.1;
142
+ }
143
+
144
+ const response = await fetch(`${this.baseUrl}/chat/completions`, {
145
+ method: "POST",
146
+ headers: {
147
+ "Content-Type": "application/json",
148
+ Authorization: `Bearer ${this.apiKey}`,
149
+ },
150
+ body: JSON.stringify(requestBody),
151
+ });
152
+
153
+ if (!response.ok) {
154
+ const errorBody = await response.text();
155
+ throw new Error(`OpenAI API error: ${response.status} ${response.statusText} - ${errorBody}`);
156
+ }
157
+
158
+ const data = (await response.json()) as OpenAIResponse;
159
+
160
+ return {
161
+ text: data.choices[0]?.message?.content ?? "",
162
+ usage: data.usage
163
+ ? {
164
+ inputTokens: data.usage.prompt_tokens,
165
+ outputTokens: data.usage.completion_tokens,
166
+ }
167
+ : undefined,
168
+ };
169
+ }
170
+ }
171
+
172
+ interface OpenAIResponse {
173
+ choices: Array<{ message?: { content?: string } }>;
174
+ usage?: { prompt_tokens: number; completion_tokens: number };
175
+ }
176
+
177
+ /**
178
+ * Ollama provider for local LLM operations
179
+ */
180
+ export class OllamaProvider implements LLMProvider {
181
+ private baseUrl: string;
182
+ private model: string;
183
+
184
+ constructor(config: { baseUrl?: string; model: string }) {
185
+ this.baseUrl = config.baseUrl ?? "http://localhost:11434";
186
+ this.model = config.model;
187
+ }
188
+
189
+ async complete(prompt: string, options?: LLMOptions): Promise<LLMResponse> {
190
+ const response = await fetch(`${this.baseUrl}/api/generate`, {
191
+ method: "POST",
192
+ headers: { "Content-Type": "application/json" },
193
+ body: JSON.stringify({
194
+ model: this.model,
195
+ prompt,
196
+ stream: false,
197
+ options: {
198
+ temperature: options?.temperature ?? 0.1,
199
+ num_predict: options?.maxTokens ?? 1024,
200
+ },
201
+ }),
202
+ });
203
+
204
+ if (!response.ok) {
205
+ throw new Error(`Ollama API error: ${response.status} ${response.statusText}`);
206
+ }
207
+
208
+ const data = (await response.json()) as OllamaResponse;
209
+
210
+ return {
211
+ text: data.response ?? "",
212
+ usage: {
213
+ inputTokens: data.prompt_eval_count ?? 0,
214
+ outputTokens: data.eval_count ?? 0,
215
+ },
216
+ };
217
+ }
218
+ }
219
+
220
+ interface OllamaResponse {
221
+ response?: string;
222
+ prompt_eval_count?: number;
223
+ eval_count?: number;
224
+ }
225
+
226
+ /**
227
+ * Google Gemini provider for LLM operations
228
+ *
229
+ * Uses the @google/genai SDK (recommended as of 2025)
230
+ * Supports Gemini 2.5 Flash and other Gemini models
231
+ */
232
+ export class GeminiProvider implements LLMProvider {
233
+ private model: string;
234
+ private apiKey: string;
235
+ private client: GoogleGenAIClient | null = null;
236
+
237
+ constructor(
238
+ config: {
239
+ apiKey?: string;
240
+ model?: string;
241
+ } = {},
242
+ ) {
243
+ this.apiKey = config.apiKey ?? process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? "";
244
+ this.model = config.model ?? "gemini-3-flash-preview";
245
+ }
246
+
247
+ /**
248
+ * Initialize the Gemini client (lazy loading)
249
+ */
250
+ private async getClient(): Promise<GoogleGenAIClient> {
251
+ if (this.client) {
252
+ return this.client;
253
+ }
254
+
255
+ if (!this.apiKey) {
256
+ throw new Error(
257
+ "Gemini API key required. Set GOOGLE_GENERATIVE_AI_API_KEY environment variable.",
258
+ );
259
+ }
260
+
261
+ try {
262
+ // Dynamic import to handle optional dependency
263
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
264
+ const genaiModule = await import("@google/genai" as string);
265
+ const GoogleGenAI = genaiModule.GoogleGenAI;
266
+ this.client = new GoogleGenAI({ apiKey: this.apiKey }) as unknown as GoogleGenAIClient;
267
+ } catch {
268
+ throw new Error("@google/genai not installed. Run: npm install @google/genai");
269
+ }
270
+
271
+ return this.client;
272
+ }
273
+
274
+ async complete(prompt: string, options?: LLMOptions): Promise<LLMResponse> {
275
+ const client = await this.getClient();
276
+
277
+ const response = await client.models.generateContent({
278
+ model: this.model,
279
+ contents: prompt,
280
+ config: {
281
+ maxOutputTokens: options?.maxTokens ?? 4096,
282
+ temperature: options?.temperature ?? 0.1,
283
+ },
284
+ });
285
+
286
+ return {
287
+ text: response.text ?? "",
288
+ usage: response.usageMetadata
289
+ ? {
290
+ inputTokens: response.usageMetadata.promptTokenCount ?? 0,
291
+ outputTokens: response.usageMetadata.candidatesTokenCount ?? 0,
292
+ }
293
+ : undefined,
294
+ };
295
+ }
296
+ }
297
+
298
+ /**
299
+ * Interface for GoogleGenAI client (to avoid importing types)
300
+ */
301
+ interface GoogleGenAIClient {
302
+ models: {
303
+ generateContent(params: {
304
+ model: string;
305
+ contents: string;
306
+ config?: {
307
+ maxOutputTokens?: number;
308
+ temperature?: number;
309
+ topP?: number;
310
+ topK?: number;
311
+ };
312
+ }): Promise<{
313
+ text?: string;
314
+ usageMetadata?: {
315
+ promptTokenCount?: number;
316
+ candidatesTokenCount?: number;
317
+ totalTokenCount?: number;
318
+ };
319
+ }>;
320
+ };
321
+ }
packages/benchmark/src/longmemeval/providers/engram-provider.ts ADDED
@@ -0,0 +1,1274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { EngramDocument, MappedInstance } from "../mapper.js";
2
+ import type { EmbeddingProvider, RetrievalResult } from "../retriever.js";
3
+
4
+ /**
5
+ * Embedding model options for configurable embeddings.
6
+ */
7
+ export type EmbeddingModelOption =
8
+ | "e5-small"
9
+ | "e5-base"
10
+ | "e5-large"
11
+ | "gte-base"
12
+ | "gte-large"
13
+ | "bge-small"
14
+ | "bge-base"
15
+ | "bge-large";
16
+
17
+ /**
18
+ * Configuration for the Engram provider
19
+ */
20
+ export interface EngramProviderConfig {
21
+ /** Qdrant server URL */
22
+ qdrantUrl: string;
23
+ /** Collection name for benchmark data */
24
+ collectionName: string;
25
+ /** Enable hybrid search (dense + sparse with RRF) */
26
+ hybridSearch: boolean;
27
+ /** Use learned fusion weights instead of fixed RRF */
28
+ learnedFusion: boolean;
29
+ /** Path to fusion MLP ONNX model */
30
+ fusionModel: string;
31
+ /** Enable reranking */
32
+ rerank: boolean;
33
+ /** Reranker tier: fast, accurate, code, colbert, or llm */
34
+ rerankTier: "fast" | "accurate" | "code" | "colbert" | "llm";
35
+ /** Number of candidates to fetch before reranking */
36
+ rerankDepth: number;
37
+ /** Number of documents to return */
38
+ topK: number;
39
+ /** Enable multi-query expansion with RRF fusion */
40
+ multiQuery: boolean;
41
+ /** Number of query variations to generate */
42
+ multiQueryVariations: number;
43
+ /** Enable retrieval confidence abstention detection */
44
+ abstention: boolean;
45
+ /** Minimum retrieval score to proceed (0-1) */
46
+ abstentionThreshold: number;
47
+ /** Enable session-aware hierarchical retrieval */
48
+ sessionAware: boolean;
49
+ /** Number of sessions to retrieve in stage 1 */
50
+ topSessions: number;
51
+ /** Number of turns per session in stage 2 */
52
+ turnsPerSession: number;
53
+ /** Enable temporal query parsing */
54
+ temporalAware: boolean;
55
+ /** Minimum confidence to apply temporal filter (0-1) */
56
+ temporalConfidenceThreshold: number;
57
+ /** Embedding model to use */
58
+ embeddingModel: EmbeddingModelOption;
59
+ /** Reference date for temporal queries (defaults to question date) */
60
+ referenceDate?: Date;
61
+ }
62
+
63
+ const DEFAULT_CONFIG: EngramProviderConfig = {
64
+ qdrantUrl: "http://localhost:6333",
65
+ collectionName: "longmemeval_engram",
66
+ hybridSearch: true,
67
+ learnedFusion: false,
68
+ fusionModel: "models/fusion_mlp.onnx",
69
+ rerank: true,
70
+ rerankTier: "fast",
71
+ rerankDepth: 30,
72
+ topK: 10,
73
+ multiQuery: false,
74
+ multiQueryVariations: 3,
75
+ abstention: false,
76
+ abstentionThreshold: 0.3,
77
+ sessionAware: false,
78
+ topSessions: 5,
79
+ turnsPerSession: 3,
80
+ temporalAware: false,
81
+ temporalConfidenceThreshold: 0.5,
82
+ embeddingModel: "e5-small",
83
+ };
84
+
85
+ /**
86
+ * Full Engram retrieval pipeline using search-core
87
+ *
88
+ * Features:
89
+ * - Dense embeddings (E5-small, 384d)
90
+ * - Sparse embeddings (SPLADE)
91
+ * - Hybrid search with RRF fusion
92
+ * - ColBERT late interaction reranking
93
+ * - Cross-encoder reranking (fast/accurate/code tiers)
94
+ */
95
+ export class EngramRetriever {
96
+ private config: EngramProviderConfig;
97
+ private textEmbedder: TextEmbedderInterface | null = null;
98
+ private spladeEmbedder: SpladeEmbedderInterface | null = null;
99
+ private colbertEmbedder: ColBERTEmbedderInterface | null = null;
100
+ private reranker: RerankerInterface | null = null;
101
+ private colbertReranker: ColBERTRerankerInterface | null = null;
102
+ private client: QdrantClientInterface | null = null;
103
+ private indexed: boolean = false;
104
+ private documentEmbeddings: Map<string, Float32Array[]> = new Map(); // ColBERT embeddings cache
105
+ private xaiClient: XAIClientInterface | null = null; // For multi-query expansion
106
+ private abstentionDetector: AbstentionDetectorInterface | null = null;
107
+ private sessionSummarizer: SessionSummarizerInterface | null = null;
108
+ private sessionRetriever: SessionRetrieverInterface | null = null;
109
+ private llmProvider: LLMProviderInterface | null = null;
110
+ private temporalParser: TemporalParserInterface | null = null;
111
+ private learnedFusion: LearnedFusionInterface | null = null;
112
+ private embeddingDimensions: number = 384; // Default for e5-small
113
+
114
+ constructor(config: Partial<EngramProviderConfig> = {}) {
115
+ this.config = { ...DEFAULT_CONFIG, ...config };
116
+ }
117
+
118
+ /**
119
+ * Initialize all embedders and rerankers (lazy loading)
120
+ */
121
+ private async initialize(): Promise<void> {
122
+ if (this.textEmbedder) return;
123
+
124
+ try {
125
+ // Import search-core components
126
+ const searchCore = await import("@engram/search");
127
+
128
+ // Initialize embedders with configurable model
129
+ if (this.config.embeddingModel === "e5-small") {
130
+ // Use legacy TextEmbedder for backwards compatibility
131
+ this.textEmbedder = new searchCore.TextEmbedder() as unknown as TextEmbedderInterface;
132
+ this.embeddingDimensions = 384;
133
+ } else {
134
+ // Use configurable embedder for other models
135
+ const embedder = searchCore.createEmbedder({
136
+ model: this.config.embeddingModel,
137
+ sparse: this.config.hybridSearch,
138
+ });
139
+ this.textEmbedder = embedder as unknown as TextEmbedderInterface;
140
+ this.embeddingDimensions = embedder.dimensions;
141
+ console.log(`Using ${this.config.embeddingModel} embedder (${this.embeddingDimensions}d)`);
142
+ }
143
+
144
+ // Initialize temporal parser
145
+ if (this.config.temporalAware) {
146
+ this.temporalParser = new searchCore.TemporalQueryParser(
147
+ this.config.referenceDate,
148
+ ) as unknown as TemporalParserInterface;
149
+ }
150
+
151
+ if (this.config.hybridSearch) {
152
+ this.spladeEmbedder = new searchCore.SpladeEmbedder() as unknown as SpladeEmbedderInterface;
153
+ }
154
+
155
+ // Initialize learned fusion if enabled
156
+ if (this.config.learnedFusion) {
157
+ this.learnedFusion = new searchCore.LearnedFusion({
158
+ modelPath: this.config.fusionModel,
159
+ }) as unknown as LearnedFusionInterface;
160
+ console.log(` [Learned Fusion] Using model: ${this.config.fusionModel}`);
161
+ }
162
+
163
+ if (this.config.rerank && this.config.rerankTier === "colbert") {
164
+ const colbertEmb = new searchCore.ColBERTEmbedder();
165
+ this.colbertEmbedder = colbertEmb as unknown as ColBERTEmbedderInterface;
166
+ this.colbertReranker = new searchCore.ColBERTReranker(
167
+ colbertEmb,
168
+ ) as unknown as ColBERTRerankerInterface;
169
+ }
170
+
171
+ if (this.config.rerank && this.config.rerankTier !== "colbert") {
172
+ // Use BatchedReranker for cross-encoder tiers
173
+ this.reranker = searchCore.BatchedReranker.forTier(
174
+ this.config.rerankTier,
175
+ ) as unknown as RerankerInterface;
176
+ }
177
+
178
+ // Initialize Qdrant client
179
+ const { QdrantClient } = await import("@qdrant/js-client-rest");
180
+ this.client = new QdrantClient({ url: this.config.qdrantUrl }) as QdrantClientInterface;
181
+
182
+ // Initialize Google AI client for multi-query expansion
183
+ if (this.config.multiQuery) {
184
+ const { createGoogleGenerativeAI } = await import("@ai-sdk/google");
185
+ const { generateText } = await import("ai");
186
+ const googleProvider = createGoogleGenerativeAI();
187
+ this.xaiClient = {
188
+ chat: async (messages: Array<{ role: string; content: string }>) => {
189
+ const result = await generateText({
190
+ model: googleProvider("gemini-3-flash-preview"),
191
+ system: messages.find((m) => m.role === "system")?.content,
192
+ prompt: messages.find((m) => m.role === "user")?.content ?? "",
193
+ });
194
+ return result.text;
195
+ },
196
+ };
197
+ }
198
+
199
+ // Initialize abstention detector
200
+ if (this.config.abstention) {
201
+ const { AbstentionDetector } = await import("@engram/search");
202
+ this.abstentionDetector = new AbstentionDetector({
203
+ minRetrievalScore: this.config.abstentionThreshold,
204
+ }) as unknown as AbstentionDetectorInterface;
205
+ }
206
+
207
+ // Initialize session-aware components
208
+ if (this.config.sessionAware) {
209
+ // Create a simple LLM provider for summarization
210
+ const { SessionSummarizer, SessionAwareRetriever } = await import("@engram/search");
211
+ const { createGoogleGenerativeAI } = await import("@ai-sdk/google");
212
+ const { generateText } = await import("ai");
213
+
214
+ // Use Google AI via AI SDK as LLM provider for summarization
215
+ const googleProvider = createGoogleGenerativeAI();
216
+
217
+ this.llmProvider = {
218
+ complete: async (prompt: string) => {
219
+ const result = await generateText({
220
+ model: googleProvider("gemini-3-flash-preview"),
221
+ prompt,
222
+ });
223
+ return { text: result.text };
224
+ },
225
+ };
226
+
227
+ this.sessionSummarizer = new SessionSummarizer(
228
+ this.llmProvider,
229
+ ) as unknown as SessionSummarizerInterface;
230
+
231
+ // Session retriever will be initialized after collection setup
232
+ // Cast client to the expected type for SessionAwareRetriever
233
+ const sessionRetrieverInstance = new SessionAwareRetriever(
234
+ this.client as never,
235
+ {
236
+ topSessions: this.config.topSessions,
237
+ turnsPerSession: this.config.turnsPerSession,
238
+ finalTopK: this.config.topK,
239
+ sessionCollection: `${this.config.collectionName}_sessions`,
240
+ turnCollection: this.config.collectionName,
241
+ },
242
+ this.reranker as never,
243
+ );
244
+ this.sessionRetriever = sessionRetrieverInstance as unknown as SessionRetrieverInterface;
245
+
246
+ console.log(" [Session-Aware] Initialized session summarizer and retriever");
247
+ }
248
+ } catch (error) {
249
+ console.error("Failed to initialize Engram provider:", error);
250
+ throw new Error("@engram/search not available. Install it or use a different provider.");
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Ensure collection exists with proper multi-vector schema
256
+ */
257
+ async ensureCollection(): Promise<void> {
258
+ await this.initialize();
259
+ if (!this.client) throw new Error("Client not initialized");
260
+
261
+ try {
262
+ await this.client.getCollection(this.config.collectionName);
263
+ // Collection exists, delete it to start fresh for each benchmark instance
264
+ await this.client.deleteCollection(this.config.collectionName);
265
+ } catch {
266
+ // Collection doesn't exist, that's fine
267
+ }
268
+
269
+ // Create collection with multi-vector support
270
+ const vectorsConfig: Record<string, unknown> = {
271
+ dense: {
272
+ size: 384,
273
+ distance: "Cosine",
274
+ },
275
+ };
276
+
277
+ const sparseVectorsConfig: Record<string, unknown> = {};
278
+ if (this.config.hybridSearch) {
279
+ sparseVectorsConfig.sparse = {
280
+ index: {
281
+ on_disk: false,
282
+ },
283
+ };
284
+ }
285
+
286
+ await this.client.createCollection(this.config.collectionName, {
287
+ vectors: vectorsConfig,
288
+ sparse_vectors: Object.keys(sparseVectorsConfig).length > 0 ? sparseVectorsConfig : undefined,
289
+ });
290
+
291
+ // Create sessions collection for session-aware retrieval
292
+ if (this.config.sessionAware) {
293
+ const sessionsCollection = `${this.config.collectionName}_sessions`;
294
+ try {
295
+ await this.client.getCollection(sessionsCollection);
296
+ await this.client.deleteCollection(sessionsCollection);
297
+ } catch {
298
+ // Collection doesn't exist, that's fine
299
+ }
300
+
301
+ // Sessions collection uses text_dense vector for summary embeddings
302
+ await this.client.createCollection(sessionsCollection, {
303
+ vectors: {
304
+ text_dense: {
305
+ size: 384,
306
+ distance: "Cosine",
307
+ },
308
+ },
309
+ });
310
+ console.log(` [Session-Aware] Created sessions collection: ${sessionsCollection}`);
311
+ }
312
+ }
313
+
314
+ /**
315
+ * Index a mapped instance for retrieval (Retriever interface)
316
+ */
317
+ async indexInstance(mapped: MappedInstance): Promise<void> {
318
+ await this.index(mapped.documents);
319
+ }
320
+
321
+ /**
322
+ * Retrieve relevant documents for a question (Retriever interface)
323
+ * Uses session-aware retrieval, multi-query expansion, or standard search.
324
+ */
325
+ async retrieve(question: string, _questionDate?: Date): Promise<RetrievalResult> {
326
+ // Session-aware two-stage retrieval
327
+ if (this.config.sessionAware && this.sessionRetriever) {
328
+ return this.sessionAwareSearch(question);
329
+ }
330
+ // Multi-query expansion with RRF fusion
331
+ if (this.config.multiQuery && this.xaiClient) {
332
+ return this.multiQuerySearch(question, this.config.topK);
333
+ }
334
+ return this.search(question, this.config.topK);
335
+ }
336
+
337
+ /**
338
+ * Session-aware two-stage retrieval.
339
+ * Stage 1: Retrieve relevant sessions
340
+ * Stage 2: Retrieve turns within each session
341
+ */
342
+ private async sessionAwareSearch(query: string): Promise<RetrievalResult> {
343
+ if (!this.sessionRetriever) {
344
+ return this.search(query, this.config.topK);
345
+ }
346
+
347
+ try {
348
+ const results = await this.sessionRetriever.retrieve(query);
349
+
350
+ // Convert SessionAwareSearchResult to EngramDocument
351
+ const documents: EngramDocument[] = results.map((r) => {
352
+ const payload = r.payload;
353
+ return {
354
+ id: payload?.node_id ?? String(r.id),
355
+ instanceId: payload?.session_id ?? "",
356
+ sessionId: r.sessionId,
357
+ content: payload?.content ?? "",
358
+ validTime: new Date(payload?.timestamp ?? Date.now()),
359
+ metadata: {
360
+ questionId: payload?.session_id ?? "",
361
+ hasAnswer: false,
362
+ role: "combined" as const,
363
+ turnIndex: undefined,
364
+ sessionIndex: 0,
365
+ },
366
+ };
367
+ });
368
+
369
+ return {
370
+ documents,
371
+ scores: results.map((r) => r.score),
372
+ retrievedIds: documents.map((d) => d.id),
373
+ };
374
+ } catch (error) {
375
+ console.warn("[Session-Aware] Retrieval failed, falling back to standard search:", error);
376
+ return this.search(query, this.config.topK);
377
+ }
378
+ }
379
+
380
+ /**
381
+ * Multi-query search: expand query into variations and fuse results with RRF.
382
+ * Based on DMQR-RAG: Diverse Multi-Query Rewriting for RAG.
383
+ * @see https://arxiv.org/abs/2411.13154
384
+ */
385
+ private async multiQuerySearch(query: string, topK: number): Promise<RetrievalResult> {
386
+ await this.initialize();
387
+
388
+ try {
389
+ // Step 1: Expand query into variations
390
+ const variations = await this.expandQuery(query);
391
+ console.log(` [Multi-Query] Generated ${variations.length} query variations`);
392
+
393
+ // Step 2: Search with each variation in parallel
394
+ const perQueryLimit = Math.max(topK * 2, 20);
395
+ const allResults = await Promise.all(
396
+ variations.map((varQuery) => this.search(varQuery, perQueryLimit)),
397
+ );
398
+
399
+ // Step 3: Fuse results using RRF
400
+ const fused = this.rrfFusionResults(allResults, topK);
401
+
402
+ console.log(
403
+ ` [Multi-Query] Fused ${allResults.reduce((sum, r) => sum + r.documents.length, 0)} candidates into ${fused.documents.length} results`,
404
+ );
405
+
406
+ return fused;
407
+ } catch (error) {
408
+ console.warn("[Multi-Query] Expansion failed, falling back to single query:", error);
409
+ return this.search(query, topK);
410
+ }
411
+ }
412
+
413
+ /**
414
+ * Expand a query into multiple variations using LLM.
415
+ */
416
+ private async expandQuery(query: string): Promise<string[]> {
417
+ const variations: string[] = [query]; // Always include original
418
+
419
+ if (!this.xaiClient) {
420
+ return variations;
421
+ }
422
+
423
+ const systemPrompt = `You are a search query expansion expert. Given a user query, generate alternative search queries that will help retrieve relevant documents.
424
+
425
+ Rules:
426
+ - Generate queries that are semantically different but target the same information need
427
+ - Each query should emphasize different aspects or use different vocabulary
428
+ - Return ONLY a JSON array of query strings
429
+ - Example: ["query 1", "query 2", "query 3"]
430
+ - Do not include numbering, bullets, or markdown formatting`;
431
+
432
+ const userPrompt = `Generate ${this.config.multiQueryVariations} alternative search queries for:
433
+ "${query}"
434
+
435
+ Use these strategies:
436
+ - Paraphrase: Rephrase the query using different words and synonyms
437
+ - Keyword: Focus on key entities, names, and technical terms
438
+ - Step-back: Generalize to a broader concept or category
439
+
440
+ Return ONLY a JSON array of query strings. No explanations.`;
441
+
442
+ try {
443
+ const response = await this.xaiClient.chat([
444
+ { role: "system", content: systemPrompt },
445
+ { role: "user", content: userPrompt },
446
+ ]);
447
+
448
+ // Parse JSON array from response
449
+ const jsonMatch = response.match(/\[[\s\S]*\]/);
450
+ if (jsonMatch) {
451
+ const parsed = JSON.parse(jsonMatch[0]) as string[];
452
+ const validVariations = parsed
453
+ .filter((v) => typeof v === "string" && v.trim().length > 0 && v !== query)
454
+ .slice(0, this.config.multiQueryVariations);
455
+ variations.push(...validVariations);
456
+ }
457
+ } catch (error) {
458
+ console.warn("[Multi-Query] Query expansion parsing failed:", error);
459
+ }
460
+
461
+ return variations;
462
+ }
463
+
464
+ /**
465
+ * Fuse multiple RetrievalResults using Reciprocal Rank Fusion (RRF).
466
+ * RRF score = sum(1 / (k + rank_i)) across all result sets.
467
+ */
468
+ private rrfFusionResults(resultSets: RetrievalResult[], topK: number): RetrievalResult {
469
+ const k = 60; // RRF constant
470
+ const scoreMap = new Map<string, { document: EngramDocument; rrfScore: number }>();
471
+
472
+ for (const results of resultSets) {
473
+ for (let rank = 0; rank < results.documents.length; rank++) {
474
+ const doc = results.documents[rank];
475
+ const rrfScore = 1 / (k + rank + 1);
476
+
477
+ const existing = scoreMap.get(doc.id);
478
+ if (existing) {
479
+ existing.rrfScore += rrfScore;
480
+ } else {
481
+ scoreMap.set(doc.id, { document: doc, rrfScore });
482
+ }
483
+ }
484
+ }
485
+
486
+ // Sort by RRF score and return top K
487
+ const sorted = Array.from(scoreMap.values())
488
+ .sort((a, b) => b.rrfScore - a.rrfScore)
489
+ .slice(0, topK);
490
+
491
+ return {
492
+ documents: sorted.map((s) => s.document),
493
+ scores: sorted.map((s) => s.rrfScore),
494
+ retrievedIds: sorted.map((s) => s.document.id),
495
+ };
496
+ }
497
+
498
+ /**
499
+ * Index documents with dense, sparse, and optionally ColBERT embeddings
500
+ */
501
+ async index(documents: EngramDocument[]): Promise<void> {
502
+ await this.initialize();
503
+ if (!this.client || !this.textEmbedder) throw new Error("Not initialized");
504
+
505
+ await this.ensureCollection();
506
+
507
+ // Generate dense embeddings
508
+ const texts = documents.map((d) => d.content);
509
+ const denseEmbeddings = await Promise.all(
510
+ texts.map((text) => this.textEmbedder?.embed(text) ?? Promise.resolve(new Float32Array(384))),
511
+ );
512
+
513
+ // Generate sparse embeddings if hybrid search enabled
514
+ let sparseEmbeddings: SparseVector[] | null = null;
515
+ if (this.config.hybridSearch && this.spladeEmbedder) {
516
+ sparseEmbeddings = await Promise.all(
517
+ texts.map(
518
+ (text) =>
519
+ this.spladeEmbedder?.embed(text) ?? Promise.resolve({ indices: [], values: [] }),
520
+ ),
521
+ );
522
+ }
523
+
524
+ // Generate ColBERT embeddings if using ColBERT reranking
525
+ if (this.config.rerank && this.config.rerankTier === "colbert" && this.colbertEmbedder) {
526
+ for (const doc of documents) {
527
+ const colbertEmb = await this.colbertEmbedder.encodeDocument(doc.content);
528
+ this.documentEmbeddings.set(doc.id, colbertEmb);
529
+ }
530
+ }
531
+
532
+ // Prepare points for Qdrant
533
+ const points = documents.map((doc, i) => {
534
+ const embedding = denseEmbeddings[i] ?? new Float32Array(384);
535
+ const point: QdrantPoint = {
536
+ id: this.hashId(doc.id),
537
+ vector: {
538
+ dense: Array.from(embedding),
539
+ },
540
+ payload: {
541
+ doc_id: doc.id,
542
+ instance_id: doc.instanceId,
543
+ session_id: doc.sessionId,
544
+ content: doc.content,
545
+ valid_time: doc.validTime.toISOString(),
546
+ has_answer: doc.metadata.hasAnswer,
547
+ role: doc.metadata.role,
548
+ turn_index: doc.metadata.turnIndex,
549
+ session_index: doc.metadata.sessionIndex,
550
+ },
551
+ };
552
+
553
+ // Add sparse vector if available
554
+ if (sparseEmbeddings?.[i]) {
555
+ point.vector.sparse = sparseEmbeddings[i];
556
+ }
557
+
558
+ return point;
559
+ });
560
+
561
+ // Batch upsert with retry logic
562
+ const batchSize = 50; // Smaller batches to reduce memory pressure
563
+ for (let i = 0; i < points.length; i += batchSize) {
564
+ const batch = points.slice(i, i + batchSize);
565
+ if (!this.client) throw new Error("Client not initialized");
566
+ const client = this.client;
567
+ await this.retryOperation(() =>
568
+ client.upsert(this.config.collectionName, {
569
+ wait: true,
570
+ points: batch,
571
+ }),
572
+ );
573
+ }
574
+
575
+ // Index session summaries if session-aware is enabled
576
+ if (this.config.sessionAware && this.sessionSummarizer) {
577
+ await this.indexSessionSummaries(documents);
578
+ }
579
+
580
+ this.indexed = true;
581
+ }
582
+
583
+ /**
584
+ * Group documents by session and index session summaries
585
+ */
586
+ private async indexSessionSummaries(documents: EngramDocument[]): Promise<void> {
587
+ if (!this.client || !this.sessionSummarizer) return;
588
+
589
+ // Group documents by session
590
+ const sessionGroups = this.groupBySession(documents);
591
+ const sessionIds = Object.keys(sessionGroups);
592
+
593
+ console.log(` [Session-Aware] Generating summaries for ${sessionIds.length} sessions...`);
594
+
595
+ // Generate summaries for each session
596
+ const summaries = await Promise.all(
597
+ sessionIds.map(async (sessionId) => {
598
+ const docs = sessionGroups[sessionId];
599
+ // Convert EngramDocument to Turn format for SessionSummarizer
600
+ const turns = docs.map((doc) => ({
601
+ id: doc.id,
602
+ sessionId: doc.sessionId,
603
+ role: doc.metadata.role as "user" | "assistant" | "system",
604
+ content: doc.content,
605
+ timestamp: doc.validTime,
606
+ }));
607
+
608
+ try {
609
+ return await this.sessionSummarizer?.summarize(turns);
610
+ } catch (error) {
611
+ console.warn(` [Session-Aware] Failed to summarize session ${sessionId}:`, error);
612
+ return null;
613
+ }
614
+ }),
615
+ );
616
+
617
+ // Filter out failed summaries (type guard to narrow type)
618
+ const validSummaries = summaries.filter((s): s is NonNullable<typeof s> => s !== null);
619
+ console.log(` [Session-Aware] Generated ${validSummaries.length} session summaries`);
620
+
621
+ // Index summaries in sessions collection
622
+ const sessionsCollection = `${this.config.collectionName}_sessions`;
623
+ const sessionPoints = validSummaries.map((summary) => ({
624
+ id: this.hashId(summary.sessionId),
625
+ vector: {
626
+ text_dense: summary.embedding,
627
+ },
628
+ payload: {
629
+ session_id: summary.sessionId,
630
+ summary: summary.summary,
631
+ topics: summary.topics,
632
+ entities: summary.entities,
633
+ start_time: summary.startTime.toISOString(),
634
+ end_time: summary.endTime.toISOString(),
635
+ turn_count: summary.turnCount,
636
+ },
637
+ }));
638
+
639
+ // Batch upsert sessions
640
+ const client = this.client;
641
+ for (let i = 0; i < sessionPoints.length; i += 50) {
642
+ const batch = sessionPoints.slice(i, i + 50);
643
+ await this.retryOperation(() =>
644
+ client.upsert(sessionsCollection, {
645
+ wait: true,
646
+ points: batch,
647
+ }),
648
+ );
649
+ }
650
+
651
+ console.log(` [Session-Aware] Indexed ${sessionPoints.length} session summaries`);
652
+ }
653
+
654
+ /**
655
+ * Group documents by session ID
656
+ */
657
+ private groupBySession(docs: EngramDocument[]): Record<string, EngramDocument[]> {
658
+ const groups: Record<string, EngramDocument[]> = {};
659
+ for (const doc of docs) {
660
+ if (!groups[doc.sessionId]) {
661
+ groups[doc.sessionId] = [];
662
+ }
663
+ groups[doc.sessionId].push(doc);
664
+ }
665
+ // Sort each group by validTime
666
+ for (const sessionId of Object.keys(groups)) {
667
+ groups[sessionId].sort((a, b) => a.validTime.getTime() - b.validTime.getTime());
668
+ }
669
+ return groups;
670
+ }
671
+
672
+ /**
673
+ * Retry an operation with exponential backoff
674
+ */
675
+ private async retryOperation<T>(
676
+ operation: () => Promise<T>,
677
+ maxRetries = 3,
678
+ baseDelayMs = 100,
679
+ ): Promise<T> {
680
+ let lastError: Error | undefined;
681
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
682
+ try {
683
+ return await operation();
684
+ } catch (error) {
685
+ lastError = error as Error;
686
+ if (attempt < maxRetries - 1) {
687
+ const delay = baseDelayMs * 2 ** attempt;
688
+ await new Promise((resolve) => setTimeout(resolve, delay));
689
+ }
690
+ }
691
+ }
692
+ throw lastError;
693
+ }
694
+
695
+ /**
696
+ * Search with full Engram pipeline: hybrid retrieval + reranking
697
+ */
698
+ async search(query: string, topK: number): Promise<RetrievalResult> {
699
+ if (!this.indexed || !this.client || !this.textEmbedder) {
700
+ return { documents: [], scores: [], retrievedIds: [] };
701
+ }
702
+
703
+ try {
704
+ // Step 0: Parse temporal expressions if enabled
705
+ let semanticQuery = query;
706
+ let temporalFilter: TemporalFilterType | null = null;
707
+
708
+ if (this.temporalParser) {
709
+ const parsed = this.temporalParser.parse(query);
710
+ if (parsed.temporalFilter && parsed.confidence >= this.config.temporalConfidenceThreshold) {
711
+ semanticQuery = parsed.semanticQuery;
712
+ temporalFilter = parsed.temporalFilter;
713
+ console.log(
714
+ ` [Temporal] "${parsed.temporalFilter.expression}" → ` +
715
+ `${parsed.temporalFilter.after?.toISOString().split("T")[0] ?? "∞"} to ` +
716
+ `${parsed.temporalFilter.before?.toISOString().split("T")[0] ?? "∞"} ` +
717
+ `(conf: ${parsed.confidence.toFixed(2)})`,
718
+ );
719
+ }
720
+ }
721
+
722
+ // Step 1: Generate query embeddings (use semantic query without temporal)
723
+ const denseQuery = await this.textEmbedder.embedQuery(semanticQuery);
724
+ let sparseQuery: SparseVector | null = null;
725
+ if (this.config.hybridSearch && this.spladeEmbedder) {
726
+ try {
727
+ sparseQuery = await this.spladeEmbedder.embedQuery(semanticQuery);
728
+ } catch (error) {
729
+ // Fall back to dense-only if SPLADE fails
730
+ console.warn("SPLADE embedding failed, using dense-only:", error);
731
+ }
732
+ }
733
+
734
+ // Step 2: Retrieve candidates (fetch more for reranking)
735
+ const fetchLimit = this.config.rerank ? this.config.rerankDepth : topK;
736
+ let results: QdrantSearchResult[];
737
+
738
+ if (this.config.hybridSearch && sparseQuery) {
739
+ if (this.config.learnedFusion && this.learnedFusion) {
740
+ // Learned fusion: fetch dense and sparse separately, then fuse with predicted weights
741
+ results = await this.learnedFusionSearch(
742
+ query,
743
+ denseQuery,
744
+ sparseQuery,
745
+ fetchLimit,
746
+ temporalFilter,
747
+ );
748
+ } else {
749
+ // Standard hybrid search with fixed RRF fusion
750
+ results = await this.hybridSearch(denseQuery, sparseQuery, fetchLimit, temporalFilter);
751
+ }
752
+ } else {
753
+ // Dense-only search
754
+ results = await this.denseSearch(denseQuery, fetchLimit, temporalFilter);
755
+ }
756
+
757
+ // Step 3: Rerank if enabled
758
+ if (this.config.rerank && results.length > 0) {
759
+ try {
760
+ results = await this.rerank(query, results, topK);
761
+ } catch (error) {
762
+ // Fall back to retrieval results if reranking fails
763
+ console.warn("Reranking failed, using retrieval scores:", error);
764
+ results = results.slice(0, topK);
765
+ }
766
+ } else {
767
+ results = results.slice(0, topK);
768
+ }
769
+
770
+ // Step 4: Convert to EngramDocuments
771
+ const documents: EngramDocument[] = results.map((r) => {
772
+ const payload = r.payload as Record<string, unknown>;
773
+ return {
774
+ id: payload.doc_id as string,
775
+ instanceId: payload.instance_id as string,
776
+ sessionId: payload.session_id as string,
777
+ content: payload.content as string,
778
+ validTime: new Date(payload.valid_time as string),
779
+ metadata: {
780
+ questionId: payload.instance_id as string,
781
+ hasAnswer: payload.has_answer as boolean,
782
+ role: payload.role as "user" | "assistant" | "combined",
783
+ turnIndex: payload.turn_index as number | undefined,
784
+ sessionIndex: payload.session_index as number,
785
+ },
786
+ };
787
+ });
788
+
789
+ const retrievalResult: RetrievalResult = {
790
+ documents,
791
+ scores: results.map((r) => r.score),
792
+ retrievedIds: documents.map((d) => d.id),
793
+ };
794
+
795
+ // Apply abstention detection if enabled
796
+ if (this.abstentionDetector && results.length > 0) {
797
+ const abstentionResult = this.abstentionDetector.checkRetrievalConfidence(results);
798
+ retrievalResult.abstained = abstentionResult.shouldAbstain;
799
+ retrievalResult.abstentionReason = abstentionResult.reason;
800
+ retrievalResult.retrievalConfidence = abstentionResult.confidence;
801
+
802
+ if (abstentionResult.shouldAbstain) {
803
+ console.log(` [Abstention] ${abstentionResult.reason}: ${abstentionResult.details}`);
804
+ }
805
+ }
806
+
807
+ return retrievalResult;
808
+ } catch (error) {
809
+ console.error("Search failed:", error);
810
+ return { documents: [], scores: [], retrievedIds: [] };
811
+ }
812
+ }
813
+
814
+ /**
815
+ * Dense-only vector search with retry and optional temporal filter
816
+ */
817
+ private async denseSearch(
818
+ queryVector: number[] | Float32Array,
819
+ limit: number,
820
+ temporalFilter?: TemporalFilterType | null,
821
+ ): Promise<QdrantSearchResult[]> {
822
+ if (!this.client) return [];
823
+
824
+ const client = this.client;
825
+ const qdrantFilter = temporalFilter ? this.buildQdrantFilter(temporalFilter) : undefined;
826
+
827
+ return this.retryOperation(async () => {
828
+ const results = await client.search(this.config.collectionName, {
829
+ vector: { name: "dense", vector: Array.from(queryVector) },
830
+ limit,
831
+ with_payload: true,
832
+ filter: qdrantFilter,
833
+ });
834
+ return results ?? [];
835
+ });
836
+ }
837
+
838
+ /**
839
+ * Build Qdrant filter from temporal constraints
840
+ */
841
+ private buildQdrantFilter(filter: TemporalFilterType): Record<string, unknown> {
842
+ const conditions: Array<{ key: string; range: { gte?: string; lte?: string } }> = [];
843
+
844
+ if (filter.after) {
845
+ conditions.push({
846
+ key: "valid_time",
847
+ range: { gte: filter.after.toISOString() },
848
+ });
849
+ }
850
+
851
+ if (filter.before) {
852
+ conditions.push({
853
+ key: "valid_time",
854
+ range: { lte: filter.before.toISOString() },
855
+ });
856
+ }
857
+
858
+ return { must: conditions };
859
+ }
860
+
861
+ /**
862
+ * Hybrid search with RRF fusion (dense + sparse) and optional temporal filter
863
+ */
864
+ private async hybridSearch(
865
+ denseQuery: number[] | Float32Array,
866
+ sparseQuery: SparseVector,
867
+ limit: number,
868
+ temporalFilter?: TemporalFilterType | null,
869
+ ): Promise<QdrantSearchResult[]> {
870
+ if (!this.client) return [];
871
+
872
+ const qdrantFilter = temporalFilter ? this.buildQdrantFilter(temporalFilter) : undefined;
873
+
874
+ // Use Qdrant's native query API with prefetch for RRF
875
+ try {
876
+ const results = await this.client.query(this.config.collectionName, {
877
+ prefetch: [
878
+ {
879
+ query: Array.from(denseQuery),
880
+ using: "dense",
881
+ limit: limit * 2,
882
+ filter: qdrantFilter,
883
+ },
884
+ {
885
+ query: {
886
+ indices: sparseQuery.indices,
887
+ values: sparseQuery.values,
888
+ },
889
+ using: "sparse",
890
+ limit: limit * 2,
891
+ filter: qdrantFilter,
892
+ },
893
+ ],
894
+ query: { fusion: "rrf" },
895
+ limit,
896
+ with_payload: true,
897
+ });
898
+
899
+ return results.points || [];
900
+ } catch {
901
+ // Fall back to dense-only if hybrid fails
902
+ console.warn("Hybrid search failed, falling back to dense-only");
903
+ return this.denseSearch(denseQuery, limit, temporalFilter);
904
+ }
905
+ }
906
+
907
+ /**
908
+ * Learned fusion search: fetch dense and sparse separately, then use MLP-predicted weights
909
+ */
910
+ private async learnedFusionSearch(
911
+ query: string,
912
+ denseQuery: number[] | Float32Array,
913
+ sparseQuery: SparseVector,
914
+ limit: number,
915
+ temporalFilter?: TemporalFilterType | null,
916
+ ): Promise<QdrantSearchResult[]> {
917
+ if (!this.client || !this.learnedFusion) {
918
+ return this.hybridSearch(denseQuery, sparseQuery, limit, temporalFilter);
919
+ }
920
+
921
+ try {
922
+ // Fetch dense and sparse results separately
923
+ const denseResults = await this.denseSearch(denseQuery, limit * 2, temporalFilter);
924
+ const sparseResults = await this.sparseSearch(sparseQuery, limit * 2, temporalFilter);
925
+
926
+ // Convert to SearchResult format for LearnedFusion
927
+ const denseSearchResults = denseResults.map((r) => {
928
+ const payload = r.payload as Record<string, unknown>;
929
+ return {
930
+ id: payload.doc_id as string,
931
+ content: payload.content as string,
932
+ score: r.score,
933
+ };
934
+ });
935
+
936
+ const sparseSearchResults = sparseResults.map((r) => {
937
+ const payload = r.payload as Record<string, unknown>;
938
+ return {
939
+ id: payload.doc_id as string,
940
+ content: payload.content as string,
941
+ score: r.score,
942
+ };
943
+ });
944
+
945
+ // Use learned fusion to combine results
946
+ const fusedResults = await this.learnedFusion.fuse(
947
+ query,
948
+ denseSearchResults,
949
+ sparseSearchResults,
950
+ );
951
+
952
+ // Map back to QdrantSearchResult format
953
+ const resultMap = new Map<string, QdrantSearchResult>();
954
+ for (const r of denseResults) {
955
+ const payload = r.payload as Record<string, unknown>;
956
+ resultMap.set(payload.doc_id as string, r);
957
+ }
958
+ for (const r of sparseResults) {
959
+ const payload = r.payload as Record<string, unknown>;
960
+ if (!resultMap.has(payload.doc_id as string)) {
961
+ resultMap.set(payload.doc_id as string, r);
962
+ }
963
+ }
964
+
965
+ return fusedResults.slice(0, limit).map((f) => {
966
+ const original = resultMap.get(f.id);
967
+ if (!original) throw new Error(`Missing result for ${f.id}`);
968
+ return { ...original, score: f.score };
969
+ });
970
+ } catch (error) {
971
+ console.warn("Learned fusion failed, falling back to RRF:", error);
972
+ return this.hybridSearch(denseQuery, sparseQuery, limit, temporalFilter);
973
+ }
974
+ }
975
+
976
+ /**
977
+ * Sparse-only search
978
+ */
979
+ private async sparseSearch(
980
+ sparseQuery: SparseVector,
981
+ limit: number,
982
+ temporalFilter?: TemporalFilterType | null,
983
+ ): Promise<QdrantSearchResult[]> {
984
+ if (!this.client) return [];
985
+
986
+ const qdrantFilter = temporalFilter ? this.buildQdrantFilter(temporalFilter) : undefined;
987
+
988
+ try {
989
+ const results = await this.client.query(this.config.collectionName, {
990
+ query: {
991
+ indices: sparseQuery.indices,
992
+ values: sparseQuery.values,
993
+ },
994
+ using: "sparse",
995
+ limit,
996
+ with_payload: true,
997
+ filter: qdrantFilter,
998
+ });
999
+ return results.points || [];
1000
+ } catch {
1001
+ return [];
1002
+ }
1003
+ }
1004
+
1005
+ /**
1006
+ * Rerank results using configured reranker
1007
+ */
1008
+ private async rerank(
1009
+ query: string,
1010
+ results: QdrantSearchResult[],
1011
+ topK: number,
1012
+ ): Promise<QdrantSearchResult[]> {
1013
+ if (results.length === 0) return results;
1014
+
1015
+ try {
1016
+ if (this.config.rerankTier === "colbert" && this.colbertReranker) {
1017
+ // ColBERT late interaction reranking
1018
+ const candidates = results.map((r) => {
1019
+ const payload = r.payload as Record<string, unknown>;
1020
+ const docId = payload.doc_id as string;
1021
+ return {
1022
+ id: docId,
1023
+ content: payload.content as string,
1024
+ score: r.score,
1025
+ colbertEmbeddings: this.documentEmbeddings.get(docId),
1026
+ };
1027
+ });
1028
+
1029
+ const reranked = await this.colbertReranker.rerank(query, candidates, topK);
1030
+
1031
+ // Map back to QdrantSearchResult format
1032
+ return reranked.map((item) => {
1033
+ const original = results.find(
1034
+ (r) => (r.payload as Record<string, unknown>).doc_id === item.id,
1035
+ );
1036
+ if (!original) throw new Error(`Original result not found for ${item.id}`);
1037
+ return {
1038
+ ...original,
1039
+ score: item.score,
1040
+ };
1041
+ });
1042
+ } else if (this.reranker) {
1043
+ // Cross-encoder reranking
1044
+ const candidates = results.map((r) => {
1045
+ const payload = r.payload as Record<string, unknown>;
1046
+ return {
1047
+ id: payload.doc_id as string,
1048
+ content: payload.content as string,
1049
+ score: r.score,
1050
+ };
1051
+ });
1052
+
1053
+ const reranked = await this.reranker.rerank(query, candidates, topK);
1054
+
1055
+ // Map back to QdrantSearchResult format
1056
+ return reranked.map((item) => {
1057
+ const original = results.find(
1058
+ (r) => (r.payload as Record<string, unknown>).doc_id === item.id,
1059
+ );
1060
+ if (!original) throw new Error(`Original result not found for ${item.id}`);
1061
+ return {
1062
+ ...original,
1063
+ score: item.score,
1064
+ };
1065
+ });
1066
+ }
1067
+ } catch (error) {
1068
+ console.warn("Reranking failed, using retrieval scores:", error);
1069
+ }
1070
+
1071
+ return results.slice(0, topK);
1072
+ }
1073
+
1074
+ /**
1075
+ * Clear the collection and release resources
1076
+ */
1077
+ clear(): void {
1078
+ this.indexed = false;
1079
+ this.documentEmbeddings.clear();
1080
+ // Note: We don't delete the collection here as it will be recreated on next index
1081
+ // This avoids unnecessary Qdrant operations between instances
1082
+ }
1083
+
1084
+ /**
1085
+ * Generate numeric hash for Qdrant point ID
1086
+ */
1087
+ private hashId(id: string): number {
1088
+ let hash = 0;
1089
+ for (let i = 0; i < id.length; i++) {
1090
+ hash = (hash << 5) - hash + id.charCodeAt(i);
1091
+ hash = hash >>> 0;
1092
+ }
1093
+ return hash;
1094
+ }
1095
+ }
1096
+
1097
+ /**
1098
+ * Engram embedding provider (wrapper for compatibility)
1099
+ */
1100
+ export class EngramEmbeddingProvider implements EmbeddingProvider {
1101
+ readonly dimension = 384;
1102
+ private textEmbedder: TextEmbedderInterface | null = null;
1103
+
1104
+ async embed(texts: string[]): Promise<number[][]> {
1105
+ const embedder = await this.getEmbedder();
1106
+ return Promise.all(texts.map((text) => embedder.embed(text).then((v) => Array.from(v))));
1107
+ }
1108
+
1109
+ async embedQuery(text: string): Promise<number[]> {
1110
+ const embedder = await this.getEmbedder();
1111
+ const result = await embedder.embedQuery(text);
1112
+ return Array.from(result);
1113
+ }
1114
+
1115
+ private async getEmbedder(): Promise<TextEmbedderInterface> {
1116
+ if (this.textEmbedder) return this.textEmbedder;
1117
+
1118
+ try {
1119
+ const { TextEmbedder } = await import("@engram/search");
1120
+ this.textEmbedder = new TextEmbedder() as unknown as TextEmbedderInterface;
1121
+ } catch {
1122
+ throw new Error("@engram/search not available");
1123
+ }
1124
+
1125
+ return this.textEmbedder;
1126
+ }
1127
+ }
1128
+
1129
+ // Type interfaces for search-core components
1130
+ interface TextEmbedderInterface {
1131
+ embed(text: string): Promise<number[] | Float32Array>;
1132
+ embedQuery(text: string): Promise<number[] | Float32Array>;
1133
+ }
1134
+
1135
+ interface SpladeEmbedderInterface {
1136
+ embed(text: string): Promise<SparseVector>;
1137
+ embedQuery(text: string): Promise<SparseVector>;
1138
+ }
1139
+
1140
+ interface ColBERTEmbedderInterface {
1141
+ encodeDocument(text: string): Promise<Float32Array[]>;
1142
+ encodeQuery(text: string): Promise<Float32Array[]>;
1143
+ }
1144
+
1145
+ interface RerankerInterface {
1146
+ rerank(
1147
+ query: string,
1148
+ candidates: Array<{ id: string; content: string; score: number }>,
1149
+ topK: number,
1150
+ ): Promise<Array<{ id: string; content: string; score: number }>>;
1151
+ }
1152
+
1153
+ interface ColBERTRerankerInterface {
1154
+ rerank(
1155
+ query: string,
1156
+ candidates: Array<{
1157
+ id: string;
1158
+ content: string;
1159
+ score: number;
1160
+ colbertEmbeddings?: Float32Array[];
1161
+ }>,
1162
+ topK: number,
1163
+ ): Promise<Array<{ id: string; content: string; score: number }>>;
1164
+ }
1165
+
1166
+ interface SparseVector {
1167
+ indices: number[];
1168
+ values: number[];
1169
+ }
1170
+
1171
+ interface QdrantClientInterface {
1172
+ getCollection(name: string): Promise<unknown>;
1173
+ createCollection(name: string, config: unknown): Promise<unknown>;
1174
+ deleteCollection(name: string): Promise<unknown>;
1175
+ upsert(name: string, config: unknown): Promise<unknown>;
1176
+ search(name: string, config: unknown): Promise<QdrantSearchResult[]>;
1177
+ query(name: string, config: unknown): Promise<{ points?: QdrantSearchResult[] }>;
1178
+ }
1179
+
1180
+ interface QdrantPoint {
1181
+ id: number;
1182
+ vector: {
1183
+ dense: number[];
1184
+ sparse?: SparseVector;
1185
+ };
1186
+ payload: Record<string, unknown>;
1187
+ }
1188
+
1189
+ interface QdrantSearchResult {
1190
+ id: number | string;
1191
+ score: number;
1192
+ payload?: Record<string, unknown>;
1193
+ }
1194
+
1195
+ interface XAIClientInterface {
1196
+ chat(messages: Array<{ role: string; content: string }>): Promise<string>;
1197
+ }
1198
+
1199
+ interface AbstentionDetectorInterface {
1200
+ checkRetrievalConfidence(results: Array<{ score: number }>): {
1201
+ shouldAbstain: boolean;
1202
+ reason?: string;
1203
+ confidence: number;
1204
+ details?: string;
1205
+ };
1206
+ }
1207
+
1208
+ interface SessionSummarizerInterface {
1209
+ summarize(
1210
+ turns: Array<{
1211
+ id: string;
1212
+ sessionId: string;
1213
+ role: "user" | "assistant" | "system";
1214
+ content: string;
1215
+ timestamp: Date;
1216
+ }>,
1217
+ ): Promise<{
1218
+ sessionId: string;
1219
+ summary: string;
1220
+ topics: string[];
1221
+ entities: string[];
1222
+ startTime: Date;
1223
+ endTime: Date;
1224
+ turnCount: number;
1225
+ embedding: number[];
1226
+ }>;
1227
+ }
1228
+
1229
+ interface SessionRetrieverInterface {
1230
+ retrieve(query: string): Promise<
1231
+ Array<{
1232
+ id: string | number;
1233
+ score: number;
1234
+ sessionId: string;
1235
+ sessionSummary?: string;
1236
+ sessionScore?: number;
1237
+ payload?: {
1238
+ content?: string;
1239
+ node_id?: string;
1240
+ session_id?: string;
1241
+ timestamp?: number;
1242
+ };
1243
+ }>
1244
+ >;
1245
+ }
1246
+
1247
+ interface LLMProviderInterface {
1248
+ complete(prompt: string): Promise<{ text: string }>;
1249
+ }
1250
+
1251
+ interface TemporalFilterType {
1252
+ after?: Date;
1253
+ before?: Date;
1254
+ sortByRecency?: boolean;
1255
+ expression?: string;
1256
+ }
1257
+
1258
+ interface TemporalParserInterface {
1259
+ parse(query: string): {
1260
+ semanticQuery: string;
1261
+ temporalFilter: TemporalFilterType | null;
1262
+ confidence: number;
1263
+ };
1264
+ setReferenceDate(date: Date): void;
1265
+ }
1266
+
1267
+ interface LearnedFusionInterface {
1268
+ fuse(
1269
+ query: string,
1270
+ denseResults: Array<{ id: string; content: string; score: number }>,
1271
+ sparseResults: Array<{ id: string; content: string; score: number }>,
1272
+ rerankResults?: Array<{ id: string; content: string; score: number }>,
1273
+ ): Promise<Array<{ id: string; content: string; score: number }>>;
1274
+ }
packages/benchmark/src/longmemeval/providers/index.ts ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Provider integrations for LongMemEval benchmark
3
+ *
4
+ * These providers wrap Engram's search-core components for use in benchmarking.
5
+ * Includes LLM providers for Anthropic, OpenAI, Ollama, and Google Gemini.
6
+ */
7
+
8
+ export * from "./anthropic-provider.js";
9
+ // Re-export specific providers for convenience
10
+ export {
11
+ AnthropicProvider,
12
+ GeminiProvider,
13
+ OllamaProvider,
14
+ OpenAICompatibleProvider,
15
+ } from "./anthropic-provider.js";
16
+ export * from "./engram-provider.js";
17
+ export * from "./qdrant-provider.js";
packages/benchmark/src/longmemeval/providers/qdrant-provider.ts ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { QdrantClient } from "@qdrant/js-client-rest";
2
+ import type { EngramDocument } from "../mapper.js";
3
+ import type { EmbeddingProvider, RetrievalResult } from "../retriever.js";
4
+
5
+ /**
6
+ * Configuration for the Qdrant provider
7
+ */
8
+ export interface QdrantProviderConfig {
9
+ /** Qdrant server URL */
10
+ url: string;
11
+ /** Collection name for benchmark data */
12
+ collectionName: string;
13
+ /** Embedding model to use */
14
+ embeddingModel: "e5-small" | "e5-base" | "e5-large";
15
+ /** Whether to use hybrid search (dense + sparse) */
16
+ hybridSearch: boolean;
17
+ }
18
+
19
+ const DEFAULT_CONFIG: QdrantProviderConfig = {
20
+ url: "http://localhost:6333",
21
+ collectionName: "longmemeval_benchmark",
22
+ embeddingModel: "e5-small",
23
+ hybridSearch: true,
24
+ };
25
+
26
+ /**
27
+ * Embedding dimensions by model
28
+ */
29
+ const EMBEDDING_DIMENSIONS: Record<string, number> = {
30
+ "e5-small": 384,
31
+ "e5-base": 768,
32
+ "e5-large": 1024,
33
+ };
34
+
35
+ /**
36
+ * Qdrant-based embedding provider using HuggingFace transformers
37
+ *
38
+ * Uses @engram/search's TextEmbedder under the hood when available,
39
+ * otherwise falls back to a lightweight implementation.
40
+ */
41
+ export class QdrantEmbeddingProvider implements EmbeddingProvider {
42
+ readonly dimension: number;
43
+ private config: QdrantProviderConfig;
44
+ private embedder: TextEmbedderInterface | null = null;
45
+
46
+ constructor(config: Partial<QdrantProviderConfig> = {}) {
47
+ this.config = { ...DEFAULT_CONFIG, ...config };
48
+ this.dimension = EMBEDDING_DIMENSIONS[this.config.embeddingModel] ?? 384;
49
+ }
50
+
51
+ /**
52
+ * Initialize the embedder (lazy loading)
53
+ */
54
+ private async getEmbedder(): Promise<TextEmbedderInterface> {
55
+ if (this.embedder) {
56
+ return this.embedder;
57
+ }
58
+
59
+ try {
60
+ // Try to import from search-core
61
+ const { TextEmbedder } = await import("@engram/search");
62
+ this.embedder = new TextEmbedder() as unknown as TextEmbedderInterface;
63
+ } catch {
64
+ // Fall back to stub if search-core not available
65
+ console.warn("@engram/search not available, using stub embedder");
66
+ this.embedder = new StubTextEmbedder(this.dimension);
67
+ }
68
+
69
+ return this.embedder;
70
+ }
71
+
72
+ /**
73
+ * Generate embeddings for a batch of texts
74
+ */
75
+ async embed(texts: string[]): Promise<number[][]> {
76
+ const embedder = await this.getEmbedder();
77
+
78
+ // Embed in batches to avoid memory issues
79
+ const embeddings: number[][] = [];
80
+ const batchSize = 32;
81
+
82
+ for (let i = 0; i < texts.length; i += batchSize) {
83
+ const batch = texts.slice(i, i + batchSize);
84
+ const batchEmbeddings = await Promise.all(batch.map((text) => embedder.embed(text)));
85
+ embeddings.push(...batchEmbeddings);
86
+ }
87
+
88
+ return embeddings;
89
+ }
90
+
91
+ /**
92
+ * Generate embedding for a query
93
+ */
94
+ async embedQuery(text: string): Promise<number[]> {
95
+ const embedder = await this.getEmbedder();
96
+ return embedder.embedQuery(text);
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Interface for text embedders
102
+ */
103
+ interface TextEmbedderInterface {
104
+ embed(text: string): Promise<number[]>;
105
+ embedQuery(text: string): Promise<number[]>;
106
+ }
107
+
108
+ /**
109
+ * Stub embedder for when search-core is not available
110
+ */
111
+ class StubTextEmbedder implements TextEmbedderInterface {
112
+ private dimension: number;
113
+
114
+ constructor(dimension: number) {
115
+ this.dimension = dimension;
116
+ }
117
+
118
+ async embed(text: string): Promise<number[]> {
119
+ return this.generateEmbedding(text, "passage:");
120
+ }
121
+
122
+ async embedQuery(text: string): Promise<number[]> {
123
+ return this.generateEmbedding(text, "query:");
124
+ }
125
+
126
+ private generateEmbedding(text: string, prefix: string): number[] {
127
+ // Simple deterministic embedding based on text hash
128
+ const hash = this.hashString(prefix + text);
129
+ return Array.from({ length: this.dimension }, (_, i) => {
130
+ const x = Math.sin(hash + i) * 10000;
131
+ return x - Math.floor(x);
132
+ });
133
+ }
134
+
135
+ private hashString(str: string): number {
136
+ let hash = 0;
137
+ for (let i = 0; i < str.length; i++) {
138
+ hash = (hash << 5) - hash + str.charCodeAt(i);
139
+ hash = hash & hash;
140
+ }
141
+ return Math.abs(hash);
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Qdrant-based retriever with hybrid search support
147
+ */
148
+ export class QdrantRetriever {
149
+ private client: QdrantClient;
150
+ private config: QdrantProviderConfig;
151
+ private embedder: QdrantEmbeddingProvider;
152
+ private indexed: boolean = false;
153
+
154
+ constructor(config: Partial<QdrantProviderConfig> = {}) {
155
+ this.config = { ...DEFAULT_CONFIG, ...config };
156
+ this.client = new QdrantClient({ url: this.config.url });
157
+ this.embedder = new QdrantEmbeddingProvider(config);
158
+ }
159
+
160
+ /**
161
+ * Ensure collection exists with proper schema
162
+ */
163
+ async ensureCollection(): Promise<void> {
164
+ try {
165
+ await this.client.getCollection(this.config.collectionName);
166
+ } catch {
167
+ // Collection doesn't exist, create it
168
+ await this.client.createCollection(this.config.collectionName, {
169
+ vectors: {
170
+ dense: {
171
+ size: this.embedder.dimension,
172
+ distance: "Cosine",
173
+ },
174
+ },
175
+ });
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Index documents for retrieval
181
+ */
182
+ async index(documents: EngramDocument[]): Promise<void> {
183
+ await this.ensureCollection();
184
+
185
+ // Generate embeddings
186
+ const texts = documents.map((d) => d.content);
187
+ const embeddings = await this.embedder.embed(texts);
188
+
189
+ // Upsert to Qdrant
190
+ const points = documents.map((doc, i) => ({
191
+ id: this.hashId(doc.id),
192
+ vector: { dense: embeddings[i] },
193
+ payload: {
194
+ doc_id: doc.id,
195
+ instance_id: doc.instanceId,
196
+ session_id: doc.sessionId,
197
+ content: doc.content,
198
+ valid_time: doc.validTime.toISOString(),
199
+ has_answer: doc.metadata.hasAnswer,
200
+ role: doc.metadata.role,
201
+ turn_index: doc.metadata.turnIndex,
202
+ session_index: doc.metadata.sessionIndex,
203
+ },
204
+ }));
205
+
206
+ // Batch upsert
207
+ const batchSize = 100;
208
+ for (let i = 0; i < points.length; i += batchSize) {
209
+ const batch = points.slice(i, i + batchSize);
210
+ await this.client.upsert(this.config.collectionName, {
211
+ wait: true,
212
+ points: batch,
213
+ });
214
+ }
215
+
216
+ this.indexed = true;
217
+ }
218
+
219
+ /**
220
+ * Search for relevant documents
221
+ */
222
+ async search(query: string, topK: number): Promise<RetrievalResult> {
223
+ if (!this.indexed) {
224
+ return { documents: [], scores: [], retrievedIds: [] };
225
+ }
226
+
227
+ const queryVector = await this.embedder.embedQuery(query);
228
+
229
+ const results = await this.client.search(this.config.collectionName, {
230
+ vector: { name: "dense", vector: queryVector },
231
+ limit: topK,
232
+ with_payload: true,
233
+ });
234
+
235
+ const documents: EngramDocument[] = results.map((r) => {
236
+ const payload = r.payload as Record<string, unknown>;
237
+ return {
238
+ id: payload.doc_id as string,
239
+ instanceId: payload.instance_id as string,
240
+ sessionId: payload.session_id as string,
241
+ content: payload.content as string,
242
+ validTime: new Date(payload.valid_time as string),
243
+ metadata: {
244
+ questionId: payload.instance_id as string,
245
+ hasAnswer: payload.has_answer as boolean,
246
+ role: payload.role as "user" | "assistant" | "combined",
247
+ turnIndex: payload.turn_index as number | undefined,
248
+ sessionIndex: payload.session_index as number,
249
+ },
250
+ };
251
+ });
252
+
253
+ return {
254
+ documents,
255
+ scores: results.map((r) => r.score),
256
+ retrievedIds: documents.map((d) => d.id),
257
+ };
258
+ }
259
+
260
+ /**
261
+ * Clear the collection
262
+ */
263
+ async clear(): Promise<void> {
264
+ try {
265
+ await this.client.deleteCollection(this.config.collectionName);
266
+ this.indexed = false;
267
+ } catch {
268
+ // Collection might not exist
269
+ }
270
+ }
271
+
272
+ /**
273
+ * Generate numeric hash for Qdrant point ID
274
+ */
275
+ private hashId(id: string): number {
276
+ let hash = 0;
277
+ for (let i = 0; i < id.length; i++) {
278
+ hash = (hash << 5) - hash + id.charCodeAt(i);
279
+ hash = hash >>> 0; // Convert to unsigned
280
+ }
281
+ return hash;
282
+ }
283
+ }
packages/benchmark/src/longmemeval/reader.ts ADDED
@@ -0,0 +1,780 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { EngramDocument } from "./mapper.js";
2
+
3
+ /**
4
+ * Configuration for the reading/answer generation stage
5
+ */
6
+ export interface ReaderConfig {
7
+ /** Maximum tokens for context */
8
+ maxContextTokens: number;
9
+ /** Whether to use Chain-of-Note (improves QA by ~10 points) */
10
+ chainOfNote: boolean;
11
+ /** Whether to use enhanced Chain-of-Note with multi-step reasoning */
12
+ enhancedChainOfNote: boolean;
13
+ /** Whether to use structured JSON format for context */
14
+ structuredFormat: boolean;
15
+ /** Abstention confidence threshold (0-1, lower = more abstentions) */
16
+ abstentionThreshold: number;
17
+ /** Whether to use calibrated confidence scoring */
18
+ calibratedConfidence: boolean;
19
+ /** Whether to request JSON-structured output from LLM */
20
+ jsonOutput: boolean;
21
+ /** Enable three-layer abstention detection (Layer 2 + 3) */
22
+ abstentionDetection: boolean;
23
+ /** Enable NLI-based answer grounding check (Layer 2) - requires abstentionDetection */
24
+ abstentionNLI: boolean;
25
+ /** NLI entailment threshold for abstention (0-1) */
26
+ abstentionNLIThreshold: number;
27
+ }
28
+
29
+ /**
30
+ * Default reader configuration based on LongMemEval findings
31
+ */
32
+ export const DEFAULT_READER_CONFIG: ReaderConfig = {
33
+ maxContextTokens: 8000,
34
+ chainOfNote: true,
35
+ enhancedChainOfNote: true,
36
+ structuredFormat: true,
37
+ abstentionThreshold: 0.3,
38
+ calibratedConfidence: true,
39
+ jsonOutput: true,
40
+ abstentionDetection: false,
41
+ abstentionNLI: false,
42
+ abstentionNLIThreshold: 0.7,
43
+ };
44
+
45
+ /**
46
+ * Result of reading/answer generation
47
+ */
48
+ export interface ReadResult {
49
+ /** Generated answer */
50
+ hypothesis: string;
51
+ /** Chain-of-thought reasoning (if enabled) */
52
+ reasoning?: string;
53
+ /** Key information extracted from context (Chain-of-Note) */
54
+ keyInformation?: string[];
55
+ /** Confidence score for abstention (0-1, calibrated) */
56
+ confidence?: number;
57
+ /** Individual confidence signals for debugging */
58
+ confidenceSignals?: ConfidenceSignals;
59
+ /** Whether the model chose to abstain */
60
+ abstained: boolean;
61
+ /** Reason for abstention from AbstentionDetector */
62
+ abstentionReason?: "low_retrieval_score" | "no_score_gap" | "not_grounded" | "hedging_detected";
63
+ /** Original answer before abstention (if abstained) */
64
+ originalAnswer?: string;
65
+ }
66
+
67
+ /**
68
+ * Individual signals used to compute calibrated confidence
69
+ */
70
+ export interface ConfidenceSignals {
71
+ /** Whether relevant documents were found */
72
+ hasRelevantDocs: boolean;
73
+ /** Relevance score of top document (0-1) */
74
+ topDocRelevance: number;
75
+ /** Number of documents supporting the answer */
76
+ supportingDocCount: number;
77
+ /** Whether the question is answerable based on context */
78
+ questionAnswerable: boolean;
79
+ /** LLM's self-reported confidence (if available) */
80
+ llmConfidence?: number;
81
+ /** Whether abstention phrases were detected */
82
+ abstentionDetected: boolean;
83
+ }
84
+
85
+ /**
86
+ * Interface for LLM providers
87
+ */
88
+ export interface LLMProvider {
89
+ /** Generate a completion */
90
+ complete(prompt: string, options?: LLMOptions): Promise<LLMResponse>;
91
+ }
92
+
93
+ export interface LLMOptions {
94
+ temperature?: number;
95
+ maxTokens?: number;
96
+ stopSequences?: string[];
97
+ }
98
+
99
+ export interface LLMResponse {
100
+ text: string;
101
+ usage?: {
102
+ inputTokens: number;
103
+ outputTokens: number;
104
+ };
105
+ }
106
+
107
+ /**
108
+ * Interface for AbstentionDetector from @engram/search
109
+ */
110
+ interface AbstentionDetectorInterface {
111
+ checkHedgingPatterns(answer: string): {
112
+ shouldAbstain: boolean;
113
+ reason?: string;
114
+ confidence: number;
115
+ details?: string;
116
+ };
117
+ checkAnswerGrounding(
118
+ answer: string,
119
+ context: string,
120
+ ): Promise<{
121
+ shouldAbstain: boolean;
122
+ reason?: string;
123
+ confidence: number;
124
+ details?: string;
125
+ }>;
126
+ }
127
+
128
+ /**
129
+ * Reader class that generates answers from retrieved context
130
+ *
131
+ * Implements Milestone 3 optimizations:
132
+ * - Enhanced Chain-of-Note with multi-step reasoning
133
+ * - JSON-structured prompts for better parsing
134
+ * - Calibrated abstention confidence scoring
135
+ * - Three-layer abstention detection (Layer 2: NLI, Layer 3: Hedging)
136
+ */
137
+ export class Reader {
138
+ private config: ReaderConfig;
139
+ private llm: LLMProvider;
140
+ private abstentionDetector: AbstentionDetectorInterface | null = null;
141
+ private abstentionDetectorInitPromise: Promise<void> | null = null;
142
+
143
+ constructor(llm: LLMProvider, config?: Partial<ReaderConfig>) {
144
+ this.config = { ...DEFAULT_READER_CONFIG, ...config };
145
+ this.llm = llm;
146
+
147
+ // Initialize abstention detector if enabled
148
+ if (this.config.abstentionDetection) {
149
+ this.abstentionDetectorInitPromise = this.initAbstentionDetector();
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Initialize the AbstentionDetector from @engram/search
155
+ */
156
+ private async initAbstentionDetector(): Promise<void> {
157
+ try {
158
+ const { AbstentionDetector } = await import("@engram/search");
159
+ this.abstentionDetector = new AbstentionDetector({
160
+ useNLI: this.config.abstentionNLI,
161
+ nliThreshold: this.config.abstentionNLIThreshold,
162
+ }) as unknown as AbstentionDetectorInterface;
163
+ } catch (error) {
164
+ console.warn(
165
+ "[Reader] AbstentionDetector not available, disabling abstention detection:",
166
+ error,
167
+ );
168
+ this.abstentionDetector = null;
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Generate an answer given retrieved documents and a question
174
+ */
175
+ async read(
176
+ question: string,
177
+ documents: EngramDocument[],
178
+ questionDate?: Date,
179
+ retrievalScores?: number[],
180
+ ): Promise<ReadResult> {
181
+ // Wait for abstention detector initialization if in progress
182
+ if (this.abstentionDetectorInitPromise) {
183
+ await this.abstentionDetectorInitPromise;
184
+ }
185
+
186
+ const prompt = this.buildPrompt(question, documents, questionDate);
187
+
188
+ const response = await this.llm.complete(prompt, {
189
+ temperature: 0.1,
190
+ maxTokens: 1024,
191
+ });
192
+
193
+ const result = this.parseResponse(response.text, documents, retrievalScores);
194
+
195
+ // Apply abstention detection (Layers 2 & 3) if enabled and detector available
196
+ if (this.abstentionDetector && !result.abstained) {
197
+ const abstentionResult = await this.applyAbstentionDetection(
198
+ result.hypothesis,
199
+ documents.map((d) => d.content).join("\n\n"),
200
+ );
201
+
202
+ if (abstentionResult.shouldAbstain) {
203
+ return {
204
+ ...result,
205
+ hypothesis: "I don't have enough information to answer this question.",
206
+ abstained: true,
207
+ abstentionReason: abstentionResult.reason as ReadResult["abstentionReason"],
208
+ originalAnswer: result.hypothesis,
209
+ };
210
+ }
211
+ }
212
+
213
+ return result;
214
+ }
215
+
216
+ /**
217
+ * Apply Layer 2 (NLI) and Layer 3 (Hedging) abstention detection
218
+ */
219
+ private async applyAbstentionDetection(
220
+ answer: string,
221
+ context: string,
222
+ ): Promise<{ shouldAbstain: boolean; reason?: string; details?: string }> {
223
+ if (!this.abstentionDetector) {
224
+ return { shouldAbstain: false };
225
+ }
226
+
227
+ // Layer 3: Hedging pattern detection (sync, fast)
228
+ const hedgingResult = this.abstentionDetector.checkHedgingPatterns(answer);
229
+ if (hedgingResult.shouldAbstain) {
230
+ console.log(` [Abstention:Hedging] ${hedgingResult.details}`);
231
+ return hedgingResult;
232
+ }
233
+
234
+ // Layer 2: NLI answer grounding check (async, slower - only if NLI enabled)
235
+ if (this.config.abstentionNLI) {
236
+ const nliResult = await this.abstentionDetector.checkAnswerGrounding(answer, context);
237
+ if (nliResult.shouldAbstain) {
238
+ console.log(` [Abstention:NLI] ${nliResult.details}`);
239
+ return nliResult;
240
+ }
241
+ }
242
+
243
+ return { shouldAbstain: false };
244
+ }
245
+
246
+ /**
247
+ * Builds the prompt for answer generation
248
+ */
249
+ private buildPrompt(question: string, documents: EngramDocument[], questionDate?: Date): string {
250
+ const context = this.config.structuredFormat
251
+ ? this.formatAsJSON(documents)
252
+ : documents.map((d) => d.content).join("\n\n---\n\n");
253
+
254
+ const dateContext = questionDate
255
+ ? `Today's date: ${questionDate.toISOString().split("T")[0]}\n\n`
256
+ : "";
257
+
258
+ if (this.config.enhancedChainOfNote) {
259
+ return this.buildEnhancedChainOfNotePrompt(question, context, dateContext);
260
+ }
261
+
262
+ if (this.config.chainOfNote) {
263
+ return this.buildChainOfNotePrompt(question, context, dateContext);
264
+ }
265
+
266
+ return this.buildDirectPrompt(question, context, dateContext);
267
+ }
268
+
269
+ /**
270
+ * Format documents as JSON for structured context
271
+ */
272
+ private formatAsJSON(documents: EngramDocument[]): string {
273
+ const items = documents.map((doc, idx) => ({
274
+ index: idx + 1,
275
+ timestamp: doc.validTime.toISOString().split("T")[0],
276
+ role: doc.metadata.role,
277
+ content: doc.content,
278
+ sessionId: doc.sessionId,
279
+ }));
280
+
281
+ return JSON.stringify(items, null, 2);
282
+ }
283
+
284
+ /**
285
+ * Builds an enhanced Chain-of-Note prompt with multi-step reasoning
286
+ * Based on LongMemEval findings: +10 points QA accuracy
287
+ */
288
+ private buildEnhancedChainOfNotePrompt(
289
+ question: string,
290
+ context: string,
291
+ dateContext: string,
292
+ ): string {
293
+ const outputFormat = this.config.jsonOutput
294
+ ? `Respond in JSON format:
295
+ \`\`\`json
296
+ {
297
+ "key_information": ["fact1", "fact2", ...],
298
+ "reasoning_steps": ["step1", "step2", ...],
299
+ "answer": "your answer",
300
+ "confidence": 0.0-1.0,
301
+ "answerable": true/false
302
+ }
303
+ \`\`\``
304
+ : `### Key Information:
305
+ (List facts from conversation relevant to the question)
306
+
307
+ ### Reasoning Steps:
308
+ (Your step-by-step reasoning process)
309
+
310
+ ### Confidence:
311
+ (0.0 to 1.0 - how confident are you?)
312
+
313
+ ### Answerable:
314
+ (yes/no - is this answerable from the context?)
315
+
316
+ ### Answer:
317
+ (Your final answer - be direct and concise)`;
318
+
319
+ return `You are a memory assistant analyzing conversation history to answer questions.
320
+
321
+ ${dateContext}## Conversation History (JSON format)
322
+
323
+ ${context}
324
+
325
+ ## Task
326
+
327
+ Analyze the conversation history and answer the question below.
328
+
329
+ **Step-by-step approach:**
330
+ 1. EXTRACT: Identify all facts in the conversation that could be relevant to the question
331
+ 2. VERIFY: Check if the extracted facts directly answer the question or if information is missing
332
+ 3. REASON: If answerable, reason through the facts to derive the answer
333
+ 4. CONFIDENCE: Assess your confidence (1.0 = certain from direct evidence, 0.5 = inferred, 0.0 = cannot answer)
334
+ 5. ANSWER: Provide a direct, concise answer OR state you cannot answer
335
+
336
+ **Important:**
337
+ - Only use information explicitly stated in the conversation history
338
+ - If the question cannot be answered from the history, set confidence to 0 and answerable to false
339
+ - For temporal questions, pay attention to dates and time references
340
+ - For knowledge updates, use the most recent information
341
+
342
+ ## Question
343
+
344
+ ${question}
345
+
346
+ ## Response
347
+
348
+ ${outputFormat}`;
349
+ }
350
+
351
+ /**
352
+ * Builds a Chain-of-Note prompt (recommended by LongMemEval)
353
+ */
354
+ private buildChainOfNotePrompt(question: string, context: string, dateContext: string): string {
355
+ return `You are a helpful assistant with access to conversation history.
356
+
357
+ ${dateContext}## Retrieved Conversation History
358
+
359
+ ${context}
360
+
361
+ ## Task
362
+
363
+ Based on the conversation history above, answer the following question.
364
+
365
+ **Important Instructions:**
366
+ 1. First, extract the key information from the conversation history that is relevant to the question.
367
+ 2. Then, reason step by step to arrive at your answer.
368
+ 3. If the information needed to answer the question is not present in the history, respond with "I don't have that information."
369
+ 4. Be concise and direct in your final answer.
370
+
371
+ ## Question
372
+
373
+ ${question}
374
+
375
+ ## Response
376
+
377
+ ### Key Information Extracted:
378
+ (List the relevant facts from the conversation history)
379
+
380
+ ### Reasoning:
381
+ (Your step-by-step reasoning)
382
+
383
+ ### Answer:
384
+ (Your final answer - be direct and concise)`;
385
+ }
386
+
387
+ /**
388
+ * Builds a direct prompt without Chain-of-Note
389
+ */
390
+ private buildDirectPrompt(question: string, context: string, dateContext: string): string {
391
+ return `You are a helpful assistant with access to conversation history.
392
+
393
+ ${dateContext}## Retrieved Conversation History
394
+
395
+ ${context}
396
+
397
+ ## Question
398
+
399
+ ${question}
400
+
401
+ ## Instructions
402
+
403
+ Answer the question based on the conversation history above.
404
+ If the information is not available in the history, respond with "I don't have that information."
405
+ Be concise and direct.
406
+
407
+ ## Answer:`;
408
+ }
409
+
410
+ /**
411
+ * Parses the LLM response to extract the answer with calibrated confidence
412
+ */
413
+ private parseResponse(
414
+ text: string,
415
+ documents: EngramDocument[],
416
+ retrievalScores?: number[],
417
+ ): ReadResult {
418
+ // Try JSON parsing first
419
+ const jsonResult = this.parseJsonResponse(text);
420
+ if (jsonResult) {
421
+ const signals = this.computeConfidenceSignals(jsonResult, documents, retrievalScores, text);
422
+ const calibratedConfidence = this.config.calibratedConfidence
423
+ ? this.calibrateConfidence(signals)
424
+ : (jsonResult.confidence ?? (jsonResult.answerable ? 1 : 0));
425
+
426
+ return {
427
+ hypothesis: jsonResult.answer,
428
+ reasoning: jsonResult.reasoning_steps?.join(" → "),
429
+ keyInformation: jsonResult.key_information,
430
+ confidence: calibratedConfidence,
431
+ confidenceSignals: signals,
432
+ abstained: calibratedConfidence < this.config.abstentionThreshold,
433
+ };
434
+ }
435
+
436
+ // Fall back to markdown parsing
437
+ return this.parseMarkdownResponse(text, documents, retrievalScores);
438
+ }
439
+
440
+ /**
441
+ * Parse JSON-formatted response
442
+ */
443
+ private parseJsonResponse(text: string): JsonResponse | null {
444
+ try {
445
+ // Extract JSON from markdown code blocks
446
+ const jsonMatch = text.match(/```json\s*([\s\S]*?)\s*```/);
447
+ if (jsonMatch) {
448
+ return JSON.parse(jsonMatch[1]);
449
+ }
450
+
451
+ // Try parsing entire response as JSON
452
+ const directMatch = text.match(/\{[\s\S]*\}/);
453
+ if (directMatch) {
454
+ return JSON.parse(directMatch[0]);
455
+ }
456
+ } catch {
457
+ // JSON parsing failed, fall back to markdown
458
+ }
459
+ return null;
460
+ }
461
+
462
+ /**
463
+ * Parse markdown-formatted response (fallback)
464
+ */
465
+ private parseMarkdownResponse(
466
+ text: string,
467
+ documents: EngramDocument[],
468
+ retrievalScores?: number[],
469
+ ): ReadResult {
470
+ // Check for abstention phrases
471
+ const abstentionPhrases = [
472
+ "i don't have that information",
473
+ "i do not have that information",
474
+ "not mentioned in the conversation",
475
+ "no information about",
476
+ "cannot find",
477
+ "not available in the history",
478
+ "not present in the conversation",
479
+ "cannot answer",
480
+ "unable to answer",
481
+ ];
482
+
483
+ const lowerText = text.toLowerCase();
484
+ const abstentionDetected = abstentionPhrases.some((phrase) => lowerText.includes(phrase));
485
+
486
+ // Extract key information
487
+ let keyInformation: string[] | undefined;
488
+ const keyInfoMatch = text.match(/### Key Information[:\s]*([\s\S]*?)(?:\n###|$)/i);
489
+ if (keyInfoMatch) {
490
+ keyInformation = keyInfoMatch[1]
491
+ .split(/\n[-•*]\s*/)
492
+ .map((s) => s.trim())
493
+ .filter((s) => s.length > 0);
494
+ }
495
+
496
+ // Extract reasoning
497
+ let reasoning: string | undefined;
498
+ const reasoningMatch = text.match(
499
+ /### Reasoning(?:\s+Steps)?[:\s]*([\s\S]*?)(?:\n### (?:Answer|Confidence)|$)/i,
500
+ );
501
+ if (reasoningMatch) {
502
+ reasoning = reasoningMatch[1].trim();
503
+ }
504
+
505
+ // Extract confidence
506
+ let llmConfidence: number | undefined;
507
+ const confidenceMatch = text.match(/### Confidence[:\s]*(\d*\.?\d+)/i);
508
+ if (confidenceMatch) {
509
+ llmConfidence = Number.parseFloat(confidenceMatch[1]);
510
+ }
511
+
512
+ // Extract answerable
513
+ let questionAnswerable = true;
514
+ const answerableMatch = text.match(/### Answerable[:\s]*(yes|no|true|false)/i);
515
+ if (answerableMatch) {
516
+ questionAnswerable = ["yes", "true"].includes(answerableMatch[1].toLowerCase());
517
+ }
518
+
519
+ // Extract answer
520
+ let hypothesis = text;
521
+ const answerMatch = text.match(/### Answer[:\s]*([\s\S]*?)(?:\n###|$)/i);
522
+ if (answerMatch) {
523
+ hypothesis = answerMatch[1].trim();
524
+ }
525
+
526
+ // Clean up the hypothesis
527
+ hypothesis = hypothesis.trim();
528
+ if (hypothesis.includes("###")) {
529
+ hypothesis = hypothesis.split("###")[0].trim();
530
+ }
531
+
532
+ // Compute confidence signals
533
+ const signals: ConfidenceSignals = {
534
+ hasRelevantDocs: documents.length > 0,
535
+ topDocRelevance: retrievalScores?.[0] ?? 0,
536
+ supportingDocCount: documents.length,
537
+ questionAnswerable,
538
+ llmConfidence,
539
+ abstentionDetected,
540
+ };
541
+
542
+ const calibratedConfidence = this.config.calibratedConfidence
543
+ ? this.calibrateConfidence(signals)
544
+ : abstentionDetected
545
+ ? 0
546
+ : 1;
547
+
548
+ return {
549
+ hypothesis,
550
+ reasoning,
551
+ keyInformation,
552
+ confidence: calibratedConfidence,
553
+ confidenceSignals: signals,
554
+ abstained: calibratedConfidence < this.config.abstentionThreshold,
555
+ };
556
+ }
557
+
558
+ /**
559
+ * Compute confidence signals from various sources
560
+ */
561
+ private computeConfidenceSignals(
562
+ jsonResponse: JsonResponse,
563
+ documents: EngramDocument[],
564
+ retrievalScores?: number[],
565
+ rawText?: string,
566
+ ): ConfidenceSignals {
567
+ const lowerText = (rawText ?? "").toLowerCase();
568
+ const abstentionPhrases = [
569
+ "cannot answer",
570
+ "don't have",
571
+ "do not have",
572
+ "not available",
573
+ "not found",
574
+ ];
575
+
576
+ return {
577
+ hasRelevantDocs: documents.length > 0,
578
+ topDocRelevance: retrievalScores?.[0] ?? 0,
579
+ supportingDocCount: documents.length,
580
+ questionAnswerable: jsonResponse.answerable ?? true,
581
+ llmConfidence: jsonResponse.confidence,
582
+ abstentionDetected: abstentionPhrases.some((p) => lowerText.includes(p)),
583
+ };
584
+ }
585
+
586
+ /**
587
+ * Calibrate confidence using multiple signals
588
+ *
589
+ * Weighted combination based on LongMemEval findings:
590
+ * - LLM self-reported confidence is somewhat reliable
591
+ * - Retrieval score indicates evidence quality
592
+ * - Abstention detection catches explicit uncertainty
593
+ */
594
+ private calibrateConfidence(signals: ConfidenceSignals): number {
595
+ // If abstention explicitly detected, low confidence
596
+ if (signals.abstentionDetected) {
597
+ return 0.1;
598
+ }
599
+
600
+ // If question marked as unanswerable
601
+ if (!signals.questionAnswerable) {
602
+ return 0.15;
603
+ }
604
+
605
+ // If no relevant documents retrieved
606
+ if (!signals.hasRelevantDocs) {
607
+ return 0.2;
608
+ }
609
+
610
+ // Weighted combination of signals
611
+ const weights = {
612
+ llmConfidence: 0.4,
613
+ topDocRelevance: 0.3,
614
+ docCountScore: 0.2,
615
+ baseConfidence: 0.1,
616
+ };
617
+
618
+ // LLM confidence (default to 0.7 if not provided)
619
+ const llmScore = signals.llmConfidence ?? 0.7;
620
+
621
+ // Document relevance score (already 0-1)
622
+ const relevanceScore = signals.topDocRelevance;
623
+
624
+ // Document count score (more docs = higher confidence, capped)
625
+ const docCountScore = Math.min(signals.supportingDocCount / 5, 1);
626
+
627
+ // Base confidence (always some uncertainty)
628
+ const baseScore = 0.5;
629
+
630
+ const calibrated =
631
+ weights.llmConfidence * llmScore +
632
+ weights.topDocRelevance * relevanceScore +
633
+ weights.docCountScore * docCountScore +
634
+ weights.baseConfidence * baseScore;
635
+
636
+ // Clamp to 0-1 range
637
+ return Math.max(0, Math.min(1, calibrated));
638
+ }
639
+ }
640
+
641
+ /**
642
+ * JSON response structure from LLM
643
+ */
644
+ interface JsonResponse {
645
+ key_information?: string[];
646
+ reasoning_steps?: string[];
647
+ answer: string;
648
+ confidence?: number;
649
+ answerable?: boolean;
650
+ }
651
+
652
+ /**
653
+ * Stub LLM provider for testing - returns JSON-formatted responses
654
+ */
655
+ export class StubLLMProvider implements LLMProvider {
656
+ private responses: Map<string, string> = new Map();
657
+
658
+ /**
659
+ * Set a canned response for a question pattern
660
+ */
661
+ setResponse(questionPattern: string, response: string): void {
662
+ this.responses.set(questionPattern.toLowerCase(), response);
663
+ }
664
+
665
+ async complete(prompt: string): Promise<LLMResponse> {
666
+ // Extract the question from the prompt
667
+ const questionMatch = prompt.match(/## Question\s+([\s\S]*?)(?:\n##|$)/);
668
+ const question = questionMatch?.[1]?.trim() ?? "Unknown question";
669
+ const lowerQuestion = question.toLowerCase();
670
+
671
+ // Check for canned responses
672
+ for (const [pattern, response] of this.responses) {
673
+ if (lowerQuestion.includes(pattern)) {
674
+ return { text: response, usage: { inputTokens: 0, outputTokens: 0 } };
675
+ }
676
+ }
677
+
678
+ // Default JSON response indicating unable to answer
679
+ const jsonResponse = {
680
+ key_information: [],
681
+ reasoning_steps: ["No context provided", "Cannot determine answer"],
682
+ answer: `Unable to answer: "${question}"`,
683
+ confidence: 0.1,
684
+ answerable: false,
685
+ };
686
+
687
+ return {
688
+ text: `\`\`\`json\n${JSON.stringify(jsonResponse, null, 2)}\n\`\`\``,
689
+ usage: { inputTokens: 0, outputTokens: 0 },
690
+ };
691
+ }
692
+ }
693
+
694
+ /**
695
+ * Mock LLM provider for testing with configurable behavior
696
+ */
697
+ export class MockLLMProvider implements LLMProvider {
698
+ private fixedResponse: JsonResponse | null = null;
699
+ private confidenceOverride: number | null = null;
700
+
701
+ /**
702
+ * Set a fixed JSON response
703
+ */
704
+ setFixedResponse(response: JsonResponse): void {
705
+ this.fixedResponse = response;
706
+ }
707
+
708
+ /**
709
+ * Override confidence in responses
710
+ */
711
+ setConfidenceOverride(confidence: number): void {
712
+ this.confidenceOverride = confidence;
713
+ }
714
+
715
+ async complete(prompt: string): Promise<LLMResponse> {
716
+ if (this.fixedResponse) {
717
+ const response = { ...this.fixedResponse };
718
+ if (this.confidenceOverride !== null) {
719
+ response.confidence = this.confidenceOverride;
720
+ }
721
+ return {
722
+ text: `\`\`\`json\n${JSON.stringify(response, null, 2)}\n\`\`\``,
723
+ usage: { inputTokens: 0, outputTokens: 0 },
724
+ };
725
+ }
726
+
727
+ // Default behavior - extract question and return generic response
728
+ const questionMatch = prompt.match(/## Question\s+([\s\S]*?)(?:\n##|$)/);
729
+ const question = questionMatch?.[1]?.trim() ?? "Unknown question";
730
+
731
+ const response: JsonResponse = {
732
+ key_information: ["Extracted from context"],
733
+ reasoning_steps: ["Analyzed the question", "Found relevant information"],
734
+ answer: `Answer to: ${question}`,
735
+ confidence: this.confidenceOverride ?? 0.8,
736
+ answerable: true,
737
+ };
738
+
739
+ return {
740
+ text: `\`\`\`json\n${JSON.stringify(response, null, 2)}\n\`\`\``,
741
+ usage: { inputTokens: 0, outputTokens: 0 },
742
+ };
743
+ }
744
+ }
745
+
746
+ /**
747
+ * Simple embedding provider for testing (random embeddings)
748
+ */
749
+ export class StubEmbeddingProvider {
750
+ readonly dimension = 384;
751
+
752
+ async embed(texts: string[]): Promise<number[][]> {
753
+ // Generate deterministic pseudo-random embeddings based on text hash
754
+ return texts.map((text) => {
755
+ const seed = hashString(text);
756
+ return Array.from({ length: this.dimension }, (_, i) => seededRandom(seed + i));
757
+ });
758
+ }
759
+ }
760
+
761
+ /**
762
+ * Simple string hash function
763
+ */
764
+ function hashString(str: string): number {
765
+ let hash = 0;
766
+ for (let i = 0; i < str.length; i++) {
767
+ const char = str.charCodeAt(i);
768
+ hash = (hash << 5) - hash + char;
769
+ hash = hash & hash; // Convert to 32-bit integer
770
+ }
771
+ return Math.abs(hash);
772
+ }
773
+
774
+ /**
775
+ * Seeded random number generator
776
+ */
777
+ function seededRandom(seed: number): number {
778
+ const x = Math.sin(seed) * 10000;
779
+ return x - Math.floor(x);
780
+ }
packages/benchmark/src/longmemeval/retriever.ts ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { EngramDocument, MappedInstance } from "./mapper.js";
2
+
3
+ /**
4
+ * Configuration for the retrieval stage
5
+ */
6
+ export interface RetrieverConfig {
7
+ /** Retrieval method */
8
+ method: "dense" | "bm25" | "hybrid";
9
+ /** Number of documents to retrieve */
10
+ topK: number;
11
+ /** Time-aware query expansion (improves temporal reasoning by 7-11%) */
12
+ timeAwareExpansion: boolean;
13
+ /** Similarity threshold (0-1) */
14
+ similarityThreshold?: number;
15
+ }
16
+
17
+ /**
18
+ * Default retriever configuration
19
+ */
20
+ export const DEFAULT_RETRIEVER_CONFIG: RetrieverConfig = {
21
+ method: "dense",
22
+ topK: 10,
23
+ timeAwareExpansion: false,
24
+ similarityThreshold: 0.5,
25
+ };
26
+
27
+ /**
28
+ * Result of a retrieval operation
29
+ */
30
+ export interface RetrievalResult {
31
+ /** Retrieved documents */
32
+ documents: EngramDocument[];
33
+ /** Similarity scores for each document */
34
+ scores: number[];
35
+ /** IDs of retrieved documents */
36
+ retrievedIds: string[];
37
+ /** Time range extracted from query (if time-aware) */
38
+ extractedTimeRange?: { start: Date; end: Date };
39
+ /** Whether abstention detection indicated low confidence */
40
+ abstained?: boolean;
41
+ /** Reason for abstention (if applicable) */
42
+ abstentionReason?: string;
43
+ /** Retrieval confidence score from abstention detector */
44
+ retrievalConfidence?: number;
45
+ }
46
+
47
+ /**
48
+ * Interface for embedding providers
49
+ */
50
+ export interface EmbeddingProvider {
51
+ /** Generate embeddings for texts */
52
+ embed(texts: string[]): Promise<number[][]>;
53
+ /** Get the embedding dimension */
54
+ dimension: number;
55
+ }
56
+
57
+ /**
58
+ * Simple in-memory vector store for benchmarking
59
+ * In production, this would use Qdrant
60
+ */
61
+ export class InMemoryVectorStore {
62
+ private documents: EngramDocument[] = [];
63
+ private embeddings: number[][] = [];
64
+ private embeddingProvider: EmbeddingProvider;
65
+
66
+ constructor(embeddingProvider: EmbeddingProvider) {
67
+ this.embeddingProvider = embeddingProvider;
68
+ }
69
+
70
+ /**
71
+ * Index documents for retrieval
72
+ */
73
+ async index(documents: EngramDocument[]): Promise<void> {
74
+ const texts = documents.map((d) => d.content);
75
+ const embeddings = await this.embeddingProvider.embed(texts);
76
+
77
+ this.documents = documents;
78
+ this.embeddings = embeddings;
79
+ }
80
+
81
+ /**
82
+ * Search for similar documents
83
+ */
84
+ async search(query: string, topK: number): Promise<RetrievalResult> {
85
+ const [queryEmbedding] = await this.embeddingProvider.embed([query]);
86
+
87
+ // Compute cosine similarities
88
+ const similarities = this.embeddings.map((docEmb) => cosineSimilarity(queryEmbedding, docEmb));
89
+
90
+ // Get top-K indices
91
+ const indices = similarities
92
+ .map((score, index) => ({ score, index }))
93
+ .sort((a, b) => b.score - a.score)
94
+ .slice(0, topK)
95
+ .map((item) => item.index);
96
+
97
+ const documents = indices.map((i) => this.documents[i]);
98
+ const scores = indices.map((i) => similarities[i]);
99
+ const retrievedIds = documents.map((d) => d.id);
100
+
101
+ return {
102
+ documents,
103
+ scores,
104
+ retrievedIds,
105
+ };
106
+ }
107
+
108
+ /**
109
+ * Clear the index
110
+ */
111
+ clear(): void {
112
+ this.documents = [];
113
+ this.embeddings = [];
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Computes cosine similarity between two vectors
119
+ */
120
+ function cosineSimilarity(a: number[], b: number[]): number {
121
+ if (a.length !== b.length) {
122
+ throw new Error("Vectors must have the same dimension");
123
+ }
124
+
125
+ let dotProduct = 0;
126
+ let normA = 0;
127
+ let normB = 0;
128
+
129
+ for (let i = 0; i < a.length; i++) {
130
+ dotProduct += a[i] * b[i];
131
+ normA += a[i] * a[i];
132
+ normB += b[i] * b[i];
133
+ }
134
+
135
+ normA = Math.sqrt(normA);
136
+ normB = Math.sqrt(normB);
137
+
138
+ if (normA === 0 || normB === 0) {
139
+ return 0;
140
+ }
141
+
142
+ return dotProduct / (normA * normB);
143
+ }
144
+
145
+ /**
146
+ * Retriever class that handles document retrieval for LongMemEval
147
+ */
148
+ export class Retriever {
149
+ private config: RetrieverConfig;
150
+ private vectorStore: InMemoryVectorStore;
151
+
152
+ constructor(embeddingProvider: EmbeddingProvider, config?: Partial<RetrieverConfig>) {
153
+ this.config = { ...DEFAULT_RETRIEVER_CONFIG, ...config };
154
+ this.vectorStore = new InMemoryVectorStore(embeddingProvider);
155
+ }
156
+
157
+ /**
158
+ * Index a mapped instance for retrieval
159
+ */
160
+ async indexInstance(mapped: MappedInstance): Promise<void> {
161
+ await this.vectorStore.index(mapped.documents);
162
+ }
163
+
164
+ /**
165
+ * Retrieve relevant documents for a question
166
+ */
167
+ async retrieve(question: string, questionDate?: Date): Promise<RetrievalResult> {
168
+ let query = question;
169
+ let extractedTimeRange: { start: Date; end: Date } | undefined;
170
+
171
+ // Apply time-aware query expansion if enabled
172
+ if (this.config.timeAwareExpansion && questionDate) {
173
+ const extraction = extractTemporalContext(question, questionDate);
174
+ if (extraction) {
175
+ query = extraction.expandedQuery;
176
+ extractedTimeRange = extraction.timeRange;
177
+ }
178
+ }
179
+
180
+ const result = await this.vectorStore.search(query, this.config.topK);
181
+
182
+ // Filter by time range if extracted
183
+ if (extractedTimeRange) {
184
+ const filtered = result.documents.filter((doc) => {
185
+ const docTime = doc.validTime.getTime();
186
+ return (
187
+ docTime >= extractedTimeRange?.start.getTime() &&
188
+ docTime <= extractedTimeRange?.end.getTime()
189
+ );
190
+ });
191
+
192
+ // If filtering removes too many, fall back to unfiltered
193
+ if (filtered.length >= this.config.topK / 2) {
194
+ result.documents = filtered.slice(0, this.config.topK);
195
+ result.retrievedIds = result.documents.map((d) => d.id);
196
+ result.scores = result.scores.slice(0, result.documents.length);
197
+ }
198
+ }
199
+
200
+ result.extractedTimeRange = extractedTimeRange;
201
+
202
+ return result;
203
+ }
204
+
205
+ /**
206
+ * Clear the index
207
+ */
208
+ clear(): void {
209
+ this.vectorStore.clear();
210
+ }
211
+ }
212
+
213
+ /**
214
+ * Extracts temporal context from a question
215
+ * This is a simplified version - production would use LLM extraction
216
+ */
217
+ function extractTemporalContext(
218
+ question: string,
219
+ questionDate: Date,
220
+ ): { expandedQuery: string; timeRange: { start: Date; end: Date } } | null {
221
+ const lowerQuestion = question.toLowerCase();
222
+
223
+ // Common temporal patterns
224
+ const patterns = [
225
+ { regex: /last (?:week|7 days)/i, daysBack: 7 },
226
+ { regex: /last (?:month|30 days)/i, daysBack: 30 },
227
+ { regex: /last (?:year|12 months)/i, daysBack: 365 },
228
+ { regex: /yesterday/i, daysBack: 1 },
229
+ { regex: /this (?:week|month)/i, daysBack: 7 },
230
+ ];
231
+
232
+ for (const pattern of patterns) {
233
+ if (pattern.regex.test(lowerQuestion)) {
234
+ const end = new Date(questionDate);
235
+ const start = new Date(questionDate);
236
+ start.setDate(start.getDate() - pattern.daysBack);
237
+
238
+ return {
239
+ expandedQuery: question,
240
+ timeRange: { start, end },
241
+ };
242
+ }
243
+ }
244
+
245
+ // Check for specific month/year mentions
246
+ const monthYearMatch = lowerQuestion.match(
247
+ /(january|february|march|april|may|june|july|august|september|october|november|december)\s*(\d{4})?/i,
248
+ );
249
+
250
+ if (monthYearMatch) {
251
+ const monthNames = [
252
+ "january",
253
+ "february",
254
+ "march",
255
+ "april",
256
+ "may",
257
+ "june",
258
+ "july",
259
+ "august",
260
+ "september",
261
+ "october",
262
+ "november",
263
+ "december",
264
+ ];
265
+ const monthIndex = monthNames.indexOf(monthYearMatch[1].toLowerCase());
266
+ const year = monthYearMatch[2]
267
+ ? Number.parseInt(monthYearMatch[2], 10)
268
+ : questionDate.getFullYear();
269
+
270
+ const start = new Date(year, monthIndex, 1);
271
+ const end = new Date(year, monthIndex + 1, 0);
272
+
273
+ return {
274
+ expandedQuery: question,
275
+ timeRange: { start, end },
276
+ };
277
+ }
278
+
279
+ return null;
280
+ }
281
+
282
+ /**
283
+ * Computes retrieval metrics for evaluation
284
+ */
285
+ export function computeRetrievalMetrics(
286
+ result: RetrievalResult,
287
+ evidenceDocIds: string[],
288
+ ): {
289
+ recall: number;
290
+ precision: number;
291
+ recallAtK: Record<number, number>;
292
+ } {
293
+ const evidenceSet = new Set(evidenceDocIds);
294
+ const _retrievedSet = new Set(result.retrievedIds);
295
+
296
+ // Compute recall and precision
297
+ let hits = 0;
298
+ for (const id of result.retrievedIds) {
299
+ if (evidenceSet.has(id)) {
300
+ hits++;
301
+ }
302
+ }
303
+
304
+ const recall = evidenceDocIds.length > 0 ? hits / evidenceDocIds.length : 0;
305
+ const precision = result.retrievedIds.length > 0 ? hits / result.retrievedIds.length : 0;
306
+
307
+ // Compute recall@K for K = 1, 5, 10
308
+ const recallAtK: Record<number, number> = {};
309
+ for (const k of [1, 5, 10]) {
310
+ const topKIds = result.retrievedIds.slice(0, k);
311
+ let hitsAtK = 0;
312
+ for (const id of topKIds) {
313
+ if (evidenceSet.has(id)) {
314
+ hitsAtK++;
315
+ }
316
+ }
317
+ recallAtK[k] = evidenceDocIds.length > 0 ? hitsAtK / evidenceDocIds.length : 0;
318
+ }
319
+
320
+ return { recall, precision, recallAtK };
321
+ }
packages/benchmark/src/longmemeval/temporal.ts ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { LLMProvider } from "./reader.js";
2
+
3
+ /**
4
+ * Time-Aware Query Expansion
5
+ *
6
+ * Based on LongMemEval findings:
7
+ * - Time-aware indexing and query expansion improves temporal reasoning by 7-11%
8
+ * - Extracting temporal ranges from queries narrows search scope
9
+ *
10
+ * @see https://arxiv.org/abs/2410.10813
11
+ */
12
+
13
+ /**
14
+ * Configuration for temporal query expansion
15
+ */
16
+ export interface TemporalConfig {
17
+ /** LLM for extraction (optional - uses heuristics if not provided) */
18
+ llm?: LLMProvider;
19
+ /** Default time window in days when no explicit range */
20
+ defaultWindowDays: number;
21
+ }
22
+
23
+ const DEFAULT_CONFIG: TemporalConfig = {
24
+ defaultWindowDays: 30,
25
+ };
26
+
27
+ /**
28
+ * Result of temporal query analysis
29
+ */
30
+ export interface TemporalAnalysis {
31
+ /** Original query */
32
+ originalQuery: string;
33
+ /** Expanded query with temporal context */
34
+ expandedQuery: string;
35
+ /** Extracted time range for filtering */
36
+ timeRange?: TimeRange;
37
+ /** Temporal keywords found */
38
+ temporalKeywords: string[];
39
+ /** Whether query requires temporal reasoning */
40
+ isTemporalQuery: boolean;
41
+ }
42
+
43
+ /**
44
+ * Time range for filtering
45
+ */
46
+ export interface TimeRange {
47
+ start: Date;
48
+ end: Date;
49
+ confidence: "high" | "medium" | "low";
50
+ source: string; // What triggered this range
51
+ }
52
+
53
+ /**
54
+ * Temporal query analyzer and expander
55
+ */
56
+ export class TemporalAnalyzer {
57
+ private config: TemporalConfig;
58
+
59
+ constructor(config: Partial<TemporalConfig> = {}) {
60
+ this.config = { ...DEFAULT_CONFIG, ...config };
61
+ }
62
+
63
+ /**
64
+ * Analyze and expand a query for temporal context
65
+ */
66
+ async analyze(query: string, queryDate: Date): Promise<TemporalAnalysis> {
67
+ // Extract temporal keywords
68
+ const temporalKeywords = this.extractTemporalKeywords(query);
69
+ const isTemporalQuery = temporalKeywords.length > 0 || this.hasTemporalIntent(query);
70
+
71
+ // Extract time range
72
+ let timeRange: TimeRange | undefined;
73
+ if (isTemporalQuery) {
74
+ timeRange = this.config.llm
75
+ ? await this.llmExtractTimeRange(query, queryDate)
76
+ : this.heuristicTimeRange(query, queryDate);
77
+ }
78
+
79
+ // Expand query
80
+ const expandedQuery = this.expandQuery(query, timeRange, queryDate);
81
+
82
+ return {
83
+ originalQuery: query,
84
+ expandedQuery,
85
+ timeRange,
86
+ temporalKeywords,
87
+ isTemporalQuery,
88
+ };
89
+ }
90
+
91
+ /**
92
+ * Extract temporal keywords from query
93
+ */
94
+ private extractTemporalKeywords(query: string): string[] {
95
+ const keywords: string[] = [];
96
+ const lowerQuery = query.toLowerCase();
97
+
98
+ // Temporal keyword patterns
99
+ const patterns = [
100
+ // Relative time
101
+ /\b(yesterday|today|tomorrow|last|next|recent|recently|previous|current|now)\b/g,
102
+ // Time units
103
+ /\b(week|month|year|day|hour|minute|morning|afternoon|evening|night)\b/g,
104
+ // Ordinals
105
+ /\b(first|second|third|latest|earliest|oldest|newest)\b/g,
106
+ // Temporal questions
107
+ /\b(when|since|until|before|after|during|while)\b/g,
108
+ // Specific time references
109
+ /\b(january|february|march|april|may|june|july|august|september|october|november|december)\b/g,
110
+ /\b(monday|tuesday|wednesday|thursday|friday|saturday|sunday)\b/g,
111
+ // Date patterns
112
+ /\b\d{4}\b/g, // Year
113
+ /\b\d{1,2}\/\d{1,2}\b/g, // Date format
114
+ ];
115
+
116
+ for (const pattern of patterns) {
117
+ for (const match of lowerQuery.matchAll(pattern)) {
118
+ keywords.push(match[0]);
119
+ }
120
+ }
121
+
122
+ return [...new Set(keywords)];
123
+ }
124
+
125
+ /**
126
+ * Check if query has temporal intent without explicit keywords
127
+ */
128
+ private hasTemporalIntent(query: string): boolean {
129
+ const lowerQuery = query.toLowerCase();
130
+
131
+ // Questions that often require temporal context
132
+ const temporalPatterns = [
133
+ /how long/,
134
+ /how many times/,
135
+ /what time/,
136
+ /what date/,
137
+ /which day/,
138
+ /most recent/,
139
+ /changed|updated|modified/,
140
+ /started|began|ended|finished/,
141
+ /first time|last time/,
142
+ /ever since/,
143
+ /up to now/,
144
+ /so far/,
145
+ /at the moment/,
146
+ /currently/,
147
+ ];
148
+
149
+ return temporalPatterns.some((pattern) => pattern.test(lowerQuery));
150
+ }
151
+
152
+ /**
153
+ * Extract time range using heuristics
154
+ */
155
+ private heuristicTimeRange(query: string, queryDate: Date): TimeRange | undefined {
156
+ const lowerQuery = query.toLowerCase();
157
+
158
+ // Yesterday
159
+ if (/\byesterday\b/.test(lowerQuery)) {
160
+ const start = new Date(queryDate);
161
+ start.setDate(start.getDate() - 1);
162
+ start.setHours(0, 0, 0, 0);
163
+ const end = new Date(start);
164
+ end.setHours(23, 59, 59, 999);
165
+ return { start, end, confidence: "high", source: "yesterday" };
166
+ }
167
+
168
+ // Today
169
+ if (/\btoday\b/.test(lowerQuery)) {
170
+ const start = new Date(queryDate);
171
+ start.setHours(0, 0, 0, 0);
172
+ const end = new Date(queryDate);
173
+ end.setHours(23, 59, 59, 999);
174
+ return { start, end, confidence: "high", source: "today" };
175
+ }
176
+
177
+ // Tomorrow
178
+ if (/\btomorrow\b/.test(lowerQuery)) {
179
+ const start = new Date(queryDate);
180
+ start.setDate(start.getDate() + 1);
181
+ start.setHours(0, 0, 0, 0);
182
+ const end = new Date(start);
183
+ end.setHours(23, 59, 59, 999);
184
+ return { start, end, confidence: "high", source: "tomorrow" };
185
+ }
186
+
187
+ // Last week
188
+ if (/\blast\s+week\b/.test(lowerQuery)) {
189
+ const end = new Date(queryDate);
190
+ const start = new Date(queryDate);
191
+ start.setDate(start.getDate() - 7);
192
+ return { start, end, confidence: "high", source: "last week" };
193
+ }
194
+
195
+ // Last month
196
+ if (/\blast\s+month\b/.test(lowerQuery)) {
197
+ const end = new Date(queryDate);
198
+ const start = new Date(queryDate);
199
+ start.setMonth(start.getMonth() - 1);
200
+ return { start, end, confidence: "high", source: "last month" };
201
+ }
202
+
203
+ // Last year
204
+ if (/\blast\s+year\b/.test(lowerQuery)) {
205
+ const end = new Date(queryDate);
206
+ const start = new Date(queryDate);
207
+ start.setFullYear(start.getFullYear() - 1);
208
+ return { start, end, confidence: "high", source: "last year" };
209
+ }
210
+
211
+ // Last N days/weeks/months
212
+ const lastNMatch = lowerQuery.match(/\blast\s+(\d+)\s+(day|week|month|year)s?\b/);
213
+ if (lastNMatch) {
214
+ const n = Number.parseInt(lastNMatch[1], 10);
215
+ const unit = lastNMatch[2];
216
+ const end = new Date(queryDate);
217
+ const start = new Date(queryDate);
218
+
219
+ switch (unit) {
220
+ case "day":
221
+ start.setDate(start.getDate() - n);
222
+ break;
223
+ case "week":
224
+ start.setDate(start.getDate() - n * 7);
225
+ break;
226
+ case "month":
227
+ start.setMonth(start.getMonth() - n);
228
+ break;
229
+ case "year":
230
+ start.setFullYear(start.getFullYear() - n);
231
+ break;
232
+ }
233
+
234
+ return { start, end, confidence: "high", source: `last ${n} ${unit}s` };
235
+ }
236
+
237
+ // Specific month
238
+ const monthMatch = lowerQuery.match(
239
+ /\b(january|february|march|april|may|june|july|august|september|october|november|december)(?:\s+(\d{4}))?\b/,
240
+ );
241
+ if (monthMatch) {
242
+ const monthNames = [
243
+ "january",
244
+ "february",
245
+ "march",
246
+ "april",
247
+ "may",
248
+ "june",
249
+ "july",
250
+ "august",
251
+ "september",
252
+ "october",
253
+ "november",
254
+ "december",
255
+ ];
256
+ const monthIndex = monthNames.indexOf(monthMatch[1]);
257
+ const year = monthMatch[2] ? Number.parseInt(monthMatch[2], 10) : queryDate.getFullYear();
258
+
259
+ const start = new Date(year, monthIndex, 1);
260
+ const end = new Date(year, monthIndex + 1, 0, 23, 59, 59, 999);
261
+
262
+ return {
263
+ start,
264
+ end,
265
+ confidence: monthMatch[2] ? "high" : "medium",
266
+ source: `${monthMatch[1]} ${year}`,
267
+ };
268
+ }
269
+
270
+ // Specific year
271
+ const yearMatch = lowerQuery.match(/\bin\s+(\d{4})\b/);
272
+ if (yearMatch) {
273
+ const year = Number.parseInt(yearMatch[1], 10);
274
+ const start = new Date(year, 0, 1);
275
+ const end = new Date(year, 11, 31, 23, 59, 59, 999);
276
+ return { start, end, confidence: "high", source: `year ${year}` };
277
+ }
278
+
279
+ // Recent/recently - default window
280
+ if (/\brecent(ly)?\b/.test(lowerQuery)) {
281
+ const end = new Date(queryDate);
282
+ const start = new Date(queryDate);
283
+ start.setDate(start.getDate() - this.config.defaultWindowDays);
284
+ return { start, end, confidence: "medium", source: "recently" };
285
+ }
286
+
287
+ // Day of week (assume most recent occurrence)
288
+ const dayMatch = lowerQuery.match(
289
+ /\b(monday|tuesday|wednesday|thursday|friday|saturday|sunday)\b/,
290
+ );
291
+ if (dayMatch) {
292
+ const dayNames = [
293
+ "sunday",
294
+ "monday",
295
+ "tuesday",
296
+ "wednesday",
297
+ "thursday",
298
+ "friday",
299
+ "saturday",
300
+ ];
301
+ const targetDay = dayNames.indexOf(dayMatch[1]);
302
+ const currentDay = queryDate.getDay();
303
+ let daysBack = currentDay - targetDay;
304
+ if (daysBack <= 0) daysBack += 7;
305
+
306
+ const start = new Date(queryDate);
307
+ start.setDate(start.getDate() - daysBack);
308
+ start.setHours(0, 0, 0, 0);
309
+ const end = new Date(start);
310
+ end.setHours(23, 59, 59, 999);
311
+
312
+ return { start, end, confidence: "medium", source: dayMatch[1] };
313
+ }
314
+
315
+ return undefined;
316
+ }
317
+
318
+ /**
319
+ * Extract time range using LLM
320
+ */
321
+ private async llmExtractTimeRange(
322
+ query: string,
323
+ queryDate: Date,
324
+ ): Promise<TimeRange | undefined> {
325
+ const prompt = `Analyze this question and extract any time constraints.
326
+
327
+ Question: "${query}"
328
+ Current date: ${queryDate.toISOString().split("T")[0]}
329
+
330
+ If the question references a specific time period, return JSON with:
331
+ {
332
+ "start": "YYYY-MM-DD",
333
+ "end": "YYYY-MM-DD",
334
+ "confidence": "high" | "medium" | "low",
335
+ "source": "what triggered this range"
336
+ }
337
+
338
+ If no time constraint is implied, return: {"noTimeConstraint": true}
339
+
340
+ JSON response:`;
341
+
342
+ const response = await this.config.llm?.complete(prompt, { maxTokens: 100 });
343
+ if (!response) return undefined;
344
+
345
+ try {
346
+ const jsonMatch = response.text.match(/\{[\s\S]*\}/);
347
+ if (jsonMatch) {
348
+ const parsed = JSON.parse(jsonMatch[0]);
349
+ if (parsed.noTimeConstraint) {
350
+ return undefined;
351
+ }
352
+ return {
353
+ start: new Date(parsed.start),
354
+ end: new Date(parsed.end),
355
+ confidence: parsed.confidence ?? "medium",
356
+ source: parsed.source ?? "llm extraction",
357
+ };
358
+ }
359
+ } catch {
360
+ // Fall back to heuristic
361
+ return this.heuristicTimeRange(query, queryDate);
362
+ }
363
+
364
+ return undefined;
365
+ }
366
+
367
+ /**
368
+ * Expand query with temporal context
369
+ */
370
+ private expandQuery(query: string, timeRange: TimeRange | undefined, _queryDate: Date): string {
371
+ if (!timeRange) {
372
+ return query;
373
+ }
374
+
375
+ // Add temporal context to query
376
+ const dateContext = `[Time context: ${formatDateRange(timeRange.start, timeRange.end)}]`;
377
+ return `${query}\n${dateContext}`;
378
+ }
379
+ }
380
+
381
+ /**
382
+ * Format a date range for display
383
+ */
384
+ function formatDateRange(start: Date, end: Date): string {
385
+ // Validate dates before formatting
386
+ if (!isValidDate(start) || !isValidDate(end)) {
387
+ return "unknown date range";
388
+ }
389
+
390
+ const startStr = start.toISOString().split("T")[0];
391
+ const endStr = end.toISOString().split("T")[0];
392
+
393
+ if (startStr === endStr) {
394
+ return startStr;
395
+ }
396
+
397
+ return `${startStr} to ${endStr}`;
398
+ }
399
+
400
+ /**
401
+ * Check if a date is valid
402
+ */
403
+ function isValidDate(date: Date): boolean {
404
+ return date instanceof Date && !Number.isNaN(date.getTime());
405
+ }
406
+
407
+ /**
408
+ * Quick function to analyze temporal aspects of a query
409
+ */
410
+ export async function analyzeTemporalQuery(
411
+ query: string,
412
+ queryDate: Date,
413
+ config?: Partial<TemporalConfig>,
414
+ ): Promise<TemporalAnalysis> {
415
+ const analyzer = new TemporalAnalyzer(config);
416
+ return analyzer.analyze(query, queryDate);
417
+ }
418
+
419
+ /**
420
+ * Filter documents by time range
421
+ */
422
+ export function filterByTimeRange<T extends { validTime: Date }>(
423
+ documents: T[],
424
+ timeRange: TimeRange | { start: Date; end: Date },
425
+ ): T[] {
426
+ return documents.filter((doc) => {
427
+ const docTime = doc.validTime.getTime();
428
+ return docTime >= timeRange.start.getTime() && docTime <= timeRange.end.getTime();
429
+ });
430
+ }
packages/benchmark/src/longmemeval/types.ts ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * LongMemEval Dataset Schema
5
+ *
6
+ * Based on the LongMemEval benchmark (ICLR 2025)
7
+ * @see https://github.com/xiaowu0162/LongMemEval
8
+ * @see https://huggingface.co/datasets/xiaowu0162/longmemeval-cleaned
9
+ */
10
+
11
+ /**
12
+ * Question types representing the 5 core memory abilities:
13
+ * - IE (Information Extraction): single-session-*
14
+ * - MR (Multi-Session Reasoning): multi-session
15
+ * - TR (Temporal Reasoning): temporal-reasoning
16
+ * - KU (Knowledge Update): knowledge-update
17
+ * - ABS (Abstention): indicated by _abs suffix on question_id
18
+ */
19
+ export const QuestionTypeSchema = z.enum([
20
+ "single-session-user",
21
+ "single-session-assistant",
22
+ "single-session-preference",
23
+ "multi-session",
24
+ "temporal-reasoning",
25
+ "knowledge-update",
26
+ ]);
27
+
28
+ export type QuestionType = z.infer<typeof QuestionTypeSchema>;
29
+
30
+ /**
31
+ * A single turn in a conversation (user or assistant message)
32
+ */
33
+ export const TurnSchema = z.object({
34
+ role: z.enum(["user", "assistant"]),
35
+ content: z.string(),
36
+ has_answer: z.boolean().optional(),
37
+ });
38
+
39
+ export type Turn = z.infer<typeof TurnSchema>;
40
+
41
+ /**
42
+ * A session is an array of turns representing a conversation
43
+ */
44
+ export const SessionSchema = z.array(TurnSchema);
45
+
46
+ export type Session = z.infer<typeof SessionSchema>;
47
+
48
+ /**
49
+ * A single evaluation instance from LongMemEval
50
+ * Note: answer field uses coerce because some answers are numeric in the dataset
51
+ */
52
+ export const LongMemEvalInstanceSchema = z.object({
53
+ question_id: z.string(),
54
+ question_type: QuestionTypeSchema,
55
+ question: z.string(),
56
+ answer: z.coerce.string(), // Coerce numbers to strings
57
+ question_date: z.string(),
58
+ haystack_session_ids: z.array(z.string()),
59
+ haystack_dates: z.array(z.string()),
60
+ haystack_sessions: z.array(SessionSchema),
61
+ answer_session_ids: z.array(z.string()),
62
+ });
63
+
64
+ export type LongMemEvalInstance = z.infer<typeof LongMemEvalInstanceSchema>;
65
+
66
+ /**
67
+ * The full dataset is an array of instances
68
+ */
69
+ export const LongMemEvalDatasetSchema = z.array(LongMemEvalInstanceSchema);
70
+
71
+ export type LongMemEvalDataset = z.infer<typeof LongMemEvalDatasetSchema>;
72
+
73
+ /**
74
+ * Dataset variants available
75
+ */
76
+ export type DatasetVariant = "s" | "m" | "oracle";
77
+
78
+ /**
79
+ * Memory ability category derived from question type
80
+ */
81
+ export type MemoryAbility = "IE" | "MR" | "TR" | "KU" | "ABS";
82
+
83
+ /**
84
+ * Maps question type to memory ability
85
+ */
86
+ export function getMemoryAbility(questionType: QuestionType, questionId: string): MemoryAbility {
87
+ // Abstention is indicated by _abs suffix
88
+ if (questionId.endsWith("_abs")) {
89
+ return "ABS";
90
+ }
91
+
92
+ switch (questionType) {
93
+ case "single-session-user":
94
+ case "single-session-assistant":
95
+ case "single-session-preference":
96
+ return "IE";
97
+ case "multi-session":
98
+ return "MR";
99
+ case "temporal-reasoning":
100
+ return "TR";
101
+ case "knowledge-update":
102
+ return "KU";
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Parsed instance with normalized data types
108
+ */
109
+ export interface ParsedInstance {
110
+ questionId: string;
111
+ questionType: QuestionType;
112
+ memoryAbility: MemoryAbility;
113
+ question: string;
114
+ answer: string;
115
+ questionDate: Date;
116
+ sessions: ParsedSession[];
117
+ answerSessionIds: string[];
118
+ isAbstention: boolean;
119
+ }
120
+
121
+ /**
122
+ * Parsed session with normalized data
123
+ */
124
+ export interface ParsedSession {
125
+ sessionId: string;
126
+ timestamp: Date;
127
+ turns: ParsedTurn[];
128
+ }
129
+
130
+ /**
131
+ * Parsed turn with sequence index
132
+ */
133
+ export interface ParsedTurn {
134
+ role: "user" | "assistant";
135
+ content: string;
136
+ hasAnswer: boolean;
137
+ sequenceIndex: number;
138
+ }
139
+
140
+ /**
141
+ * Output format for benchmark results
142
+ */
143
+ export interface BenchmarkResult {
144
+ questionId: string;
145
+ hypothesis: string;
146
+ }
147
+
148
+ /**
149
+ * Evaluation output with judgment
150
+ */
151
+ export interface EvaluatedResult extends BenchmarkResult {
152
+ answer: string;
153
+ questionType: QuestionType;
154
+ memoryAbility: MemoryAbility;
155
+ correct: boolean;
156
+ reasoning?: string;
157
+ }
158
+
159
+ /**
160
+ * Aggregate metrics per memory ability
161
+ */
162
+ export interface AbilityMetrics {
163
+ total: number;
164
+ correct: number;
165
+ accuracy: number;
166
+ }
167
+
168
+ /**
169
+ * Full evaluation metrics
170
+ */
171
+ export interface EvaluationMetrics {
172
+ overall: {
173
+ total: number;
174
+ correct: number;
175
+ accuracy: number;
176
+ };
177
+ byAbility: Record<MemoryAbility, AbilityMetrics>;
178
+ retrieval?: RetrievalMetrics;
179
+ abstention?: AbstentionMetrics;
180
+ }
181
+
182
+ /**
183
+ * Retrieval quality metrics
184
+ */
185
+ export interface RetrievalMetrics {
186
+ /** Percentage of evidence turns retrieved */
187
+ turnRecall: number;
188
+ /** Percentage of evidence sessions retrieved */
189
+ sessionRecall: number;
190
+ /** Recall at different K values (1, 5, 10) */
191
+ recallAtK: Record<number, number>;
192
+ /** NDCG at different K values (1, 5, 10) - measures ranking quality */
193
+ ndcgAtK: Record<number, number>;
194
+ /** Mean Reciprocal Rank */
195
+ mrr: number;
196
+ }
197
+
198
+ /**
199
+ * Abstention-specific metrics
200
+ */
201
+ export interface AbstentionMetrics {
202
+ /** True positives: correctly abstained */
203
+ truePositives: number;
204
+ /** False positives: incorrectly abstained */
205
+ falsePositives: number;
206
+ /** False negatives: should have abstained but didn't */
207
+ falseNegatives: number;
208
+ /** True negatives: correctly answered */
209
+ trueNegatives: number;
210
+ /** Precision: correct abstentions / total abstentions */
211
+ precision: number;
212
+ /** Recall: correct abstentions / questions requiring abstention */
213
+ recall: number;
214
+ /** F1 score: harmonic mean of precision and recall */
215
+ f1: number;
216
+ }
packages/benchmark/tests/core/config.test.ts ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from "vitest";
2
+ import { buildBenchmarkConfig, DEFAULT_BENCHMARK_CONFIG } from "../../src/core/config.js";
3
+
4
+ describe("buildBenchmarkConfig", () => {
5
+ it("should require dataset", () => {
6
+ const config = buildBenchmarkConfig({ dataset: "/path/to/data.json" });
7
+ expect(config.dataset).toBe("/path/to/data.json");
8
+ });
9
+
10
+ it("should apply defaults for missing fields", () => {
11
+ const config = buildBenchmarkConfig({ dataset: "/path/to/data.json" });
12
+
13
+ expect(config.variant).toBe(DEFAULT_BENCHMARK_CONFIG.variant);
14
+ expect(config.topK).toBe(DEFAULT_BENCHMARK_CONFIG.topK);
15
+ expect(config.retriever).toBe(DEFAULT_BENCHMARK_CONFIG.retriever);
16
+ expect(config.embeddings).toBe(DEFAULT_BENCHMARK_CONFIG.embeddings);
17
+ expect(config.hybridSearch).toBe(DEFAULT_BENCHMARK_CONFIG.hybridSearch);
18
+ expect(config.rerank).toBe(DEFAULT_BENCHMARK_CONFIG.rerank);
19
+ expect(config.rerankTier).toBe(DEFAULT_BENCHMARK_CONFIG.rerankTier);
20
+ expect(config.rerankDepth).toBe(DEFAULT_BENCHMARK_CONFIG.rerankDepth);
21
+ expect(config.llm).toBe(DEFAULT_BENCHMARK_CONFIG.llm);
22
+ });
23
+
24
+ it("should allow overriding defaults", () => {
25
+ const config = buildBenchmarkConfig({
26
+ dataset: "/path/to/data.json",
27
+ variant: "s",
28
+ topK: 5,
29
+ retriever: "dense",
30
+ embeddings: "qdrant",
31
+ rerank: false,
32
+ llm: "anthropic",
33
+ limit: 100,
34
+ });
35
+
36
+ expect(config.variant).toBe("s");
37
+ expect(config.topK).toBe(5);
38
+ expect(config.retriever).toBe("dense");
39
+ expect(config.embeddings).toBe("qdrant");
40
+ expect(config.rerank).toBe(false);
41
+ expect(config.llm).toBe("anthropic");
42
+ expect(config.limit).toBe(100);
43
+ });
44
+
45
+ it("should use environment variable fallback for qdrantUrl", () => {
46
+ const originalQdrantUrl = process.env.QDRANT_URL;
47
+
48
+ process.env.QDRANT_URL = "http://qdrant.example.com:6333";
49
+
50
+ const config = buildBenchmarkConfig({ dataset: "/path/to/data.json" });
51
+ expect(config.qdrantUrl).toBe("http://qdrant.example.com:6333");
52
+
53
+ // Restore
54
+ if (originalQdrantUrl === undefined) {
55
+ delete process.env.QDRANT_URL;
56
+ } else {
57
+ process.env.QDRANT_URL = originalQdrantUrl;
58
+ }
59
+ });
60
+
61
+ it("should prefer explicit option over env var", () => {
62
+ const originalQdrantUrl = process.env.QDRANT_URL;
63
+ process.env.QDRANT_URL = "http://env.example.com:6333";
64
+
65
+ const config = buildBenchmarkConfig({
66
+ dataset: "/path/to/data.json",
67
+ qdrantUrl: "http://explicit.example.com:6333",
68
+ });
69
+
70
+ expect(config.qdrantUrl).toBe("http://explicit.example.com:6333");
71
+
72
+ // Restore
73
+ if (originalQdrantUrl === undefined) {
74
+ delete process.env.QDRANT_URL;
75
+ } else {
76
+ process.env.QDRANT_URL = originalQdrantUrl;
77
+ }
78
+ });
79
+
80
+ it("should configure multi-query settings", () => {
81
+ const config = buildBenchmarkConfig({
82
+ dataset: "/path/to/data.json",
83
+ multiQuery: true,
84
+ multiQueryVariations: 5,
85
+ });
86
+
87
+ expect(config.multiQuery).toBe(true);
88
+ expect(config.multiQueryVariations).toBe(5);
89
+ });
90
+
91
+ it("should configure abstention settings", () => {
92
+ const config = buildBenchmarkConfig({
93
+ dataset: "/path/to/data.json",
94
+ abstention: true,
95
+ abstentionThreshold: 0.5,
96
+ });
97
+
98
+ expect(config.abstention).toBe(true);
99
+ expect(config.abstentionThreshold).toBe(0.5);
100
+ });
101
+
102
+ it("should configure session-aware settings", () => {
103
+ const config = buildBenchmarkConfig({
104
+ dataset: "/path/to/data.json",
105
+ sessionAware: true,
106
+ topSessions: 10,
107
+ turnsPerSession: 5,
108
+ });
109
+
110
+ expect(config.sessionAware).toBe(true);
111
+ expect(config.topSessions).toBe(10);
112
+ expect(config.turnsPerSession).toBe(5);
113
+ });
114
+
115
+ it("should configure temporal settings", () => {
116
+ const config = buildBenchmarkConfig({
117
+ dataset: "/path/to/data.json",
118
+ temporalAware: true,
119
+ temporalConfidenceThreshold: 0.9,
120
+ });
121
+
122
+ expect(config.temporalAware).toBe(true);
123
+ expect(config.temporalConfidenceThreshold).toBe(0.9);
124
+ });
125
+ });
126
+
127
+ describe("DEFAULT_BENCHMARK_CONFIG", () => {
128
+ it("should have sensible defaults", () => {
129
+ expect(DEFAULT_BENCHMARK_CONFIG.variant).toBe("oracle");
130
+ expect(DEFAULT_BENCHMARK_CONFIG.topK).toBe(10);
131
+ expect(DEFAULT_BENCHMARK_CONFIG.retriever).toBe("hybrid");
132
+ expect(DEFAULT_BENCHMARK_CONFIG.embeddings).toBe("engram");
133
+ expect(DEFAULT_BENCHMARK_CONFIG.hybridSearch).toBe(true);
134
+ expect(DEFAULT_BENCHMARK_CONFIG.rerank).toBe(true);
135
+ expect(DEFAULT_BENCHMARK_CONFIG.rerankTier).toBe("accurate");
136
+ expect(DEFAULT_BENCHMARK_CONFIG.rerankDepth).toBe(30);
137
+ expect(DEFAULT_BENCHMARK_CONFIG.llm).toBe("stub");
138
+ });
139
+ });