How to Create a Mock Text Embedding with Hash in Python
Generate deterministic mock text embeddings using SHA-256 hashing and numpy, producing normalized vectors for similarity testing without an LLM.
pip install numpy
Python code
41 linesimport hashlib
import numpy as np
def mock_embed(text: str, dim: int = 10, seed: int = 42) -> np.ndarray:
"""Generate a deterministic mock embedding using a hash function.
Args:
text: Input text to embed
dim: Dimension of the output vector
seed: Seed for reproducibility
Returns:
A normalized numpy array of shape (dim,)
"""
# Generate a stable hash digest for the text
digest = hashlib.sha256(text.encode("utf-8")).hexdigest()
# Use the digest to seed a deterministic random generator
rng = np.random.default_rng(int(digest[:16], 16) + seed)
# Generate a random vector and normalize it
vector = rng.random(dim)
vector = vector / np.linalg.norm(vector)
return vector
if __name__ == "__main__":
text1 = "python programming"
text2 = "python programming"
text3 = "data science"
emb1 = mock_embed(text1)
emb2 = mock_embed(text2)
emb3 = mock_embed(text3)
print(f"Embedding for '{text1}':")
print(emb1)
print(f"\nEmbedding for '{text3}':")
print(emb3)
print(f"\nSame text similarity (cosine): {np.dot(emb1, emb2):.4f}")
print(f"Different text similarity (cosine): {np.dot(emb1, emb3):.4f}")
Output
Embedding for 'python programming':
[0.12525989 0.26839404 0.24422726 0.38499417 0.17679481 0.39039614
0.40300076 0.43729981 0.23967442 0.3073059 ]
Embedding for 'data science':
[0.39072291 0.27881229 0.46902804 0.15333729 0.36787263 0.29023124
0.46937402 0.32388022 0.21655173 0.16279026]
Same text similarity (cosine): 1.0000
Different text similarity (cosine): 0.8651
How it works
The hashlib.sha256 call creates a stable digest from the text, which seeds a numpy generator via np.random.default_rng. This ensures identical text always produces the same embedding. The vector is normalized to unit length so cosine similarity equals the dot product, making it easy to compare texts. This approach mimics the behavior of real embedding models but requires no API calls or heavy dependencies. Use the seed parameter to shift results across test runs while keeping reproducibility.
Common mistakes
- Using Python's built-in `hash()` which is randomized per process and unreliable for persistence
- Forgetting to normalize the vector, making cosine similarity calculations incorrect
- Slicing the digest incorrectly (e.g., `digest[:8]` gives only 4 bytes of entropy)
- Reusing the same random seed for all texts, causing identical embeddings
Variations
- Use `hashlib.md5` for faster but weaker hash functions in low-security contexts
- Generate integer vectors instead of floats by applying `np.arange(dim)` permutation from the seed
Real-world use cases
- Testing vector database pipelines locally without spending on embedding API calls.
- Building deterministic fixtures for unit tests that compare embedding-based features.
- Prototyping retrieval-augmented generation (RAG) flows with realistic vector distributions.
Sponsored
More from AI & LLM integration patterns
- Cache LLM Completions by Hashing the Prompt in Python easy
- Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo easy
- Circuit Breaker Pattern in Python for LLM API Calls medium
- Cosine Similarity to Retrieve Top K Chunks in Python easy
- Demonstrate Prompt Injection Bypass in Python easy
- How to Accumulate Streamed Tokens into a Final String in Python easy
Keep learning
Related tutorials and quizzes for this topic.