### Setup Chroma Ruby Client Source: https://github.com/mariochavez/chroma/blob/main/notebook/Chroma Gem.ipynb Installs the Chroma Ruby client using Bundler. Ensure you have Bundler installed. ```ruby require "bundler/inline" gemfile do gem "chroma-db", path: "../" end ``` -------------------------------- ### Array#any? Method Example Source: https://github.com/mariochavez/chroma/blob/main/notebook/Chroma Gem.ipynb Demonstrates the usage of the Array#any? method with different criteria. ```APIDOC ## Array#any? Method ### Description The `any?` method checks if any element in an array meets a given criterion. ### Usage 1. **Without block or argument**: Returns `true` if any element is truthy. ```ruby [nil, 0, false].any? # => true [nil, false].any? # => false [].any? # => false ``` 2. **With a block**: Returns `true` if the block returns a truthy value for any element. ```ruby [0, 1, 2].any? {|element| element > 1 } # => true [0, 1, 2].any? {|element| element > 2 } # => false ``` 3. **With an argument `obj`**: Returns `true` if `obj ===` any element. ```ruby ['food', 'drink'].any?(/foo/) # => true ['food', 'drink'].any?(/bar/) # => false [0, 1, 2].any?(1) # => true [0, 1, 2].any?(3) # => false ``` ### Related Enumerable#any? ``` -------------------------------- ### Get or Create a Collection Source: https://context7.com/mariochavez/chroma/llms.txt Retrieve a collection if it exists, otherwise create it. This is useful for idempotent initialization. ```ruby require "chroma-db" Chroma.connect_host = "http://localhost:8000" # Get or create collection - creates if doesn't exist, retrieves if it does collection = Chroma::Resources::Collection.get_or_create( "ruby-documentation", { lang: "ruby", gem: "chroma-db" } ) puts collection.name # => "ruby-documentation" # Calling again returns the existing collection (metadata not updated) same_collection = Chroma::Resources::Collection.get_or_create( "ruby-documentation", { different: "metadata" } # This metadata is ignored if collection exists ) puts same_collection.id == collection.id # => true ``` -------------------------------- ### Chroma Embedding Metadata Example Source: https://github.com/mariochavez/chroma/blob/main/notebook/Chroma Gem.ipynb Example metadata associated with a Chroma embedding, including its ID and embedding vector. ```ruby #, @distance=nil> ``` -------------------------------- ### Download Nomic Embed Text Model with Ollama Source: https://github.com/mariochavez/chroma/blob/main/notebook/Chroma Gem.ipynb Use this command to download the 'nomic-embed-text' model for use with Ollama. Ensure Ollama is installed first. ```bash ollama pull nomic-embed-text ``` -------------------------------- ### Collection.get_or_create Source: https://context7.com/mariochavez/chroma/llms.txt Get an existing collection or create it if it doesn't exist. Useful for idempotent initialization. ```APIDOC ## Collection.get_or_create Get an existing collection or create it if it doesn't exist. Useful for idempotent initialization. ### Method POST ### Endpoint `/api/v1/collections` (with `get_or_create` behavior) ### Parameters #### Request Body - **name** (string) - Required - The name of the collection. - **metadata** (object) - Optional - Key-value pairs to associate with the collection. If the collection exists, this metadata is ignored. ### Request Example ```ruby require "chroma-db" Chroma.connect_host = "http://localhost:8000" # Get or create collection - creates if doesn't exist, retrieves if it does collection = Chroma::Resources::Collection.get_or_create( "ruby-documentation", { lang: "ruby", gem: "chroma-db" } ) puts collection.name # => "ruby-documentation" # Calling again returns the existing collection (metadata not updated) same_collection = Chroma::Resources::Collection.get_or_create( "ruby-documentation", { different: "metadata" } # This metadata is ignored if collection exists ) puts same_collection.id == collection.id # => true ``` ### Response #### Success Response (200 OK or 201 Created) - **id** (string) - The unique identifier for the collection. - **name** (string) - The name of the collection. - **metadata** (object) - The metadata associated with the collection. #### Response Example ```json { "id": "39233aa7-16cb-46a5-84ce-fbcca96cf4af", "name": "ruby-documentation", "metadata": {"lang": "ruby", "gem": "chroma-db"} } ``` ``` -------------------------------- ### Complete RAG Example with Ollama in Ruby Source: https://context7.com/mariochavez/chroma/llms.txt Builds a Retrieval-Augmented Generation (RAG) pipeline using Chroma and Ollama for local embeddings. Requires 'chroma-db', 'net/http', and 'json' gems. ```ruby require "chroma-db" require "net/http" require "json" require "securerandom" # Configure Chroma Chroma.connect_host = "http://localhost:8000" Chroma.logger = Logger.new($stdout) Chroma.log_level = Chroma::LEVEL_INFO # Simple Ollama client for generating embeddings class OllamaClient def initialize(url: "http://localhost:11434") @url = url end def embed(text, model: "nomic-embed-text") uri = URI("#{@url}/api/embeddings") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request.body = { model: model, prompt: text }.to_json response = Net::HTTP.start(uri.hostname, uri.port) do |http| http.request(request) end return JSON.parse(response.body)["embedding"] if response.code == "200" raise "Embedding failed: #{response.body}" end end # Initialize clients ollama = OllamaClient.new collection = Chroma::Resources::Collection.get_or_create( "knowledge-base", { purpose: "RAG demo", embedding_model: "nomic-embed-text" } ) # Add documents to the knowledge base documents = [ "Ruby is a dynamic, open source programming language with a focus on simplicity.", "Rails is a web application framework written in Ruby under the MIT License.", "Chroma is an open-source embedding database for building LLM applications." ] documents.each_with_index do |doc, idx| embedding_vector = ollama.embed(doc) embedding = Chroma::Resources::Embedding.new( id: "doc-#{idx}", embedding: embedding_vector, metadata: { source: "demo", index: idx }, document: doc ) collection.add(embedding) end puts "Added #{collection.count} documents to collection" # Query the knowledge base query = "What is Ruby?" query_vector = ollama.embed(query) results = collection.query( query_embeddings: [query_vector], results: 2, include: %w[documents metadatas distances] ) puts "\nQuery: #{query}" puts "Results:" results.each do |result| puts "- #{result.document} (distance: #{result.distance.round(4)})") end ``` -------------------------------- ### Chroma Embedding Data Example Source: https://github.com/mariochavez/chroma/blob/main/notebook/Chroma Gem.ipynb An example of embedding data within the Chroma project, represented as a numerical array. ```plaintext 78, -0.1966988891363144, 1.530571460723877, 0.09704703837633133, 1.2469956874847412, 0.5419987440109253, 0.5530239939689636, -0.540511965751648, 1.4711883068084717, 0.9722756743431091, 0.1925874501466751, 0.39248472452163696, 0.5499120950698853, 0.34655171632766724, -0.3828185498714447, 1.568729281425476, 2.1224892139434814, 0.17062662541866302, 0.19931438565254211, -0.3234945833683014, -0.7229470014572144, 0.31668880581855774, -0.3745308816432953, -1.294561743736267, -0.5889129638671875, -0.6379764676094055, -0.4401127099990845, -0.34514597058296204, -0.060600291937589645, 0.2108048051595688, -0.4144534766674042, -0.35937070846557617, 0.8739745616912842, -0.6609992384910583, -1.1741656064987183, 0.7454974055290222, -0.19637176394462585, 0.2024635374546051, 0.09466291964054108, 1.0179792642593384, 0.5239393711090088, 0.05441559851169586, 0.5475056767463684, 0.16649267077445984, -1.1458468437194824, 0.5101571083068848, 0.34289076924324036, 0.6865392327308655, 0.23076745867729187, 0.31457680463790894, 0.23856517672538757, 0.3072117567062378, -0.9733468890190125, -1.1923526525497437, -1.554363489151001, -0.20144698023796082, -0.7564064860343933, 0.7214184403419495, -0.6734850406646729, -0.694885790348053, 0.2750096917152405, -0.7656024098396301, -0.4820512533187866, -0.775223433971405, 0.7747925519943237, -1.169996738433838, 0.08622319251298904, 0.3255981206893921, 0.7236292958259583, -0.27172741293907166, 0.16072386503219604, 0.25415512919425964, -0.30468684434890747, -0.1888609081506729, 0.163290336728096, 0.7361018061637878, 1.096892237663269, -0.7974652647972107, 0.5220590829849243, -0.31517791748046875, 0.5868136882781982, -1.2400593757629395, -0.6704225540161133, -0.19956731796264648, -0.35603779554367065, 0.4415271580219269, -0.7804092168807983, -1.5330135822296143, 0.6742067933082581, -0.21148113906383514, -0.23329216241836548, 0.3919619917869568, -0.2974919080734253, -0.00820340309292078, -1.1466299295425415, 0.34342920780181885, -1.2512612342834473, -1.2952560186386108, 0.9228042364120483, 0.04792394861578941, 0.6588780283927917, -0.030149154365062714, -0.00970460195094347, -0.9531992673873901, -0.24526171386241913, -0.43323788046836853, 1.098596453666687, -0.41034722328186035, 0.4640841484069824, 0.002632593736052513, -0.4644605219364166, -1.0648726224899292, 0.9959708452224731, 0.22528205811977386, -0.6045489311218262, -1.507542610168457, -0.6524662971496582, 0.45025399327278137, 0.14585748314857483, -0.07247880101203918, 0.4817347526550293, 0.2341473251581192, 0.5855250358581543, 2.584882974624634, 0.5957955718040466, 1.062381386756897, 0.64400315284729, 0.11549169570207596, 0.07915589213371277, -0.6310657858848572, -0.8890601396560669, -0.8262959122657776, -0.37367579340934753 ``` -------------------------------- ### Perform similarity search Source: https://github.com/mariochavez/chroma/blob/main/notebook/Chroma Gem.ipynb Example usage of the ChromaVectorStore to perform a similarity search on a collection. ```ruby vs = ChromaVectorStore.new(collection) embeddings = vs.similarity_search("array any?", k: 2) ``` -------------------------------- ### Handle Chroma Errors in Ruby Source: https://context7.com/mariochavez/chroma/llms.txt Demonstrates how to catch and handle various Chroma-specific errors, including invalid requests, connection issues, and general API errors. Ensure you have the 'chroma-db' gem installed. ```ruby require "chroma-db" Chroma.connect_host = "http://localhost:8000" begin # Attempt operations that might fail collection = Chroma::Resources::Collection.get("non-existent-collection") rescue Chroma::InvalidRequestError => e # Raised for invalid requests (e.g., collection not found, invalid parameters) puts "Invalid request: #{e.message}" puts "Status: #{e.status}" puts "Body: #{e.body}" rescue Chroma::APIConnectionError => e # Raised when unable to connect to Chroma server puts "Connection error: #{e.message}" rescue Chroma::APIError => e # Generic API error for other failures puts "API error: #{e.message}" puts "Status: #{e.status}" rescue Chroma::ChromaError => e # Base error class - catches all Chroma errors puts "Chroma error: #{e.message}" end # Example: Handling embedding addition errors begin collection = Chroma::Resources::Collection.get("my-collection") collection.add(Chroma::Resources::Embedding.new( id: "duplicate-id", # If ID already exists embedding: [1.0, 2.0, 3.0] )) rescue Chroma::InvalidRequestError => e puts "Failed to add embedding: #{e.message}" end ``` -------------------------------- ### Successful Response Log Source: https://github.com/mariochavez/chroma/blob/main/notebook/Chroma Gem.ipynb Example log message indicating a successful response with a 201 status code. ```log I, [2024-12-11T13:38:40.349321 #16507] INFO -- : message=Successful response code=201 ``` -------------------------------- ### GET /collection/count Source: https://github.com/mariochavez/chroma/blob/main/notebook/Chroma Gem.ipynb Retrieves the total count of items currently stored in the collection. ```APIDOC ## GET /collection/count ### Description Returns the number of items in the collection. ### Method GET ### Endpoint /collection/count ### Request Example ```python IRuby.display collection.count ``` ### Response #### Success Response (200) - **message** (string) - Successful response - **code** (integer) - 200 - **result** (integer) - The count of items ``` -------------------------------- ### Successful Response Log with Count Source: https://github.com/mariochavez/chroma/blob/main/notebook/Chroma Gem.ipynb Example log message indicating a successful response with a 200 status code, often associated with retrieval operations. ```log I, [2024-12-11T13:38:42.259923 #16507] INFO -- : message=Successful response code=200 ``` -------------------------------- ### Get Enumerator for Map In-Place Source: https://github.com/mariochavez/chroma/blob/main/notebook/Chroma Gem.ipynb Demonstrates obtaining an Enumerator when no block is provided to the Array#map! method in Ruby. This allows for deferred in-place modification. ```ruby a = [:foo, 'bar', 2] a1 = a.map! a1 # => # ``` -------------------------------- ### Get Enumerator for Map Source: https://github.com/mariochavez/chroma/blob/main/notebook/Chroma Gem.ipynb Illustrates obtaining an Enumerator when no block is provided to the Array#map method in Ruby. This is useful for lazy evaluation. ```ruby a = [:foo, 'bar', 2] a1 = a.map a1 # => # ``` -------------------------------- ### Get Embeddings from Collection - Ruby Source: https://context7.com/mariochavez/chroma/llms.txt Use `collection.get` to retrieve embeddings, with options for filtering by ID, metadata, document content, and pagination. You can also specify which fields to include in the results. ```ruby require "chroma-db" Chroma.connect_host = "http://localhost:8000" collection = Chroma::Resources::Collection.get("ruby-documentation") # Get all embeddings (returns metadatas and documents by default) embeddings = collection.get embeddings.each do |emb| puts "ID: #{emb.id}, Document: #{emb.document[0..50]}..." end # Get specific embeddings by ID embeddings = collection.get(ids: ["Array#sort", "Array#map"]) # Filter by metadata embeddings = collection.get(where: { type: "documentation" }) # Filter by document content embeddings = collection.get(where_document: { "$contains" => "returns" }) # Pagination with limit and offset embeddings = collection.get(limit: 10, offset: 0) # Pagination with page and page_size (convenience method) embeddings = collection.get(page: 1, page_size: 10) # First 10 results embeddings = collection.get(page: 2, page_size: 10) # Next 10 results # Choose which fields to include embeddings = collection.get(include: %w[metadatas documents embeddings]) ``` -------------------------------- ### Connect and Use Chroma Ruby Client Source: https://github.com/mariochavez/chroma/blob/main/README.md Configure the Chroma host, set logging, check the server version, create a collection, and add embeddings. Ensure Chroma Database is running and accessible. ```ruby require "logger" # Requiere Chroma Ruby client. require "chroma-db" # Configure Chroma's host. Here you can specify your own host. Chroma.connect_host = "http://localhost:8000" Chroma.logger = Logger.new($stdout) Chroma.log_level = Chroma::LEVEL_ERROR # Check current Chrome server version version = Chroma::Resources::Database.version puts version # Create a new collection collection = Chroma::Resources::Collection.create(collection_name, {lang: "ruby", gem: "chroma-db"}) # Add embeddings embeddings = [ Chroma::Resources::Embedding.new(id: "1", embedding: [1.3, 2.6, 3.1], metadata: {client: "chroma-rb"}, document: "ruby"), Chroma::Resources::Embedding.new(id: "2", embedding: [3.7, 2.8, 0.9], metadata: {client: "chroma-rb"}, document: "rails") ] collection.add(embeddings) ``` -------------------------------- ### Configuration Source: https://context7.com/mariochavez/chroma/llms.txt Configure the Chroma client connection settings including host, API key, tenant, and database for connecting to local or hosted Chroma instances. ```APIDOC ## Configuration Configure the Chroma client connection settings including host, API key, tenant, and database for connecting to local or hosted Chroma instances. ### Basic configuration for local Chroma instance ```ruby require "logger" require "chroma-db" Chroma.connect_host = "http://localhost:8000" Chroma.logger = Logger.new($stdout) Chroma.log_level = Chroma::LEVEL_INFO ``` ### Configuration for hosted Chroma service ```ruby require "chroma-db" Chroma.connect_host = "https://api.trychroma.com" Chroma.api_key = "your-api-key-here" Chroma.tenant = "my_tenant" # Optional, defaults to "default_tenant" Chroma.database = "my_database" # Optional, defaults to "default_database" ``` ### Log levels available ```ruby Chroma.log_level = Chroma::LEVEL_DEBUG # Verbose logging Chroma.log_level = Chroma::LEVEL_INFO # Standard logging Chroma.log_level = Chroma::LEVEL_ERROR # Errors only ``` ### Environment variable for API key (alternative) ```ruby # Set CHROMA_SERVER_AUTHN_CREDENTIALS environment variable ``` ``` -------------------------------- ### Create a Collection Source: https://context7.com/mariochavez/chroma/llms.txt Initialize a new collection with a name and optional metadata. ```ruby require "chroma-db" Chroma.connect_host = "http://localhost:8000" # Create a new collection with metadata collection = Chroma::Resources::Collection.create( "ruby-documentation", { lang: "ruby", version: "3.2", source: "Ruby lang website" } ) puts collection.id # => "39233aa7-16cb-46a5-84ce-fbcca96cf4af" puts collection.name # => "ruby-documentation" puts collection.metadata # => {"lang"=>"ruby", "version"=>"3.2", "source"=>"Ruby lang website"} ``` -------------------------------- ### Configure Chroma Client Connection Source: https://context7.com/mariochavez/chroma/llms.txt Set up connection parameters for local or hosted Chroma instances and configure logging levels. ```ruby require "logger" require "chroma-db" # Basic configuration for local Chroma instance Chroma.connect_host = "http://localhost:8000" Chroma.logger = Logger.new($stdout) Chroma.log_level = Chroma::LEVEL_INFO # Configuration for hosted Chroma service Chroma.connect_host = "https://api.trychroma.com" Chroma.api_key = "your-api-key-here" Chroma.tenant = "my_tenant" # Optional, defaults to "default_tenant" Chroma.database = "my_database" # Optional, defaults to "default_database" # Log levels available Chroma.log_level = Chroma::LEVEL_DEBUG # Verbose logging Chroma.log_level = Chroma::LEVEL_INFO # Standard logging Chroma.log_level = Chroma::LEVEL_ERROR # Errors only # Environment variable for API key (alternative) # Set CHROMA_SERVER_AUTHN_CREDENTIALS environment variable ``` -------------------------------- ### Configure Hosted Chroma Service Source: https://github.com/mariochavez/chroma/blob/main/README.md Set the API key, tenant, and database to connect to Chroma's hosted service. Optional parameters for tenant and database are provided. ```ruby Chroma.api_key = "cd75e50bf8213fb7ce57c05b" Chroma.tenant = "my_tenant" # Optional Chroma.database = "my_database" # Optional ``` -------------------------------- ### Manage Chroma Collections Source: https://github.com/mariochavez/chroma/blob/main/notebook/Chroma Gem.ipynb Demonstrates the lifecycle of a collection: listing, creating, retrieving, modifying, and deleting. This code first cleans up existing collections before creating a new one. ```ruby # Clean up collections collections = Chroma::Resources::Collection.list collections.each { |collection| Chroma::Resources::Collection.delete(collection.name) } # Confirm that database has no collections collections = Chroma::Resources::Collection.list collection_name = "ruby-3.0" IRuby.display "Collections in database #{collections.size}" # Create a new collection collection = Chroma::Resources::Collection.create(collection_name, {lang: "ruby", gem: "chroma-rb"}) IRuby.display collection # Confirm that database has collections collections = Chroma::Resources::Collection.list IRuby.display "Collections in database #{collections.size}" # Delete collection Chroma::Resources::Collection.delete(collection_name) # Re-Confirm that database has no collections collections = Chroma::Resources::Collection.list IRuby.display "Collections in database #{collections.size}" # Create the collection again Chroma::Resources::Collection.create(collection_name, {lang: "ruby", gem: "chroma-rb"}) # Get the collection from database collection = Chroma::Resources::Collection.get(collection_name) IRuby.display collection # Modify collection name new_collection_name = "ruby-3.2" collection.modify(new_collection_name) # Get modified collection from database collection = Chroma::Resources::Collection.get(new_collection_name) IRuby.display collection ``` -------------------------------- ### Load Documents with TextLoader Source: https://github.com/mariochavez/chroma/blob/main/notebook/Chroma Gem.ipynb Initializes the TextLoader to read a file and load its content into Document objects. ```ruby documents = TextLoader.new("ruby.txt").load documents.size ``` -------------------------------- ### Configure Chroma Connection and Log Level Source: https://github.com/mariochavez/chroma/blob/main/notebook/Chroma Gem.ipynb Configures the Chroma client to connect to a specified host and sets the logging level. This code requires the 'logger', 'json', and 'securerandom' gems. ```ruby require "logger" require "json" require "securerandom" # Requiere Chroma Ruby client. #require "chroma-db" # Configure Chroma's host. Here you can specify your own host. Chroma.connect_host = "http://localhost:8000" Chroma.logger = Logger.new($stdout) Chroma.log_level = Chroma::LEVEL_INFO ``` -------------------------------- ### Collection Get Embeddings API Source: https://context7.com/mariochavez/chroma/llms.txt This API allows you to retrieve embeddings from a collection with optional filtering, pagination, and field selection. By default, it returns metadatas and documents. ```APIDOC ## GET /api/collections/:collection_name/get ### Description Retrieves embeddings from a collection with optional filtering, pagination, and field selection. ### Method GET ### Endpoint `/api/collections/:collection_name/get` ### Parameters #### Path Parameters - **collection_name** (string) - Required - The name of the collection to retrieve embeddings from. #### Query Parameters - **ids** (array of strings) - Optional - A list of embedding IDs to retrieve. - **where** (object) - Optional - A JSON object for filtering embeddings based on metadata. - **where_document** (object) - Optional - A JSON object for filtering embeddings based on document content. - **limit** (integer) - Optional - The maximum number of embeddings to return. - **offset** (integer) - Optional - The number of embeddings to skip before returning results. - **page** (integer) - Optional - The page number for pagination (use with `page_size`). - **page_size** (integer) - Optional - The number of embeddings per page (use with `page`). - **include** (array of strings) - Optional - Specifies which fields to include in the response (e.g., `["metadatas", "documents", "embeddings"]`). ### Request Example ```ruby require "chroma-db" Chroma.connect_host = "http://localhost:8000" collection = Chroma::Resources::Collection.get("ruby-documentation") # Get all embeddings (returns metadatas and documents by default) embeddings = collection.get embeddings.each do |emb| puts "ID: #{emb.id}, Document: #{emb.document[0..50]}..." end # Get specific embeddings by ID embeddings = collection.get(ids: ["Array#sort", "Array#map"]) # Filter by metadata embeddings = collection.get(where: { type: "documentation" }) # Filter by document content embeddings = collection.get(where_document: { "$contains" => "returns" }) # Pagination with limit and offset embeddings = collection.get(limit: 10, offset: 0) # Pagination with page and page_size (convenience method) embeddings = collection.get(page: 1, page_size: 10) # First 10 results embeddings = collection.get(page: 2, page_size: 10) # Next 10 results # Choose which fields to include embeddings = collection.get(include: %w[metadatas documents embeddings]) ``` ### Response #### Success Response (200) - **embeddings** (array) - An array of embedding objects matching the query. - Each embedding object contains: - **id** (string) - The embedding ID. - **embedding** (array of floats) - The embedding vector (if requested). - **metadata** (object) - The metadata associated with the embedding (if requested). - **document** (string) - The document text associated with the embedding (if requested). #### Response Example ```json [ { "id": "Array#sort", "document": "Returns a new Array whose elements are those from self, sorted.", "metadata": { "method": "sort", "class": "Array", "url": "https://ruby-doc.org/Array#sort" } } ] ``` ``` -------------------------------- ### List All Collections Source: https://context7.com/mariochavez/chroma/llms.txt Retrieve and iterate over all collections currently in the database. ```ruby require "chroma-db" Chroma.connect_host = "http://localhost:8000" # List all collections collections = Chroma::Resources::Collection.list collections.each do |collection| puts "Collection: #{collection.name}" puts " ID: #{collection.id}" puts " Metadata: #{collection.metadata}" end # => Collection: ruby-documentation # => ID: dc767e25-55b9-424f-92b1-9bf5aa9841d1 ``` -------------------------------- ### Manage Embedding objects in Ruby Source: https://context7.com/mariochavez/chroma/llms.txt Demonstrates manual creation of Embedding objects and accessing their attributes, including distance from query results. ```ruby require "chroma-db" # Create an embedding manually embedding = Chroma::Resources::Embedding.new( id: "unique-document-id", embedding: [0.1, 0.2, 0.3, 0.4, 0.5], # Vector representation metadata: { source: "api-docs", category: "array-methods" }, document: "The original text content that was embedded" ) # Access embedding attributes puts embedding.id # => "unique-document-id" puts embedding.embedding # => [0.1, 0.2, 0.3, 0.4, 0.5] puts embedding.metadata # => {source: "api-docs", category: "array-methods"} puts embedding.document # => "The original text content that was embedded" puts embedding.distance # => nil (only set in query results) # Query results include distance collection = Chroma::Resources::Collection.get("my-collection") results = collection.query(query_embeddings: [[0.1, 0.2, 0.3, 0.4, 0.5]], results: 1) result = results.first puts result.distance # => 0.0 (distance from query vector, lower is more similar) ``` -------------------------------- ### Collection.create Source: https://context7.com/mariochavez/chroma/llms.txt Create a new collection in the Chroma database with a name and optional metadata. Collection names must be 3-63 characters, alphanumeric with underscores or hyphens. ```APIDOC ## Collection.create Create a new collection in the Chroma database with a name and optional metadata. Collection names must be 3-63 characters, alphanumeric with underscores or hyphens. ### Method POST ### Endpoint `/api/v1/collections` ### Parameters #### Request Body - **name** (string) - Required - The name of the collection. Must be 3-63 characters, alphanumeric with underscores or hyphens. - **metadata** (object) - Optional - Key-value pairs to associate with the collection. ### Request Example ```ruby require "chroma-db" Chroma.connect_host = "http://localhost:8000" collection = Chroma::Resources::Collection.create( "ruby-documentation", { lang: "ruby", version: "3.2", source: "Ruby lang website" } ) puts collection.id # => "39233aa7-16cb-46a5-84ce-fbcca96cf4af" puts collection.name # => "ruby-documentation" puts collection.metadata # => {"lang"=>"ruby", "version"=>"3.2", "source"=>"Ruby lang website"} ``` ### Response #### Success Response (201 Created) - **id** (string) - The unique identifier for the collection. - **name** (string) - The name of the collection. - **metadata** (object) - The metadata associated with the collection. #### Response Example ```json { "id": "39233aa7-16cb-46a5-84ce-fbcca96cf4af", "name": "ruby-documentation", "metadata": {"lang": "ruby", "version": "3.2", "source": "Ruby lang website"} } ``` ``` -------------------------------- ### Check Chroma Database Heartbeat and Version Source: https://github.com/mariochavez/chroma/blob/main/notebook/Chroma Gem.ipynb Retrieves the database heartbeat timestamp and the Chroma server version. This requires the Chroma client to be connected. ```ruby # Check connection with Database's heartbeat response = Chroma::Resources::Database.heartbeat IRuby.display "Heartbear timestamp #{response["nanosecond heartbeat"]}" # Check current Chrome server version version = Chroma::Resources::Database.version IRuby.display "Chroma server version #{version}" # Reset database (DANGER: This deletes all previos data) # Chroma::Resources::Database.reset ``` -------------------------------- ### Map Elements with Class Source: https://github.com/mariochavez/chroma/blob/main/notebook/Chroma Gem.ipynb Demonstrates mapping each element in an array to its class using Ruby's Array#map method. This returns a new array with the class names. ```ruby a = [:foo, 'bar', 2] a1 = a.map {|element| element.class } a1 # => [Symbol, String, Integer] ``` -------------------------------- ### Perform Database Operations Source: https://context7.com/mariochavez/chroma/llms.txt Check server health, retrieve version information, or reset the database. ```ruby require "chroma-db" Chroma.connect_host = "http://localhost:8000" # Check server heartbeat - returns timestamp indicating server is alive heartbeat = Chroma::Resources::Database.heartbeat # => {"nanosecond heartbeat" => 1733945890642513627} # Get Chroma server version version = Chroma::Resources::Database.version # => "0.5.23" # Reset database (DANGER: Deletes all data - use with caution!) Chroma::Resources::Database.reset # => true ``` -------------------------------- ### Define VectorStore and ChromaVectorStore classes Source: https://github.com/mariochavez/chroma/blob/main/notebook/Chroma Gem.ipynb Base class for vector operations and a specific implementation for Chroma using Ollama for embeddings. ```ruby class VectorStore def initialize(store, search_type = "similarity") @store = store @search_type @ollama_client = OllamaHttpClient.new end def relevant_documents(query) if @search_type == "similarity" @store.similarity_search(query) end end protected def text_to_embeddings(query) response = @ollama_client.embed(query) [response["embedding"]] end end class ChromaVectorStore < VectorStore def similarity_search(query, k: 4, filter: nil) query_embeddings = text_to_embeddings(query) @store.query(query_embeddings:, results: k, where: filter) end end ``` -------------------------------- ### Collection.list Source: https://context7.com/mariochavez/chroma/llms.txt Retrieve all collections in the database. ```APIDOC ## Collection.list Retrieve all collections in the database. ### Method GET ### Endpoint `/api/v1/collections` ### Response #### Success Response (200 OK) - **collections** (array) - An array of collection objects. - Each collection object contains: - **id** (string) - The unique identifier for the collection. - **name** (string) - The name of the collection. - **metadata** (object) - The metadata associated with the collection. ### Request Example ```ruby require "chroma-db" Chroma.connect_host = "http://localhost:8000" # List all collections collections = Chroma::Resources::Collection.list collections.each do |collection| puts "Collection: #{collection.name}" puts " ID: #{collection.id}" puts " Metadata: #{collection.metadata}" end # => Collection: ruby-documentation # => ID: dc767e25-55b9-424f-92b1-9bf5aa9841d1 # => Metadata: {"lang"=>"ruby", "version"=>"3.2"} ``` #### Response Example ```json { "collections": [ { "id": "dc767e25-55b9-424f-92b1-9bf5aa9841d1", "name": "ruby-documentation", "metadata": {"lang": "ruby", "version": "3.2"} } ] } ``` ``` -------------------------------- ### Collection.get Source: https://context7.com/mariochavez/chroma/llms.txt Retrieve an existing collection from the database by name. Raises `Chroma::InvalidRequestError` if the collection does not exist. ```APIDOC ## Collection.get Retrieve an existing collection from the database by name. Raises `Chroma::InvalidRequestError` if the collection does not exist. ### Method GET ### Endpoint `/api/v1/collections/{collection_name}` ### Parameters #### Path Parameters - **collection_name** (string) - Required - The name of the collection to retrieve. ### Request Example ```ruby require "chroma-db" Chroma.connect_host = "http://localhost:8000" # Get an existing collection collection = Chroma::Resources::Collection.get("ruby-documentation") puts collection.id # => "dc767e25-55b9-424f-92b1-9bf5aa9841d1" puts collection.name # => "ruby-documentation" puts collection.metadata # => {"lang"=>"ruby", "version"=>"3.2"} # Handle non-existent collection begin collection = Chroma::Resources::Collection.get("non-existent") rescue Chroma::InvalidRequestError => e puts "Collection not found: #{e.message}" end ``` ### Response #### Success Response (200 OK) - **id** (string) - The unique identifier for the collection. - **name** (string) - The name of the collection. - **metadata** (object) - The metadata associated with the collection. #### Error Response (404 Not Found) - **error** (string) - Description of the error, e.g., "Collection not found." #### Response Example (Success) ```json { "id": "dc767e25-55b9-424f-92b1-9bf5aa9841d1", "name": "ruby-documentation", "metadata": {"lang": "ruby", "version": "3.2"} } ``` ``` -------------------------------- ### Array#map and Array#map! Source: https://github.com/mariochavez/chroma/blob/main/notebook/ruby.txt Methods for transforming array elements by applying a block to each element. ```APIDOC ## Array#map ### Description Calls the block with each element of self and returns a new Array containing the return values. ### Parameters #### Block - **element** (Object) - Required - The block to apply to each element. ### Response - **new_array** (Array) - A new array with transformed elements. ## Array#map! ### Description Calls the block with each element and replaces the original element with the block's return value. ### Parameters #### Block - **element** (Object) - Required - The block to apply to each element. ### Response - **self** (Array) - The modified original array. ``` -------------------------------- ### Database Operations Source: https://context7.com/mariochavez/chroma/llms.txt The Database class provides methods to check server health, version, and reset the database. ```APIDOC ## Database Operations The Database class provides methods to check server health, version, and reset the database. ### Check server heartbeat Returns a timestamp indicating the server is alive. ### Method GET ### Endpoint `/heartbeat` ### Response #### Success Response (200) - **heartbeat** (string) - Nanosecond timestamp indicating server is alive. ### Request Example ```ruby require "chroma-db" Chroma.connect_host = "http://localhost:8000" heartbeat = Chroma::Resources::Database.heartbeat # => {"nanosecond heartbeat" => 1733945890642513627} ``` ### Get Chroma server version Retrieves the version of the Chroma server. ### Method GET ### Endpoint `/version` ### Response #### Success Response (200) - **version** (string) - The version of the Chroma server. ### Request Example ```ruby require "chroma-db" Chroma.connect_host = "http://localhost:8000" version = Chroma::Resources::Database.version # => "0.5.23" ``` ### Reset database **DANGER**: Deletes all data. Use with caution! ### Method POST ### Endpoint `/reset` ### Response #### Success Response (200) - **success** (boolean) - True if the database was reset successfully. ### Request Example ```ruby require "chroma-db" Chroma.connect_host = "http://localhost:8000" Chroma::Resources::Database.reset # => true ``` ``` -------------------------------- ### Retrieve a Collection Source: https://context7.com/mariochavez/chroma/llms.txt Fetch an existing collection by name, handling potential errors if the collection is missing. ```ruby require "chroma-db" Chroma.connect_host = "http://localhost:8000" # Get an existing collection collection = Chroma::Resources::Collection.get("ruby-documentation") puts collection.id # => "dc767e25-55b9-424f-92b1-9bf5aa9841d1" puts collection.name # => "ruby-documentation" puts collection.metadata # => {"lang"=>"ruby", "version"=>"3.2"} # Handle non-existent collection begin collection = Chroma::Resources::Collection.get("non-existent") rescue Chroma::InvalidRequestError => e puts "Collection not found: #{e.message}" end ``` -------------------------------- ### POST /collection/add Source: https://github.com/mariochavez/chroma/blob/main/notebook/Chroma Gem.ipynb Adds a set of embeddings to the specified Chroma collection. ```APIDOC ## POST /collection/add ### Description Adds embeddings to the collection. ### Method POST ### Endpoint /collection/add ### Request Example ```python collection.add(embeddings) ``` ### Response #### Success Response (201) - **message** (string) - Successful response - **code** (integer) - 201 ``` -------------------------------- ### Map Elements In-Place with Class Source: https://github.com/mariochavez/chroma/blob/main/notebook/Chroma Gem.ipynb Shows how to modify an array in-place by mapping each element to its class using Ruby's Array#map! method. This modifies the original array. ```ruby a = [:foo, 'bar', 2] a.map! { |element| element.class } # => [Symbol, String, Integer] ``` -------------------------------- ### Generate Embeddings for Text Chunks in Ruby Source: https://github.com/mariochavez/chroma/blob/main/notebook/Chroma Gem.ipynb This code snippet demonstrates how to use the OllamaHttpClient to generate embeddings for a list of text documents. Each document's content is passed to the client's 'embed' method, and the resulting embeddings are formatted as Chroma::Resources::Embedding objects. Requires 'securerandom' for UUID generation and 'iruby' for display. ```ruby ollama_client = OllamaHttpClient.new embeddings = texts.map do |document| embeddings_response = ollama_client.embed(document.content) Chroma::Resources::Embedding.new(id: SecureRandom.uuid, embedding: embeddings_response["embedding"], metadata: document.metadata, document: document.content) end IRuby.display embeddings ```