|
| 1 | +// Package mock provides a deterministic llm.Provider implementation for |
| 2 | +// tests. It does NOT require any network, API key, or external process. |
| 3 | +// Callers import it directly (no build tag) — the package lives under |
| 4 | +// internal/ so it cannot leak into the public API surface. |
| 5 | +package mock |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "crypto/sha256" |
| 10 | + "encoding/binary" |
| 11 | + "fmt" |
| 12 | + "math" |
| 13 | + "strings" |
| 14 | + |
| 15 | + "github.com/RandomCodeSpace/docsiq/internal/llm" |
| 16 | +) |
| 17 | + |
| 18 | +// DefaultDims is the default embedding dimensionality. |
| 19 | +const DefaultDims = 128 |
| 20 | + |
| 21 | +// Provider is a deterministic, in-memory llm.Provider useful for unit |
| 22 | +// and integration tests. It inspects the prompt for known substrings |
| 23 | +// and returns canned, schema-valid JSON; embeddings are derived from a |
| 24 | +// SHA-256 of the input so equal text yields equal vectors. |
| 25 | +type Provider struct { |
| 26 | + Dims int |
| 27 | +} |
| 28 | + |
| 29 | +// Compile-time check that *Provider satisfies llm.Provider. |
| 30 | +var _ llm.Provider = (*Provider)(nil) |
| 31 | + |
| 32 | +// New returns a mock provider. Pass 0 for DefaultDims (128). |
| 33 | +func New(dims int) *Provider { |
| 34 | + if dims <= 0 { |
| 35 | + dims = DefaultDims |
| 36 | + } |
| 37 | + return &Provider{Dims: dims} |
| 38 | +} |
| 39 | + |
| 40 | +func (p *Provider) Name() string { return "mock" } |
| 41 | +func (p *Provider) ModelID() string { return "mock-llm" } |
| 42 | + |
| 43 | +// Complete returns a deterministic response chosen by prompt substring. |
| 44 | +// Schema must match what internal/extractor and internal/community |
| 45 | +// expect; see entityPrompt in internal/extractor/entities.go and |
| 46 | +// communityPrompt in internal/community/summarizer.go. |
| 47 | +func (p *Provider) Complete(ctx context.Context, prompt string, _ ...llm.Option) (string, error) { |
| 48 | + if err := ctx.Err(); err != nil { |
| 49 | + return "", err |
| 50 | + } |
| 51 | + lower := strings.ToLower(prompt) |
| 52 | + |
| 53 | + switch { |
| 54 | + case strings.Contains(lower, "knowledge graph") && strings.Contains(lower, "entities"): |
| 55 | + // Entity + relationship extraction. The pipeline parses this |
| 56 | + // JSON via internal/extractor — schema must match exactly. |
| 57 | + // Stable entity names derived from prompt-hash so different |
| 58 | + // chunks yield different graphs; dedup then collapses across |
| 59 | + // the corpus. |
| 60 | + tag := hashTag(prompt, 2) |
| 61 | + return fmt.Sprintf(`{ |
| 62 | + "entities": [ |
| 63 | + {"name": "Entity_%s_A", "type": "Concept", "description": "deterministic mock entity A"}, |
| 64 | + {"name": "Entity_%s_B", "type": "Concept", "description": "deterministic mock entity B"} |
| 65 | + ], |
| 66 | + "relationships": [ |
| 67 | + {"source": "Entity_%s_A", "target": "Entity_%s_B", "predicate": "relates_to", "description": "mock edge", "weight": 1.0} |
| 68 | + ] |
| 69 | +}`, tag, tag, tag, tag), nil |
| 70 | + |
| 71 | + case strings.Contains(lower, "claim"): |
| 72 | + tag := hashTag(prompt, 2) |
| 73 | + return fmt.Sprintf(`{ |
| 74 | + "claims": [ |
| 75 | + {"subject": "Entity_%s_A", "predicate": "is", "object": "mock claim", "description": "deterministic"} |
| 76 | + ] |
| 77 | +}`, tag), nil |
| 78 | + |
| 79 | + case strings.Contains(lower, "community") || strings.Contains(lower, "summar"): |
| 80 | + // Must match parseCommunityReport which looks for "TITLE:" and "SUMMARY:" prefixes. |
| 81 | + return "TITLE: Mock community\nSUMMARY: A deterministic, test-only paragraph describing the community of entities in scope.", nil |
| 82 | + |
| 83 | + default: |
| 84 | + // Unknown prompt — return empty JSON so whatever caller gets |
| 85 | + // it can proceed without a parse error. |
| 86 | + return `{}`, nil |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +// Embed returns a Dims-length vector derived from SHA-256(text). Equal |
| 91 | +// text yields equal vectors. |
| 92 | +func (p *Provider) Embed(ctx context.Context, text string) ([]float32, error) { |
| 93 | + if err := ctx.Err(); err != nil { |
| 94 | + return nil, err |
| 95 | + } |
| 96 | + return hashEmbedding(text, p.Dims), nil |
| 97 | +} |
| 98 | + |
| 99 | +func (p *Provider) EmbedBatch(ctx context.Context, texts []string) ([][]float32, error) { |
| 100 | + out := make([][]float32, len(texts)) |
| 101 | + for i, t := range texts { |
| 102 | + v, err := p.Embed(ctx, t) |
| 103 | + if err != nil { |
| 104 | + return nil, err |
| 105 | + } |
| 106 | + out[i] = v |
| 107 | + } |
| 108 | + return out, nil |
| 109 | +} |
| 110 | + |
| 111 | +// hashEmbedding derives a stable dims-length unit vector from SHA-256(text). |
| 112 | +// Runs SHA-256 repeatedly with a counter suffix until dims float32s have |
| 113 | +// been produced, then L2-normalises. O(dims) time, zero allocations in |
| 114 | +// the hot path beyond the output slice. |
| 115 | +func hashEmbedding(text string, dims int) []float32 { |
| 116 | + if dims <= 0 { |
| 117 | + dims = DefaultDims |
| 118 | + } |
| 119 | + out := make([]float32, dims) |
| 120 | + seed := []byte(text) |
| 121 | + var i int |
| 122 | + for counter := uint32(0); i < dims; counter++ { |
| 123 | + var ctrBuf [4]byte |
| 124 | + binary.LittleEndian.PutUint32(ctrBuf[:], counter) |
| 125 | + h := sha256.New() |
| 126 | + h.Write(seed) |
| 127 | + h.Write(ctrBuf[:]) |
| 128 | + sum := h.Sum(nil) |
| 129 | + // Each sha256 gives 32 bytes → 8 float32s via uint32 LE. |
| 130 | + for j := 0; j < len(sum) && i < dims; j += 4 { |
| 131 | + u := binary.LittleEndian.Uint32(sum[j : j+4]) |
| 132 | + // Map uint32 into (-1, 1). |
| 133 | + out[i] = float32(int32(u))/float32(math.MaxInt32) - 0 |
| 134 | + i++ |
| 135 | + } |
| 136 | + } |
| 137 | + // L2-normalise so cosine similarity stays well defined. |
| 138 | + var norm float64 |
| 139 | + for _, v := range out { |
| 140 | + norm += float64(v) * float64(v) |
| 141 | + } |
| 142 | + if norm == 0 { |
| 143 | + out[0] = 1 |
| 144 | + return out |
| 145 | + } |
| 146 | + inv := float32(1.0 / math.Sqrt(norm)) |
| 147 | + for k := range out { |
| 148 | + out[k] *= inv |
| 149 | + } |
| 150 | + return out |
| 151 | +} |
| 152 | + |
| 153 | +// hashTag returns the first n hex chars of SHA-256(s) — used as a |
| 154 | +// stable, short identifier in canned entity names. |
| 155 | +func hashTag(s string, n int) string { |
| 156 | + sum := sha256.Sum256([]byte(s)) |
| 157 | + const hex = "0123456789abcdef" |
| 158 | + out := make([]byte, n*2) |
| 159 | + for i := 0; i < n; i++ { |
| 160 | + out[2*i] = hex[sum[i]>>4] |
| 161 | + out[2*i+1] = hex[sum[i]&0x0f] |
| 162 | + } |
| 163 | + return string(out) |
| 164 | +} |
0 commit comments