OpenAiEmbeddingModel

class OpenAiEmbeddingModel(client: HttpClient, apiKey: String?, model: String = DEFAULT_MODEL, dimensions: Int? = null, headers: Map<String, String> = emptyMap(), baseUrl: String = OpenAiChatModel.OPENAI_BASE_URL, timeout: Duration? = 1.minutes) : EmbeddingModel

An EmbeddingModel that calls the embeddings API of OpenAI. Ollama, Gemini and many other servers have the same API, so this one class reaches them all, chosen by baseUrl as for OpenAiChatModel.

val client = HttpClient()

// OpenAI
val embeddings = OpenAiEmbeddingModel(client, apiKey = System.getenv("OPENAI_API_KEY"))

// A model of Ollama on this machine, pulled first with `ollama pull nomic-embed-text`.
val local = OpenAiEmbeddingModel.ollama(client, model = "nomic-embed-text")

// Gemini
val gemini = OpenAiEmbeddingModel(
client,
apiKey = geminiKey,
model = "gemini-embedding-001",
baseUrl = "https://generativelanguage.googleapis.com/v1beta/openai",
)

val store = SemanticStore(FileStore(directory), embeddings)

One call sends all the texts it gets in one request. The client is yours, as for OpenAiChatModel: share one between models, and close it when your app is done with it.

Parameters

client

the Ktor client that sends the requests.

apiKey

the key, sent as a bearer token. null for a server that needs none.

model

the id of the model.

dimensions

how long the vectors are, for a model that can make shorter ones, such as the text-embedding-3 models. null leaves the length of the model.

headers

more headers for every request.

baseUrl

where the API lives, up to and including the version: this class adds /embeddings to it.

timeout

how long one call may take. null leaves the limits of client in place.

Throws

Constructors

Link copied to clipboard
constructor(client: HttpClient, apiKey: String?, model: String = DEFAULT_MODEL, dimensions: Int? = null, headers: Map<String, String> = emptyMap(), baseUrl: String = OpenAiChatModel.OPENAI_BASE_URL, timeout: Duration? = 1.minutes)

Types

Link copied to clipboard
object Companion

Properties

Link copied to clipboard
open override val id: String

The address of the API, the model and the dimensions: https://api.openai.com/v1 text-embedding-3-small.

Functions

Link copied to clipboard
open suspend override fun embed(texts: List<String>): List<FloatArray>

Sends texts to the embeddings API and returns their vectors, in the same order.