### Complete Cloud Client Example in Go Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/go-examples/docs/run-chroma/cloud-client.md A comprehensive example demonstrating how to initialize the Chroma Cloud client using environment variables, create or get a collection, add documents, and query the collection. Remember to defer client closing. ```go package main import ( "context" "log" "os" v2 "github.com/amikos-tech/chroma-go/pkg/api/v2" ) func main() { // Create Cloud client client, err := v2.NewCloudClient( v2.WithCloudAPIKey(os.Getenv("CHROMA_CLOUD_API_KEY")), v2.WithDatabaseAndTenant( os.Getenv("CHROMA_CLOUD_DATABASE"), os.Getenv("CHROMA_CLOUD_TENANT"), ), ) if err != nil { log.Fatalf("Error creating cloud client: %v", err) } defer client.Close() ctx := context.Background() // Create or get a collection collection, err := client.GetOrCreateCollection(ctx, "my_cloud_collection") if err != nil { log.Fatalf("Error creating collection: %v", err) } // Add documents err = collection.Add(ctx, v2.WithIDs("doc1", "doc2"), v2.WithTexts( "This is a document about machine learning", "This is a document about data science", ), ) if err != nil { log.Fatalf("Error adding documents: %v", err) } // Query the collection results, err := collection.Query(ctx, v2.WithQueryTexts("AI and ML"), v2.WithNResults(2), ) if err != nil { log.Fatalf("Error querying collection: %v", err) } log.Printf("Query results: %v", results.GetDocumentsGroups()) } ``` -------------------------------- ### Quick Start: Chroma Go Client Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/docs/index.md A comprehensive example demonstrating client creation, collection management, adding documents with metadata, and querying for similar documents. ```go package main import ( "context" "fmt" "log" chroma "github.com/amikos-tech/chroma-go/pkg/api/v2" ) func main() { ctx := context.Background() // Create client (connects to localhost:8000 by default) client, err := chroma.NewHTTPClient() if err != nil { log.Fatalf("Error creating client: %s", err) } defer client.Close() // Create or get a collection col, err := client.GetOrCreateCollection(ctx, "my-collection") if err != nil { log.Fatalf("Error creating collection: %s", err) } // Add documents err = col.Add(ctx, chroma.WithIDs("doc1", "doc2", "doc3"), chroma.WithTexts( "Machine learning is a subset of AI", "Natural language processing enables computers to understand text", "Deep learning uses neural networks with many layers", ), chroma.WithMetadatas( map[string]any{"category": "ml", "year": 2024}, map[string]any{"category": "nlp", "year": 2024}, map[string]any{"category": "dl", "year": 2023}, ), ) if err != nil { log.Fatalf("Error adding documents: %s", err) } // Query for similar documents results, err := col.Query(ctx, chroma.WithQueryTexts("What is artificial intelligence?"), chroma.WithNResults(2), ) if err != nil { log.Fatalf("Error querying: %s", err) } fmt.Printf("Found %d results\n", len(results.GetIDsGroups()[0])) for i, doc := range results.GetDocumentsGroups()[0] { fmt.Printf(" %d: %s\n", i+1, doc) } } ``` -------------------------------- ### Install Chroma-go Client (v0.2.4) Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/docs/client.md To use the examples for client versions v0.1.4 or lower, pin your dependency to v0.2.4 or earlier. This command installs the specified version of the chroma-go library. ```bash go get github.com/amikos-tech/chroma-go@v0.2.4 ``` -------------------------------- ### Complete Hybrid Search Example Setup (Python) Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/go-examples/cloud/schema/sparse-vector-search.md Initialize a ChromaDB client for cloud deployment and set up schema configurations for vector indexes, including sparse vector index configuration. ```python import chromadb from chromadb import Schema, SparseVectorIndexConfig, VectorIndexConfig, K, Search, Knn, Rrf from chromadb.utils.embedding_functions import OpenAIEmbeddingFunction, ChromaCloudSpladeEmbeddingFunction # Create client client = chromadb.CloudClient( tenant="your-tenant", database="your-database", api_key="your-api-key" ) ``` -------------------------------- ### Complete Chroma Go Client Example Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/go-examples/docs/cli/run.md This example shows how to connect to a ChromaDB server, perform basic operations like checking the heartbeat and version, creating or getting a collection, adding documents, and querying the collection. Ensure the Chroma server is running before executing this code. Use `defer client.Close()` to release resources. ```go package main import ( "context" "fmt" "log" v2 "github.com/amikos-tech/chroma-go/pkg/api/v2" ) func main() { // Create client client, err := v2.NewHTTPClient( v2.WithBaseURL("http://localhost:8000"), ) if err != nil { log.Fatalf("Error creating client: %v", err) } defer client.Close() ctx := context.Background() // Check connection heartbeat, err := client.Heartbeat(ctx) if err != nil { log.Fatalf("Server not responding: %v", err) } fmt.Printf("Connected! Heartbeat: %d\n", heartbeat) // Get server version version, err := client.Version(ctx) if err != nil { log.Fatalf("Error getting version: %v", err) } fmt.Printf("Chroma version: %s\n", version) // Create or get a collection collection, err := client.GetOrCreateCollection(ctx, "my_collection") if err != nil { log.Fatalf("Error with collection: %v", err) } fmt.Printf("Using collection: %s\n", collection.Name()) // Add documents err = collection.Add(ctx, v2.WithIDs("doc1", "doc2", "doc3"), v2.WithDocuments( "The quick brown fox", "Machine learning basics", "Vector database concepts", ), ) if err != nil { log.Fatalf("Error adding documents: %v", err) } fmt.Println("Documents added successfully") // Query the collection results, err := collection.Query(ctx, v2.WithQueryTexts("fox"), v2.WithNResults(2), ) if err != nil { log.Fatalf("Error querying: %v", err) } fmt.Printf("\nQuery results:\n") for i, row := range results.Rows() { fmt.Printf(" %d. %s\n", i+1, row.ID) } } ``` -------------------------------- ### Run All Examples Source: https://github.com/amikos-tech/chroma-go/blob/main/examples/v2/auth/README.md Execute this command to see all available authentication examples. ```bash go run main.go ``` -------------------------------- ### Complete Example: Upsert and Query in Go Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/go-examples/docs/overview/getting-started.md A full example demonstrating how to initialize the Chroma-Go HTTP client, get or create a collection, upsert documents, and then query the collection. Remember to use `defer client.Close()` and provide a `context.Context` for all operations. ```go package main import ( "context" "log" v2 "github.com/amikos-tech/chroma-go/pkg/api/v2" ) func main() { // Create client (requires running Chroma server) client, err := v2.NewHTTPClient() if err != nil { log.Fatalf("Error creating client: %v", err) } defer client.Close() ctx := context.Background() // Get or create collection collection, err := client.GetOrCreateCollection(ctx, "my_collection") if err != nil { log.Fatalf("Error getting collection: %v", err) } // Upsert documents (insert or update) err = collection.Upsert(ctx, v2.WithIDs("id1", "id2"), v2.WithTexts( "This is a document about pineapple", "This is a document about oranges", ), ) if err != nil { log.Fatalf("Error upserting documents: %v", err) } // Query the collection results, err := collection.Query(ctx, v2.WithQueryTexts("This is a query document about florida"), v2.WithNResults(2), ) if err != nil { log.Fatalf("Error querying: %v", err) } // Print results log.Printf("Documents: %v", results.GetDocumentsGroups()) log.Printf("IDs: %v", results.GetIDsGroups()) log.Printf("Distances: %v", results.GetDistances()) } ``` -------------------------------- ### Start Local Chroma Server Source: https://github.com/amikos-tech/chroma-go/blob/main/README.md Start a local Chroma server. Ensure Docker is installed and running before executing this command. ```bash make server ``` -------------------------------- ### Run Schema Examples Source: https://github.com/amikos-tech/chroma-go/blob/main/examples/v2/schema/README.md Navigate to the examples directory and run the main Go program to execute all schema examples. ```bash cd examples/v2/schema go run . ``` -------------------------------- ### Run Local Persistent Client Example Source: https://github.com/amikos-tech/chroma-go/blob/main/examples/v2/persistent_client/README.md Navigate to the example directory and execute the Go program to run the local persistent client. ```bash cd examples/v2/persistent_client go run . ``` -------------------------------- ### Run Local Chroma Instance Source: https://github.com/amikos-tech/chroma-go/blob/main/examples/v2/auth/README.md Start a local Chroma instance using Docker. This is a prerequisite for self-hosted examples. ```bash docker run -p 8000:8000 chromadb/chroma ``` -------------------------------- ### Basic Authentication Example Source: https://github.com/amikos-tech/chroma-go/blob/main/examples/v2/auth/README.md Run the basic authentication example. Ensure CHROMA_AUTH_USERNAME and CHROMA_AUTH_PASSWORD environment variables are set. ```bash # Set required environment variables export CHROMA_AUTH_USERNAME="admin" export CHROMA_AUTH_PASSWORD="your-password" export CHROMA_URL="http://localhost:8000" # optional, defaults to localhost:8000 # Run the example go run main.go -example=basic ``` -------------------------------- ### Running the Example Source: https://github.com/amikos-tech/chroma-go/blob/main/examples/v2/embedding_function_basic/README.md Download Go modules and run the main application. Ensure the OPENAI_API_KEY environment variable is set. ```bash go mod download OPENAI_API_KEY=sk-xxxxx go run main.go ``` -------------------------------- ### X-Chroma-Token Authentication Example Source: https://github.com/amikos-tech/chroma-go/blob/main/examples/v2/auth/README.md Run the X-Chroma-Token authentication example. Set the CHROMA_AUTH_TOKEN environment variable. ```bash # Set required environment variables export CHROMA_AUTH_TOKEN="your-chroma-token" export CHROMA_URL="http://localhost:8000" # optional # Run the example go run main.go -example=x-chroma-token ``` -------------------------------- ### Run Metadata Filtering Example Source: https://github.com/amikos-tech/chroma-go/blob/main/examples/v2/metadata_filters/README.md Navigate to the example directory and execute the provided make command to run the metadata filtering demonstration. ```bash cd examples/v2/metadata_filters make run ``` -------------------------------- ### Chroma Cloud Authentication Example Source: https://github.com/amikos-tech/chroma-go/blob/main/examples/v2/auth/README.md Run the Chroma Cloud authentication example. Set the CHROMA_CLOUD_API_KEY environment variable. Tenant and database are optional. ```bash # Set required environment variables export CHROMA_CLOUD_API_KEY="your-api-key" export CHROMA_CLOUD_TENANT="your-tenant" # optional, defaults shown export CHROMA_CLOUD_DATABASE="your-database" # optional, defaults shown # Run the example go run main.go -example=cloud ``` -------------------------------- ### Go Client Connection and Operation Example Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/go-examples/docs/overview/telemetry.md Connect to a Chroma server using the Go client and perform basic operations like getting or creating a collection and adding a document. Telemetry tracking depends on the server's configuration. ```go package main import ( "context" "log" v2 "github.com/amikos-tech/chroma-go/pkg/api/v2" ) func main() { // Connect to Chroma server (telemetry status depends on server config) client, err := v2.NewHTTPClient() if err != nil { log.Fatalf("Error: %v", err) } defer client.Close() ctx := context.Background() // Check connection heartbeat, err := client.Heartbeat(ctx) if err != nil { log.Fatalf("Server not responding: %v", err) } log.Printf("Connected to Chroma server. Heartbeat: %d", heartbeat) // Your application code... collection, err := client.GetOrCreateCollection(ctx, "my_collection") if err != nil { log.Fatalf("Error: %v", err) } // Operations here are tracked by server telemetry (if enabled) err = collection.Add(ctx, v2.WithIDs("doc1"), v2.WithDocuments("Sample document"), ) if err != nil { log.Fatalf("Error: %v", err) } log.Printf("Document added to collection: %s", collection.Name()) } ``` -------------------------------- ### Custom Headers Authentication Example Source: https://github.com/amikos-tech/chroma-go/blob/main/examples/v2/auth/README.md Run the custom headers authentication example. Set either AUTH_TOKEN or API_KEY environment variables. ```bash # Set at least one of these export AUTH_TOKEN="your-bearer-token" export API_KEY="your-api-key" export CHROMA_URL="http://localhost:8000" # optional # Run the example go run main.go -example=custom-headers ``` -------------------------------- ### Setup Offline Runtime Dependencies (Bash) Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/docs/embeddings.md Run the provided script to download all necessary native artifacts for offline runtime setup. Then, source the environment script to load the variables for your session. ```bash ./scripts/fetch_runtime_deps.sh ``` ```bash . artifacts/runtime-deps/runtime-env.sh ``` -------------------------------- ### Basic KNN Ranking with Text Query in Go Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/go-examples/cloud/search-api/ranking.md Perform a basic KNN search using a text query. This example shows how to set up the client, get a collection, and execute a search with a default limit. It also demonstrates how to specify a custom KNN limit to search a larger pool of results before applying the final limit. ```Go package main import ( "context" "log" v2 "github.com/amikos-tech/chroma-go/pkg/api/v2" ) func main() { client, err := v2.NewCloudClient( v2.WithCloudAPIKey("your-api-key"), v2.WithDatabaseAndTenant("database", "tenant"), ) if err != nil { log.Fatalf("Error: %v", err) } defer client.Close() ctx := context.Background() collection, err := client.GetCollection(ctx, "my_collection") if err != nil { log.Fatalf("Error: %v", err) } // Text query (auto-embedded) result1, err := collection.Search(ctx, v2.NewSearchRequest( v2.WithKnnRank(v2.KnnQueryText("machine learning research")), v2.NewPage(v2.Limit(10)), v2.WithSelect(v2.KDocument, v2.KScore), ), ) if err != nil { log.Fatalf("Error: %v", err) } // With custom KNN limit (larger pool before final limit) result2, err := collection.Search(ctx, v2.NewSearchRequest( v2.WithKnnRank( v2.KnnQueryText("AI applications"), v2.WithKnnLimit(100), ), v2.NewPage(v2.Limit(10)), v2.WithSelect(v2.KDocument, v2.KScore), ), ) if err != nil { log.Fatalf("Error: %v", err) } log.Printf("Results: %v, %v", result1, result2) } ``` -------------------------------- ### Installing Chroma-Go Client Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/go-examples/README.md Provides the command to install the chroma-go client library using the Go module system. Ensure you have Go 1.21+ and a Chroma server running. ```bash go get github.com/amikos-tech/chroma-go ``` -------------------------------- ### Bearer Token Authentication Example Source: https://github.com/amikos-tech/chroma-go/blob/main/examples/v2/auth/README.md Run the bearer token authentication example. Set the CHROMA_AUTH_TOKEN environment variable. ```bash # Set required environment variables export CHROMA_AUTH_TOKEN="your-bearer-token" export CHROMA_URL="http://localhost:8000" # optional # Run the example go run main.go -example=bearer ``` -------------------------------- ### Install Truss Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/docs/embeddings.md Command to install the Truss library for deploying models on Baseten. ```bash pip install truss ``` -------------------------------- ### Install Twelve Labs Embedding Function Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/docs/embeddings.md Provides the go get command to install the Twelve Labs embedding function package. ```bash go get github.com/amikos-tech/chroma-go/pkg/embeddings/twelvelabs ``` -------------------------------- ### Collection Operations Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/go-examples/README.md Examples for creating, getting, listing, and deleting collections. ```APIDOC ## Collection Operations ### Create/Get Collection This operation creates a new collection or retrieves an existing one. ```go // Create a new collection or get an existing one col, err := client.CreateCollection(ctx, "collection_name") // Or get an existing collection col, err := client.GetCollection(ctx, "collection_name") // Or get or create a collection col, err := client.GetOrCreateCollection(ctx, "collection_name") ``` ### List Collections This operation lists all available collections. ```go // List all collections cols, err := client.ListCollections(ctx) ``` ### Delete Collection This operation deletes a specified collection. ```go // Delete a collection by name err := client.DeleteCollection(ctx, "collection_name") ``` ``` -------------------------------- ### Start Local Chroma Server Source: https://github.com/amikos-tech/chroma-go/blob/main/README.md Run a Chroma server locally using Docker. This command starts a container and maps port 8000 for access. Ensure Docker is installed and running. ```bash docker run -d --name chroma -p 8000:8000 -e ALLOW_RESET=TRUE chromadb/chroma:latest ``` -------------------------------- ### Get Examples Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/go-examples/docs/querying-collections/query-and-get.md This section covers retrieving data from a collection by specifying IDs or using pagination. ```APIDOC ## Get Examples ### Get by IDs This method retrieves specific records from a collection using their unique IDs. #### Method Signature ```go func (c *Collection) Get(ctx context.Context, opts ...GetOption) (*GetResponse, error) ``` #### Parameters - `ctx` (context.Context): The context for the request. - `opts` ([]GetOption): Options to configure the retrieval, including: - `WithIDsGet(ids ...string)`: A list of IDs for the records to retrieve. #### Example Usage ```go package main import ( "context" "log" v2 "github.com/amikos-tech/chroma-go/pkg/api/v2" ) func main() { client, err := v2.NewHTTPClient() if err != nil { log.Fatalf("Error creating client: %v", err) } defer client.Close() ctx := context.Background() collection, err := client.GetCollection(ctx, "my_collection") if err != nil { log.Fatalf("Error getting collection: %v", err) } // Get records by IDs results, err := collection.Get(ctx, v2.WithIDsGet("id1", "id2"), ) if err != nil { log.Fatalf("Error getting documents: %v", err) } log.Printf("IDs: %v", results.GetIDs()) log.Printf("Documents: %v", results.GetDocuments()) } ``` ### Get with Pagination This method allows for paginated retrieval of records from a collection. #### Method Signature ```go func (c *Collection) Get(ctx context.Context, opts ...GetOption) (*GetResponse, error) ``` #### Parameters - `ctx` (context.Context): The context for the request. - `opts` ([]GetOption): Options to configure the retrieval, including: - `WithLimitGet(limit int)`: The maximum number of records to return. - `WithOffsetGet(offset int)`: The number of records to skip from the beginning. #### Example Usage ```go package main import ( "context" "log" v2 "github.com/amikos-tech/chroma-go/pkg/api/v2" ) func main() { client, err := v2.NewHTTPClient() if err != nil { log.Fatalf("Error creating client: %v", err) } defer client.Close() ctx := context.Background() collection, err := client.GetCollection(ctx, "my_collection") if err != nil { log.Fatalf("Error getting collection: %v", err) } // Get with limit and offset for pagination results, err := collection.Get(ctx, v2.WithLimitGet(50), v2.WithOffsetGet(100), ) if err != nil { log.Fatalf("Error getting documents: %v", err) } log.Printf("Got %d documents", len(results.GetIDs())) } ``` ``` -------------------------------- ### Data Operations Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/go-examples/README.md Examples for adding, querying, getting, updating, upserting, and deleting data within a collection. ```APIDOC ## Data Operations ### Add Data Adds documents, their IDs, and associated metadata to a collection. ```go // Add documents with IDs, texts, and metadata col.Add(ctx, v2.WithIDs("id1", "id2"), v2.WithTexts("document content 1", "document content 2"), v2.WithMetadatas( v2.NewDocumentMetadata(v2.NewStringAttribute("key", "value")), v2.NewDocumentMetadata(v2.NewStringAttribute("key", "value")), ), ) ``` ### Query Data Queries a collection based on text, number of results, and filtering conditions. ```go // Query documents by text, number of results, and where clause results, err := col.Query(ctx, v2.WithQueryTexts("search query"), v2.WithNResults(10), v2.WithWhere(v2.EqString("key", "value")), ) ``` ### Get Data Retrieves specific documents from a collection by their IDs. ```go // Get documents by their IDs results, err := col.Get(ctx, v2.WithIDs("id1", "id2"), ) ``` ### Update Data Updates existing documents in a collection identified by their IDs. ```go // Update documents by ID with new text col.Update(ctx, v2.WithIDs("id1"), v2.WithTexts("updated document content")) ``` ### Upsert Data Inserts or updates documents in a collection based on their IDs. ```go // Upsert documents by ID with new text col.Upsert(ctx, v2.WithIDs("id1"), v2.WithTexts("document content")) ``` ### Delete Data Deletes documents from a collection either by their IDs or by a filter condition. ```go // Delete documents by IDs col.Delete(ctx, v2.WithIDs("id1", "id2")) // Delete documents by a where clause col.Delete(ctx, v2.WithWhere(v2.EqString("key", "value"))) ``` ``` -------------------------------- ### Quick Start with Chroma Go Client Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/go-examples/README.md Demonstrates connecting to a Chroma server, creating a collection, adding documents, querying, and iterating through results using the chroma-go client library. ```go package main import ( "context" "log" v2 "github.com/amikos-tech/chroma-go/pkg/api/v2" ) func main() { // Connect to Chroma server client, err := v2.NewHTTPClient() if err != nil { log.Fatal(err) } defer client.Close() ctx := context.Background() // Create or get a collection collection, _ := client.GetOrCreateCollection(ctx, "my_collection") // Add documents collection.Add(ctx, v2.WithIDs("doc1", "doc2"), v2.WithTexts("Hello world", "Goodbye world"), ) // Query results, _ := collection.Query(ctx, v2.WithQueryTexts("Hello"), v2.WithNResults(1), ) // Iterate using Rows() for ergonomic access for _, row := range results.Rows() { log.Printf("Found: %s", row.ID) } } ``` -------------------------------- ### Count and Peek Collections Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/go-examples/docs/collections/manage-collections.md Provides examples for getting the document count within a collection and peeking at the first few documents. ```APIDOC ## Convenience Methods: Count and Peek These methods provide quick access to collection statistics and content. ### Count Documents #### Method `collection.Count(ctx context.Context) (int, error)` #### Description Returns the total number of documents currently stored in the collection. #### Parameters - `ctx` (context.Context) - The context for the request. ### Peek Documents #### Method `collection.Peek(ctx context.Context) (*PeekResult, error)` #### Description Retrieves a sample of the first few documents from the collection. The exact number of documents returned by `Peek` is determined by the server's default or configuration. #### Response Returns a `PeekResult` object containing the sampled documents. ### Request Example ```go // Get document count count, err := collection.Count(ctx) // Peek at first documents peek, err := collection.Peek(ctx) log.Printf("First documents: %v", peek.GetDocuments()) ``` ``` -------------------------------- ### Basic GroupBy with MinK Aggregation in Go Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/go-examples/cloud/search-api/group-by.md Get top 3 results per category, ordered by score. This example demonstrates setting up a cloud client, getting a collection, and performing a search with GroupBy and MinK aggregation. ```go package main import ( "context" "log" v2 "github.com/amikos-tech/chroma-go/pkg/api/v2" ) func main() { client, err := v2.NewCloudClient( v2.WithCloudAPIKey("your-api-key"), v2.WithDatabaseAndTenant("database", "tenant"), ) if err != nil { log.Fatalf("Error: %v", err) } defer client.Close() ctx := context.Background() collection, err := client.GetCollection(ctx, "my_collection") if err != nil { log.Fatalf("Error: %v", err) } // Get top 3 results per category, ordered by score result, err := collection.Search(ctx, v2.NewSearchRequest( v2.WithKnnRank( v2.KnnQueryText("machine learning research"), v2.WithKnnLimit(100), ), v2.WithGroupBy( v2.NewGroupBy( v2.NewMinK(3, v2.KScore), // Top 3 with lowest scores v2.K("category"), // Group by category ), ), v2.NewPage(v2.Limit(30)), v2.WithSelect(v2.KDocument, v2.KScore, v2.K("category")), ), ) if err != nil { log.Fatalf("Error: %v", err) } log.Printf("Results: %v", result) } ``` -------------------------------- ### Create and Configure Chroma-go Client Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/docs/client.md Demonstrates creating a new Chroma-go client with various configuration options. Includes setting the base path, tenant, database, default headers, and SSL certificate path. Note that `WithDebug` is deprecated and `WithLogger` should be used instead. ```go package main import ( "context" "fmt" "log" "os" chroma "github.com/amikos-tech/chroma-go" ) func main() { client, err := chroma.NewClient( chroma.WithBasePath("http://localhost:8000"), chroma.WithTenant("my_tenant"), chroma.WithDatabase("my_db"), // chroma.WithDebug(true) is deprecated - use WithLogger instead for debug output chroma.WithDefaultHeaders(map[string]string{"Authorization": "Bearer my token"}), chroma.WithSSLCert("path/to/cert.pem"), ) if err != nil { fmt.Printf("Failed to create client: %v", err) } // do something with client // Close the client to release any resources such as local embedding functions err = client.Close() if err != nil { fmt.Printf("Failed to close client: %v", err) } } ``` -------------------------------- ### Run Local HFEI Server Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/docs/rerankers.md This command starts a local Hugging Face Inference Engine (HFEI) server for reranking. Ensure you have Docker installed and the data directory is accessible. ```bash docker run --rm -p 8080:80 -v $PWD/data:/data --platform linux/amd64 ghcr.io/huggingface/text-embeddings-inference:cpu-latest --model-id BAAI/bge-reranker-base ``` -------------------------------- ### Initialize Chroma HTTP Client with Options Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/docs/client.md Demonstrates how to create an HTTP client for Chroma, specifying the base URL, database, tenant, and custom headers. Note that `WithDebug()` is deprecated and `WithLogger` should be used instead. ```go package main import ( "context" "fmt" chroma "github.com/amikos-tech/chroma-go/pkg/api/v2" "log" ) func main() { c, err := chroma.NewHTTPClient( chroma.WithBaseURL("http://localhost:8000"), chroma.WithDatabaseAndTenant("default_database", "default_tenant"), chroma.WithDefaultHeaders(map[string]string{"X-Custom-Header": "header-value"}), // chroma.WithDebug() is deprecated - use WithLogger instead for debug output ) if err != nil { log.Fatalf("Error creating client: %s \n", err) } v, err := c.GetVersion(context.Background()) if err != nil { log.Fatalf("Error getting version: %s \n", err) } fmt.Printf("Chroma API Version: %s \n", v) } ``` -------------------------------- ### Initialize Chroma Cloud Client Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/docs/client.md Demonstrates initializing the Chroma Cloud client with API key and database/tenant. Note that `WithDebug()` is deprecated and `WithLogger` should be used instead for debug output. ```go package main import ( "context" "fmt" chroma "github.com/amikos-tech/chroma-go/pkg/api/v2" "log" ) func main() { c, err := chroma.NewHTTPClient( chroma.WithCloudAPIKey("my-api-key"), chroma.WithDatabaseAndTenant("team-uuid", "my-database"), // chroma.WithDebug() is deprecated - use WithLogger instead for debug output ) if err != nil { log.Fatalf("Error creating client: %s \n", err) } v, err := c.GetVersion(context.Background()) if err != nil { log.Fatalf("Error getting version: %s \n", err) } fmt.Printf("Chroma API Version: %s \n", v) } ``` -------------------------------- ### Basic Metadata Filtering in Go Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/go-examples/cloud/search-api/filtering.md Filter search results by metadata fields, document content, or document IDs using ChromaDB's Go client. This example shows how to set up the client, get a collection, and perform searches with various filter conditions. ```go package main import ( "context" "log" v2 "github.com/amikos-tech/chroma-go/pkg/api/v2" ) func main() { client, err := v2.NewCloudClient( v2.WithCloudAPIKey("your-api-key"), v2.WithDatabaseAndTenant("database", "tenant"), ) if err != nil { log.Fatalf("Error: %v", err) } defer client.Close() ctx := context.Background() collection, err := client.GetCollection(ctx, "my_collection") if err != nil { log.Fatalf("Error: %v", err) } // Filter by metadata field: K("status") == "active" result1, err := collection.Search(ctx, v2.NewSearchRequest( v2.WithFilter(v2.EqString(v2.K("status"), "active")), v2.NewPage(v2.Limit(10)), ), ) if err != nil { log.Fatalf("Error: %v", err) } // Filter by document content: K.DOCUMENT.contains(...) result2, err := collection.Search(ctx, v2.NewSearchRequest( v2.WithFilter(v2.DocumentContains("machine learning")), v2.NewPage(v2.Limit(10)), ), ) if err != nil { log.Fatalf("Error: %v", err) } // Filter by specific document IDs: K.ID.is_in([...]) // Option 1: Using WithIDs convenience function result3, err := collection.Search(ctx, v2.NewSearchRequest( v2.WithIDs("doc1", "doc2", "doc3"), v2.NewPage(v2.Limit(10)), ), ) if err != nil { log.Fatalf("Error: %v", err) } // Option 2: Using IDIn within WithFilter result4, err := collection.Search(ctx, v2.NewSearchRequest( v2.WithFilter(v2.IDIn("doc1", "doc2", "doc3")), v2.NewPage(v2.Limit(10)), ), ) if err != nil { log.Fatalf("Error: %v", err) } // Exclude specific document IDs: K.ID.not_in([...]) result5, err := collection.Search(ctx, v2.NewSearchRequest( v2.WithFilter(v2.IDNotIn("excluded1", "excluded2")), v2.NewPage(v2.Limit(10)), ), ) if err != nil { log.Fatalf("Error: %v", err) } log.Printf("Results: %v, %v, %v, %v, %v", result1, result2, result3, result4, result5) } ``` -------------------------------- ### Twelve Labs Embedding Function Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/docs/embeddings.md This section covers the Twelve Labs embedding function, which supports multimodal content (text, image, audio, video). It includes installation instructions, basic text embedding usage, and examples for embedding different content types using the `EmbedContent` method. ```APIDOC ## Twelve Labs Embedding Function Twelve Labs provides multimodal embedding models that support text, image, audio, and video content. The default model is `marengo3.0` which produces 512-dimensional embeddings. ### Installation ```bash go get github.com/amikos-tech/chroma-go/pkg/embeddings/twelvelabs ``` ### Basic Usage (Text) ```go import ( twelvelabs "github.com/amikos-tech/chroma-go/pkg/embeddings/twelvelabs" ) ef, err := twelvelabs.NewTwelveLabsEmbeddingFunction( twelvelabs.WithEnvAPIKey(), // reads TWELVE_LABS_API_KEY ) // Use with collection col, err := client.CreateCollection(ctx, "my-collection", chroma.WithEmbeddingFunctionCreate(ef), ) ``` ### Multimodal (Content API) ```go import "github.com/amikos-tech/chroma-go/pkg/embeddings" // Text content textEmb, err := ef.EmbedContent(ctx, embeddings.NewTextContent("hello world")) // Image from URL imgEmb, err := ef.EmbedContent(ctx, embeddings.NewImageURL("https://example.com/photo.png")) // Audio from URL audioEmb, err := ef.EmbedContent(ctx, embeddings.NewAudioURL("https://example.com/clip.mp3")) // Video from URL videoEmb, err := ef.EmbedContent(ctx, embeddings.NewVideoURL("https://example.com/clip.mp4")) ``` ``` -------------------------------- ### Cloud Client Creation for Chroma Go Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/go-examples/README.md Demonstrates how to create a client for Chroma Cloud, requiring API key, database, and tenant information. ```go // Cloud client client, _ := v2.NewCloudClient( v2.WithCloudAPIKey("api-key"), v2.WithDatabaseAndTenant("database", "tenant"), ) ``` -------------------------------- ### Basic Search API Usage in Go Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/docs/search.md Demonstrates how to initialize the Chroma Go client for cloud usage, set up an embedding function, get a collection, and perform a simple text search. Ensure you replace placeholders like 'your-api-key' and 'sk-xxx' with your actual credentials. ```go package main import ( "context" "fmt" "log" chroma "github.com/amikos-tech/chroma-go/pkg/api/v2" "github.com/amikos-tech/chroma-go/pkg/embeddings/openai" ) func main() { client, err := chroma.NewHTTPClient( chroma.WithCloudAPIKey("your-api-key"), chroma.WithDatabaseAndTenant("your-tenant", "your-database"), ) if err != nil { log.Fatal(err) } defer client.Close() // Embedding function is required for text queries ef, _ := openai.NewOpenAIEmbeddingFunction("sk-xxx") col, err := client.GetCollection(context.Background(), "my-collection", chroma.WithEmbeddingFunctionGet(ef), ) if err != nil { log.Fatal(err) } // Simple text search result, err := col.Search(context.Background(), chroma.NewSearchRequest( chroma.WithKnnRank(chroma.KnnQueryText("machine learning")), chroma.WithLimit(10), ), ) if err != nil { log.Fatal(err) } fmt.Printf("Found %d results\n", len(result.(*chroma.SearchResultImpl).IDs[0])) } ``` -------------------------------- ### Collection Management with Chroma-Go Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/go-examples/README.md Demonstrates how to create, get, or get-or-create collections. Also shows how to list all collections and delete a specific collection. ```go // Create/Get col, _ := client.CreateCollection(ctx, "name") col, _ := client.GetCollection(ctx, "name") col, _ := client.GetOrCreateCollection(ctx, "name") // List/Delete cols, _ := client.ListCollections(ctx) client.DeleteCollection(ctx, "name") ``` -------------------------------- ### Get Recommendations with Hybrid Search (Go) Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/go-examples/cloud/search-api/examples.md Implements content recommendation logic in Go, using Chroma-Go's v2 API. It constructs filters for categories and minimum ratings, and defines a hybrid search using Reciprocal Rank Fusion (RRF) with two KNN signals. Includes example usage with client initialization and result processing. ```go package main import ( "context" "fmt" "log" "strings" v2 "github.com/amikos-tech/chroma-go/pkg/api/v2" ) type UserPreferences struct { Interests []string FavoriteTopics []string Categories []string MinRating float64 } func getRecommendations( ctx context.Context, collection v2.CollectionAPI, prefs UserPreferences, seenContentIDs []string, numRecommendations int, ) (*v2.SearchResultImpl, error) { // Build filter conditions var filters []v2.WhereClause // Filter by preferred categories if len(prefs.Categories) > 0 { filters = append(filters, v2.InString("category", prefs.Categories...)) } // Filter by minimum rating minRating := prefs.MinRating if minRating == 0 { minRating = 3.5 } filters = append(filters, v2.GteFloat("rating", minRating)) // Create hybrid search with multiple signals interests := prefs.Interests if len(interests) == 0 { interests = []string{"general"} } userInterestQuery := strings.Join(interests, " ") favoriteTopicsQuery := strings.Join(prefs.FavoriteTopics, " ") // Create KNN ranks for RRF interestKnn, _ := v2.NewKnnRank( v2.KnnQueryText(userInterestQuery), v2.WithKnnReturnRank(), v2.WithKnnLimit(200), ) topicsKnn, _ := v2.NewKnnRank( v2.KnnQueryText(favoriteTopicsQuery), v2.WithKnnReturnRank(), v2.WithKnnLimit(200), ) // Build search searchOpts := []v2.SearchOption{ v2.WithRrfRank( v2.WithRrfRanks( interestKnn.WithWeight(0.6), topicsKnn.WithWeight(0.4), ), v2.WithRrfK(60), ), v2.NewPage(v2.Limit(numRecommendations)), v2.WithSelect(v2.KDocument, v2.KScore, v2.K("title"), v2.K("category"), v2.K("author"), v2.K("rating")), } if len(filters) > 0 { searchOpts = append([]v2.SearchOption{v2.WithFilter(v2.And(filters...))}, searchOpts...) } // Add ID filter for seen content (using FilterIDs is for inclusion, so we handle exclusion differently) // Note: ID exclusion might need to be handled at the filter level if supported return collection.Search(ctx, v2.NewSearchRequest(searchOpts...)) } func main() { client, err := v2.NewCloudClient( v2.WithCloudAPIKey("your-api-key"), v2.WithDatabaseAndTenant("database", "tenant"), ) if err != nil { log.Fatalf("Error: %v", err) } defer client.Close() ctx := context.Background() collection, err := client.GetCollection(ctx, "content") if err != nil { log.Fatalf("Error: %v", err) } prefs := UserPreferences{ Interests: []string{"machine learning", "artificial intelligence", "data science"}, FavoriteTopics: []string{"neural networks", "deep learning", "transformers"}, Categories: []string{"technology", "science", "research"}, MinRating: 4.0, } seenContent := []string{"content_001", "content_045", "content_123"} results, err := getRecommendations(ctx, collection, prefs, seenContent, 10) if err != nil { log.Fatalf("Error: %v", err) } fmt.Println("Personalized Recommendations:") for i, row := range results.Rows() { title := "" category := "" author := "" rating := 0.0 if row.Metadata != nil { if t, ok := row.Metadata.Get("title"); ok { title = fmt.Sprintf("%v", t) } if c, ok := row.Metadata.Get("category"); ok { category = fmt.Sprintf("%v", c) } if a, ok := row.Metadata.Get("author"); ok { author = fmt.Sprintf("%v", a) } if r, ok := row.Metadata.Get("rating"); ok { rating = r.(float64) } } fmt.Printf("\n%d. %s\n", i+1, title) fmt.Printf(" Category: %s | Author: %s\n", category, author) fmt.Printf(" Rating: %.1f/5 | Match Score: %.3f\n", rating, row.Score) } } ``` -------------------------------- ### Initialize Persistent Chroma Client Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/docs/client.md Demonstrates how to create a persistent Chroma client with specified path and reset options. This client persists data locally and allows for resetting its state. It also shows how to apply regular client options like database and tenant selection. ```go package main import ( "context" "fmt" "log" chroma "github.com/amikos-tech/chroma-go/pkg/api/v2" ) func main() { client, err := chroma.NewPersistentClient( chroma.WithPersistentPath("./chroma_data"), chroma.WithPersistentAllowReset(true), chroma.WithPersistentClientOption(chroma.WithDatabaseAndTenant("default_database", "default_tenant")), ) if err != nil { log.Fatalf("Error creating persistent client: %v", err) } defer client.Close() version, err := client.GetVersion(context.Background()) if err != nil { log.Fatalf("Error getting version: %v", err) } fmt.Println("Chroma version:", version) } ``` -------------------------------- ### Create Client for Chroma Cloud Source: https://context7.com/amikos-tech/chroma-go/llms.txt Initialize a client for Chroma Cloud, requiring an API key and specifying the database and tenant. Ensure environment variables are set. ```go package main import ( "context" "fmt" "log" "os" chroma "github.com/amikos-tech/chroma-go/pkg/api/v2" ) func main() { client, err := chroma.NewCloudClient( chroma.WithCloudAPIKey(os.Getenv("CHROMA_API_KEY")), chroma.WithDatabaseAndTenant( os.Getenv("CHROMA_DATABASE"), os.Getenv("CHROMA_TENANT"), ), ) if err != nil { log.Fatalf("Error creating cloud client: %s", err) } defer client.Close() col, err := client.GetOrCreateCollection(context.Background(), "my_collection") if err != nil { log.Fatalf("Error creating collection: %s", err) } fmt.Printf("Collection: %s\n", col.Name()) } ``` -------------------------------- ### Build Project with Make Source: https://github.com/amikos-tech/chroma-go/blob/main/README.md Use the 'make build' command to compile the project. ```bash make build ``` -------------------------------- ### Basic Cloud Client Initialization in Go Source: https://github.com/amikos-tech/chroma-go/blob/main/docs/go-examples/docs/run-chroma/cloud-client.md Initialize the Chroma Cloud client with explicit credentials. Ensure you replace placeholders with your actual API key, database name, and tenant ID. Always defer client closing to release resources. ```go package main import ( "log" v2 "github.com/amikos-tech/chroma-go/pkg/api/v2" ) func main() { // Create Cloud client with explicit credentials client, err := v2.NewCloudClient( v2.WithCloudAPIKey("your-api-key"), v2.WithDatabaseAndTenant("database-name", "tenant-id"), ) if err != nil { log.Fatalf("Error creating cloud client: %v", err) } defer client.Close() log.Println("Connected to Chroma Cloud") } ```