Embeddings
How Trayn generates vector embeddings for memory retrieval.
EmbeddingAdapter Interface
interface EmbeddingAdapter {
embed(text: string): Promise<number[]>;
}The embedding adapter converts agent internal state text into a vector for semantic similarity matching during memory retrieval.
What Gets Embedded
Each agent step generates an internal state string that captures the agent's reasoning context:
Goal: Change ticket priority to High
URL: /tickets/<id>
Recent actions: click: 'Priority dropdown' | select_option: 'High'
Last action: select_option: 'High'This internal state is embedded and stored alongside each memory. During retrieval, the current internal state is embedded and compared via cosine similarity to find relevant past experiences.
Default
The harness configures an embedding adapter automatically using your AI provider's API key. Any provider supported by the Vercel AI SDK works out of the box.
Custom Embedding Example
import type { EmbeddingAdapter } from "@trayn/memory";
import { setEmbedding } from "@trayn/memory";
class OpenAIEmbedding implements EmbeddingAdapter {
async embed(text: string): Promise<number[]> {
const response = await fetch("https://api.openai.com/v1/embeddings", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.OPENAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "text-embedding-3-small",
input: text.slice(0, 8000),
}),
});
const data = await response.json();
return data.data[0].embedding;
}
}
setEmbedding(new OpenAIEmbedding());Dependency Injection
import { setEmbedding, getEmbedding } from "@trayn/memory";
// Set a custom embedding adapter
setEmbedding(myEmbedding);
// Use the embedding adapter (falls back to GoogleEmbeddingAdapter if none set)
const vector = await getEmbedding().embed("Goal: Click the submit button");getEmbedding() falls back to the built-in adapter if no custom adapter is configured. You only need setEmbedding() when replacing the default.