chromago

package module
v0.0.0-...-db61c00 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 18, 2025 License: MIT Imports: 17 Imported by: 0

README

Chroma Go

A simple Chroma Vector Database client written in Go

Works with Chroma Version: v0.4.3 - v1.0.x

We invite users to visit the docs site for the library for more in-depth information: Chroma Go Docs

[!NOTE] v0.2.0 documentation is still being updated. Please consult the tests under pkg/api/v2 for more detailed usage examples. We are working on updating the documentation with full usage examples (also feel free to contribute if you have any examples you would like to share).

Feature Parity with ChromaDB API

Operation V1 support V2 support
Create Tenant
Get Tenant
Create Database
Get Database
Delete Database
Reset
Heartbeat
List Collections
Count Collections
Get Version
Create Collection
Delete Collection
Collection Add
Collection Get
Collection Count
Collection Query
Collection Update
Collection Upsert
Collection Delete (delete documents)
Modify Collection ⚒️ partial

Additional support features:

  • Authentication (Basic, Token with Authorization header, Token with X-Chroma-Token header)
  • Private PKI and self-signed certificate support
  • ✅ Chroma Cloud support
  • ⚒️ Persistent Embedding Function support (coming soon) - automatically load embedding function from Chroma collection configuration
  • ⚒️ Persistent Client support (coming soon) - Run/embed full-featured Chroma in your go application without the need for Chroma server.

Embedding API and Models Support

HuggingFace Embedding Inference Server Support

Reranking Functions

From release 0.2.0 the Chroma Go client also supports Reranking functions. The following are supported:

Installation

[!IMPORTANT]
There are many new changes leading up to v0.2.0, as documented below. If you'd like to use them please install the latest version of the client.

go get github.com/amikos-tech/chroma-go@main
go get github.com/amikos-tech/chroma-go

Import v1:

import (
chroma "github.com/amikos-tech/chroma-go"
)

Usage

Ensure you have a running instance of Chroma running. We recommend one of the two following options:

The Setup (Cloud-native):

minikube start --profile chromago
minikube profile chromago
helm repo add chroma https://amikos-tech.github.io/chromadb-chart/
helm repo update
helm install chroma chroma/chromadb --set chromadb.allowReset=true,chromadb.apiVersion=0.

[!NOTE] To delete the minikube cluster: minikube delete --profile chromago

Getting Started (Chroma API v2)
  • We create a new collection
  • Add documents using the default embedding function
  • Query the collection using the same embedding function
  • Delete documents from the collection
package main

import (
	"context"
	"fmt"
	"log"

	chroma "github.com/amikos-tech/chroma-go/pkg/api/v2"
)

func main() {
	// Create a new Chroma client
	client, err := chroma.NewHTTPClient()
	if err != nil {
		log.Fatalf("Error creating client: %s \n", err)
		return
	}
	// Close the client to release any resources such as local embedding functions
	defer func() {
		err = client.Close()
		if err != nil {
			log.Fatalf("Error closing client: %s \n", err)
		}
	}()

	// Create a new collection with options. We don't provide an embedding function here, so the default embedding function will be used
	col, err := client.GetOrCreateCollection(context.Background(), "col1",
		chroma.WithCollectionMetadataCreate(
			chroma.NewMetadata(
				chroma.NewStringAttribute("str", "hello"),
				chroma.NewIntAttribute("int", 1),
				chroma.NewFloatAttribute("float", 1.1),
			),
		),
	)
	if err != nil {
		log.Fatalf("Error creating collection: %s \n", err)
		return
	}

	err = col.Add(context.Background(),
		//chroma.WithIDGenerator(chroma.NewULIDGenerator()),
		chroma.WithIDs("1", "2"),
		chroma.WithTexts("hello world", "goodbye world"),
		chroma.WithMetadatas(
			chroma.NewDocumentMetadata(chroma.NewIntAttribute("int", 1)),
			chroma.NewDocumentMetadata(chroma.NewStringAttribute("str", "hello")),
		))
	if err != nil {
		log.Fatalf("Error adding collection: %s \n", err)
	}

	count, err := col.Count(context.Background())
	if err != nil {
		log.Fatalf("Error counting collection: %s \n", err)
		return
	}
	fmt.Printf("Count collection: %d\n", count)

	qr, err := col.Query(context.Background(), chroma.WithQueryTexts("say hello"))
	if err != nil {
		log.Fatalf("Error querying collection: %s \n", err)
		return
	}
	fmt.Printf("Query result: %v\n", qr.GetDocumentsGroups()[0][0])

	err = col.Delete(context.Background(), chroma.WithIDsDelete("1", "2"))
	if err != nil {
		log.Fatalf("Error deleting collection: %s \n", err)
		return
	}
}

Development

Build
make build
Test

V1 API:

make test

V2 API:

make test-v2
Generate ChromaDB API Client (only for v1)
make generate 
Lint
make lint-fix
Local Server

Note: Docker must be installed

make server

References

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func APIEmbeddingToEmbedding

func APIEmbeddingToEmbedding(embedding openapiclient.EmbeddingsInner) *types.Embedding

func APIEmbeddingsToEmbeddings

func APIEmbeddingsToEmbeddings(embeddings []openapiclient.EmbeddingsInner) []*types.Embedding

func GetStringTypeOfEmbeddingFunction

func GetStringTypeOfEmbeddingFunction(ef types.EmbeddingFunction) string

Types

type Client

type Client struct {
	ApiClient  *openapiclient.APIClient //nolint
	Tenant     string
	Database   string
	APIVersion semver.Version

	BasePath string
	// contains filtered or unexported fields
}

Client represents the ChromaDB Client

func NewClient

func NewClient(options ...ClientOption) (*Client, error)

func (*Client) Close

func (c *Client) Close() error

Close closes the client and all closeable resources

func (*Client) CountCollections

func (c *Client) CountCollections(ctx context.Context) (int32, error)

CountCollections returns the number of collections in the database

func (*Client) CreateCollection

func (c *Client) CreateCollection(ctx context.Context, collectionName string, metadata map[string]interface{}, createOrGet bool, embeddingFunction types.EmbeddingFunction, distanceFunction types.DistanceFunction) (*Collection, error)

CreateCollection [legacy] creates a new collection with the given name, metadata, embedding function and distance function

func (*Client) CreateDatabase

func (c *Client) CreateDatabase(ctx context.Context, databaseName string, tenantName *string) (*openapiclient.Database, error)

CreateDatabase creates a new database with the given name, fails if the database already exists

func (*Client) CreateTenant

func (c *Client) CreateTenant(ctx context.Context, tenantName string) (*openapiclient.Tenant, error)

CreateTenant creates a new tenant with the given name, fails if the tenant already exists

func (*Client) DeleteCollection

func (c *Client) DeleteCollection(ctx context.Context, collectionName string) (*Collection, error)

DeleteCollection deletes the collection with the given name

func (*Client) GetCollection

func (c *Client) GetCollection(ctx context.Context, collectionName string, embeddingFunction types.EmbeddingFunction) (*Collection, error)

GetCollection returns an instance of a collection object which can be used to interact with the collection data.

func (*Client) GetDatabase

func (c *Client) GetDatabase(ctx context.Context, databaseName string, tenantName *string) (*openapiclient.Database, error)

GetDatabase returns the database with the given name, fails if the database does not exist

func (*Client) GetTenant

func (c *Client) GetTenant(ctx context.Context, tenantName string) (*openapiclient.Tenant, error)

GetTenant returns the tenant with the given name, fails if the tenant does not exist

func (*Client) Heartbeat

func (c *Client) Heartbeat(ctx context.Context) (map[string]float32, error)

Heartbeat checks whether the Chroma server is up and running returns a map[string]float32 with the current server timestamp

func (*Client) ListCollections

func (c *Client) ListCollections(ctx context.Context) ([]*Collection, error)

ListCollections returns a list of all collections in the database

func (*Client) NewCollection

func (c *Client) NewCollection(ctx context.Context, name string, options ...collection.Option) (*Collection, error)

NewCollection creates a new collection with the given name and options

func (*Client) PreflightChecks

func (c *Client) PreflightChecks(ctx context.Context) (map[string]interface{}, error)

PreflightChecks returns the preflight checks of the Chroma server, returns a map of the preflight checks. Currently on max_batch_size supported by the server is returned

func (*Client) Reset

func (c *Client) Reset(ctx context.Context) (bool, error)

Reset deletes all data in the Chroma server if `ALLOW_RESET` is set to true in the environment variables of the server, otherwise fails

func (*Client) SetDatabase

func (c *Client) SetDatabase(database string)

func (*Client) SetTenant

func (c *Client) SetTenant(tenant string)

func (*Client) Version

func (c *Client) Version(ctx context.Context) (string, error)

Version returns the version of the Chroma server

type ClientConfiguration

type ClientConfiguration struct {
	BasePath          string                  `json:"basePath,omitempty"`
	DefaultHeaders    map[string]string       `json:"defaultHeader,omitempty"`
	EmbeddingFunction types.EmbeddingFunction `json:"embeddingFunction,omitempty"`
}

type ClientOption

type ClientOption func(p *Client) error

func WithAuth

func WithAuth(provider types.CredentialsProvider) ClientOption

func WithBasePath

func WithBasePath(basePath string) ClientOption

WithBasePath sets the base path for the client. The base path must be a valid URL.

func WithDatabase

func WithDatabase(database string) ClientOption

func WithDebug

func WithDebug(debug bool) ClientOption

func WithDefaultHeaders

func WithDefaultHeaders(headers map[string]string) ClientOption

func WithHTTPClient

func WithHTTPClient(client *http.Client) ClientOption

WithHTTPClient sets a custom http.Client for the client. The option is mutually exclusive with WithSSLCert and WithIgnoreSSLCert.

func WithInsecure

func WithInsecure() ClientOption

WithInsecure disables SSL certificate verification. This option is not recommended for production use. The option is mutually exclusive with WithHttpClient.

func WithSSLCert

func WithSSLCert(certPath string) ClientOption

WithSSLCert adds a custom SSL certificate to the client. The certificate must be in PEM format. The Option can be added multiple times to add multiple certificates. The option is mutually exclusive with WithHttpClient.

func WithTenant

func WithTenant(tenant string) ClientOption

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout sets the timeout for the client

type Collection

type Collection struct {
	Name              string
	EmbeddingFunction types.EmbeddingFunction
	ApiClient         *openapiclient.APIClient //nolint
	Metadata          map[string]interface{}
	ID                string
	Tenant            string
	Database          string
	// contains filtered or unexported fields
}

func NewCollection

func NewCollection(chromaClient *Client, id string, name string, metadata *map[string]interface{}, embeddingFunction types.EmbeddingFunction, tenant string, database string) *Collection

func (*Collection) Add

func (c *Collection) Add(ctx context.Context, embeddings []*types.Embedding, metadatas []map[string]interface{}, documents []string, ids []string) (*Collection, error)

func (*Collection) AddRecords

func (c *Collection) AddRecords(ctx context.Context, recordSet *types.RecordSet) (*Collection, error)

func (*Collection) Count

func (c *Collection) Count(ctx context.Context) (int32, error)

func (*Collection) Delete

func (c *Collection) Delete(ctx context.Context, ids []string, where map[string]interface{}, whereDocuments map[string]interface{}) ([]string, error)

func (*Collection) Get

func (c *Collection) Get(ctx context.Context, where map[string]interface{}, whereDocuments map[string]interface{}, ids []string, include []types.QueryEnum) (*GetResults, error)

func (*Collection) GetWithOptions

func (c *Collection) GetWithOptions(ctx context.Context, options ...types.CollectionQueryOption) (*GetResults, error)

func (*Collection) Modify

func (c *Collection) Modify(ctx context.Context, embeddings []*types.Embedding, metadatas []map[string]interface{}, documents []string, ids []string) (*Collection, error)

func (*Collection) Query

func (c *Collection) Query(ctx context.Context, queryTexts []string, nResults int32, where map[string]interface{}, whereDocuments map[string]interface{}, include []types.QueryEnum) (*QueryResults, error)

func (*Collection) QueryWithOptions

func (c *Collection) QueryWithOptions(ctx context.Context, queryOptions ...types.CollectionQueryOption) (*QueryResults, error)

func (*Collection) String

func (c *Collection) String() string

func (*Collection) Update

func (c *Collection) Update(ctx context.Context, newName string, newMetadata *map[string]interface{}) (*Collection, error)

func (*Collection) Upsert

func (c *Collection) Upsert(ctx context.Context, embeddings []*types.Embedding, metadatas []map[string]interface{}, documents []string, ids []string) (*Collection, error)

type GetResults

type GetResults struct {
	Ids        []string
	Documents  []string
	Metadatas  []map[string]interface{}
	Embeddings []*types.Embedding
}

type QueryResults

type QueryResults struct {
	Documents                     [][]string                 `json:"documents,omitempty"`
	Ids                           [][]string                 `json:"ids,omitempty"`
	Metadatas                     [][]map[string]interface{} `json:"metadatas,omitempty"`
	Distances                     [][]float32                `json:"distances,omitempty"`
	QueryTexts                    []string
	QueryEmbeddings               []*types.Embedding
	QueryTextsGeneratedEmbeddings []*types.Embedding // the generated embeddings from the query texts
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL