Documentation
¶
Overview ¶
Package kjarni provides text classification, embeddings, semantic search, and reranking using pre-trained transformer models, running inside your process against a native library. Models download automatically on first use and are cached on disk, so everything after that works offline.
The same engine ships for other runtimes: Kjarni on NuGet for C#, kjarni-wasm on npm for the browser, and a command line binary. Documentation and guides live at https://kjarni.ai and the source is at https://github.com/olafurjohannsson/kjarni
Getting started ¶
import "github.com/olafurjohannsson/kjarni-go"
emb, err := kjarni.NewEmbedder("minilm-l6-v2")
if err != nil {
log.Fatal(err)
}
defer emb.Close()
vec, err := emb.Encode("hello world")
Index ¶
- func CosineSimilarity(a, b []float32) float32
- type Chat
- func (c *Chat) Close() error
- func (c *Chat) ContextSize() int
- func (c *Chat) Conversation() (*ChatConversation, error)
- func (c *Chat) ModelName() string
- func (c *Chat) Send(message string) (string, error)
- func (c *Chat) SendWithConfig(message string, config *GenerationConfig) (string, error)
- func (c *Chat) Stream(message string, onToken func(token string) bool) error
- func (c *Chat) StreamWithConfig(message string, config *GenerationConfig, onToken func(token string) bool) error
- type ChatConversation
- func (cc *ChatConversation) Clear(keepSystem bool)
- func (cc *ChatConversation) Close() error
- func (cc *ChatConversation) Length() int
- func (cc *ChatConversation) Send(message string) (string, error)
- func (cc *ChatConversation) SendWithConfig(message string, config *GenerationConfig) (string, error)
- func (cc *ChatConversation) Stream(message string, onToken func(token string) bool) error
- type ChatMode
- type ChatOption
- type Classifier
- type ClassifyResult
- type Embedder
- type ErrorCode
- type GenerationConfig
- type IndexStats
- type Indexer
- type KjarniError
- type LabelScore
- type Option
- type RerankResult
- type Reranker
- type SearchMode
- type SearchResult
- type Searcher
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CosineSimilarity ¶
CosineSimilarity computes cosine similarity between two vectors in Go.
Types ¶
type Chat ¶ added in v0.1.9
type Chat struct {
// contains filtered or unexported fields
}
func (*Chat) ContextSize ¶ added in v0.1.9
returns the model's context window size
func (*Chat) Conversation ¶ added in v0.1.9
func (c *Chat) Conversation() (*ChatConversation, error)
create a stateful conversation with history management
func (*Chat) SendWithConfig ¶ added in v0.1.9
func (c *Chat) SendWithConfig(message string, config *GenerationConfig) (string, error)
sends a message with custom generation config
func (*Chat) Stream ¶ added in v0.1.9
Stream sends a message and calls onToken for each generated token. Return false from onToken to stop generation.
func (*Chat) StreamWithConfig ¶ added in v0.1.9
func (c *Chat) StreamWithConfig(message string, config *GenerationConfig, onToken func(token string) bool) error
streams with custom generation config.
type ChatConversation ¶ added in v0.1.9
type ChatConversation struct {
// contains filtered or unexported fields
}
ChatConversation maintains chat history parent Chat must outlive this object
func (*ChatConversation) Clear ¶ added in v0.1.9
func (cc *ChatConversation) Clear(keepSystem bool)
clear the conversation history
func (*ChatConversation) Close ¶ added in v0.1.9
func (cc *ChatConversation) Close() error
release the conversation resources
func (*ChatConversation) Length ¶ added in v0.1.9
func (cc *ChatConversation) Length() int
returns the number of messages in history
func (*ChatConversation) Send ¶ added in v0.1.9
func (cc *ChatConversation) Send(message string) (string, error)
Send sends a message and returns a response Both user message and response are added to history
func (*ChatConversation) SendWithConfig ¶ added in v0.1.9
func (cc *ChatConversation) SendWithConfig(message string, config *GenerationConfig) (string, error)
send with custom generation config.
type ChatOption ¶ added in v0.1.9
type ChatOption func(*chatOptions)
func WithChatMode ¶ added in v0.1.9
func WithChatMode(mode ChatMode) ChatOption
func WithSystemPrompt ¶ added in v0.1.9
func WithSystemPrompt(prompt string) ChatOption
type Classifier ¶
type Classifier struct {
// contains filtered or unexported fields
}
Classifier runs text classification using a pre-trained model.
func NewClassifier ¶
func NewClassifier(model string, opts ...Option) (*Classifier, error)
NewClassifier creates a classifier for the given model. Available models: distilbert-sentiment, roberta-sentiment, bert-sentiment-multilingual, distilroberta-emotion, roberta-emotions, toxic-bert. Models download automatically on first use and are cached locally.
func (*Classifier) Classify ¶
func (c *Classifier) Classify(text string) (*ClassifyResult, error)
Classify runs the model on the given text and returns scored labels.
func (*Classifier) Close ¶
func (c *Classifier) Close() error
Close releases the classifier resources. Safe to call multiple times.
func (*Classifier) NumLabels ¶
func (c *Classifier) NumLabels() int
NumLabels returns the number of labels the model supports.
type ClassifyResult ¶
type ClassifyResult struct {
Label string
Score float32
AllScores []LabelScore
}
ClassifyResult holds the output of a classification. Label and Score contain the top prediction. AllScores contains scores for every label.
func (*ClassifyResult) String ¶
func (r *ClassifyResult) String() string
String returns the result as "label (score%)".
func (*ClassifyResult) ToJSON ¶
func (r *ClassifyResult) ToJSON() string
ToJSON returns the result as a JSON string.
type Embedder ¶
type Embedder struct {
// contains filtered or unexported fields
}
Embedder encodes text into vector embeddings for similarity and search.
func NewEmbedder ¶
NewEmbedder creates an embedder for the given model. Available models: minilm-l6-v2 (384d), mpnet-base-v2 (768d), distilbert-base (768d). Models download automatically on first use and are cached locally.
func (*Embedder) EncodeBatch ¶
EncodeBatch encodes multiple texts and returns their embedding vectors.
type ErrorCode ¶
type ErrorCode int32
ErrorCode represents error codes returned by the kjarni engine.
const ( ErrOk ErrorCode = 0 ErrNullPointer ErrorCode = 1 ErrInvalidUtf8 ErrorCode = 2 ErrModelNotFound ErrorCode = 3 ErrLoadFailed ErrorCode = 4 ErrInferenceFailed ErrorCode = 5 ErrInvalidConfig ErrorCode = 7 ErrCancelled ErrorCode = 8 ErrTimeout ErrorCode = 9 ErrStreamEnded ErrorCode = 10 // ErrPanic reports a panic in the native engine caught at the ABI boundary. The // operation failed and its outputs are undefined; the handle stays valid to Close. ErrPanic ErrorCode = 11 ErrUnknown ErrorCode = 255 )
type GenerationConfig ¶ added in v0.1.9
type GenerationConfig struct {
Temperature float32
TopK int32
TopP float32
MinP float32
RepetitionPenalty float32
MaxNewTokens int32
DoSample int32
}
func CreativeGenerationConfig ¶ added in v0.1.9
func CreativeGenerationConfig() GenerationConfig
func DefaultGenerationConfig ¶ added in v0.1.9
func DefaultGenerationConfig() GenerationConfig
func GreedyGenerationConfig ¶ added in v0.1.9
func GreedyGenerationConfig() GenerationConfig
type IndexStats ¶
type IndexStats struct {
DocumentsIndexed int
ChunksCreated int
Dimension int
SizeBytes uint64
FilesProcessed int
FilesSkipped int
ElapsedMs uint64
}
IndexStats holds statistics from an indexing operation.
type Indexer ¶
type Indexer struct {
// contains filtered or unexported fields
}
Indexer creates search indexes from files in a directory.
func NewIndexer ¶
NewIndexer creates an indexer using the given embedding model. The model is used to generate vectors for each text chunk during indexing.
type KjarniError ¶
KjarniError is an error returned by the kjarni engine.
func (*KjarniError) Error ¶
func (e *KjarniError) Error() string
type LabelScore ¶
LabelScore is a single label with its confidence score.
type Option ¶
type Option func(*options)
Option configures a classifier, embedder, or other kjarni component.
func WithDevice ¶
WithDevice sets the compute device. Supported values: "cpu", "gpu".
type RerankResult ¶
RerankResult holds a single reranked document with its relevance score.
type Reranker ¶
type Reranker struct {
// contains filtered or unexported fields
}
Reranker scores query-document relevance using a cross-encoder model.
func NewReranker ¶
NewReranker creates a reranker using the default cross-encoder model. The model downloads automatically on first use and is cached locally.
func (*Reranker) Rerank ¶
func (r *Reranker) Rerank(query string, documents []string) ([]RerankResult, error)
Rerank scores all documents and returns them sorted by relevance to the query.
func (*Reranker) RerankTopK ¶
RerankTopK scores all documents and returns the top k sorted by relevance.
type SearchMode ¶
type SearchMode int
SearchMode determines the search strategy.
const ( // Keyword uses BM25 term matching. Keyword SearchMode = 0 // Semantic uses vector similarity. Semantic SearchMode = 1 // Hybrid combines BM25 and vector similarity. Hybrid SearchMode = 2 )
type SearchResult ¶
SearchResult holds a single search result with its relevance score.
type Searcher ¶
type Searcher struct {
// contains filtered or unexported fields
}
Searcher queries indexes created by an Indexer.
func NewSearcher ¶
NewSearcher creates a searcher using the given embedding model. Pass a non-empty rerankerModel to enable cross-encoder reranking of results. Pass an empty string to disable reranking.
func (*Searcher) Search ¶
func (s *Searcher) Search(indexPath string, query string, mode SearchMode) ([]SearchResult, error)
Search queries the index at indexPath and returns results using the given mode.
