AI
Embeddings
Find texts by meaning, and answer questions from your own documents.
Searching with keywords misses "how long do refunds take?" when your document says "money is returned within 5 working days" (no shared words). An embedding turns a text into a list of numbers so that texts with similar meaning are close together. Then "search" is "find the stored texts closest to the question".
KnowledgeBase stores texts with their embeddings and searches them:
val kb = ai.knowledgeBase() // needs AiModule.forRoot { embeddings = ... }
kb.add("refunds", "Refunds are paid back within 5 working days.", metadata = mapOf("lang" to "en"))
kb.addAll(mapOf("shipping" to "Orders ship within 24 hours.", "returns" to "You can return items within 30 days."))
val hits = kb.search("how long do refunds take?", k = 3) { it["lang"] == "en" } // the 3 closest, only English ones
hits.first().text // "Refunds are paid back within 5 working days."
hits.first().score // cosine similarity, 0..1 (higher = closer)Answer from your own documents (RAG)
Retrieval-augmented generation: search first, then give the best passages to the model as context, so it answers from your facts instead of guessing:
fun answer(question: String): String {
val context = kb.search(question, 4).joinToString("\n") { it.text }
return ai.chat(
"Answer using ONLY this information. If it is not there, say you do not know.\n\n$context\n\nQuestion: $question",
system = "You are a support assistant.",
)
}Tips
- Split documents into passages of a few sentences to a paragraph before adding them; one giant embedding is too vague.
- Store metadata (language, product, source) and filter by it.
- Re-index when documents change (
addwith the same id replaces it). - Show sources to the user (the
idof each hit) so answers can be checked.
Stores and models
InMemoryVectorStore (the default) suits thousands to low hundreds of thousands of texts in one process and loses them on restart: re-index at start-up, or implement VectorStore (add, remove, search, size) over a vector database for more or for persistence. OpenAiEmbeddings works with OpenAI and any compatible server (set baseUrl); implement EmbeddingModel for another provider.