### Moss CLI Quick Start Guide Source: https://docs.moss.dev/docs/integrations/moss-cli A quick guide to get started with the Moss CLI, covering credential setup, listing indexes, creating an index, and performing a search query. ```bash # 1. Save credentials moss init # 2. List indexes moss index list # 3. Create an index from a JSON file moss index create my-index -f docs.json --wait # 4. Search it moss query my-index "what is machine learning" # 5. Search via cloud API (skips local download) moss query my-index "neural networks" --cloud ``` -------------------------------- ### Starting LiveKit Server Source: https://docs.moss.dev/docs/integrations/livekit Command to start the LiveKit server in development mode. ```bash livekit-server --dev ``` -------------------------------- ### C Example: Metadata Filtering with libmoss Source: https://docs.moss.dev/docs/reference/c/examples This comprehensive example demonstrates creating a cloud index, loading it locally, and performing searches with $eq, $and, $in, and $near filters. It requires project ID and key as command-line arguments. Ensure the index is loaded locally before querying for filtering to work. ```c #include "libmoss.h" #include #include #include #include static void check(MossResult r, const char *context) { if (r != OK) { const char *err = moss_last_error(); fprintf(stderr, "ERROR [%s]: %s\n", context, err ? err : "(no details)"); exit(1); } } static void print_results(MossSearchResult *res) { for (size_t i = 0; i < res->doc_count; i++) { MossQueryResultDoc *doc = &res->docs[i]; printf(" - %s | score=%.3f", doc->id, doc->score); if (doc->metadata_count > 0) { printf(" | metadata={"); for (size_t j = 0; j < doc->metadata_count; j++) { if (j > 0) printf(", "); printf("%s: %s", doc->metadata[j].key, doc->metadata[j].value); } printf("}"); } printf("\n"); } } int main(int argc, char *argv[]) { if (argc < 3) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } MossClient *client = NULL; check(moss_client_new(argv[1], argv[2], &client), "client_new"); char index_name[64]; time_t now = time(NULL); struct tm *t = localtime(&now); snprintf(index_name, sizeof(index_name), "metadata-filter-sample-%04d%02d%02d-%02d%02d%02d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); // Documents with rich metadata. MossMetadataEntry meta1[] = { { .key = "category", .value = "shoes" }, { .key = "brand", .value = "swiftfit" }, { .key = "price", .value = "79" }, { .key = "city", .value = "new-york" }, { .key = "location", .value = "40.7580,-73.9855" }, }; MossMetadataEntry meta2[] = { { .key = "category", .value = "shoes" }, { .key = "brand", .value = "peakstride" }, { .key = "price", .value = "149" }, { .key = "city", .value = "seattle" }, { .key = "location", .value = "47.6062,-122.3321" }, }; MossMetadataEntry meta3[] = { { .key = "category", .value = "bags" }, { .key = "brand", .value = "urbanpack" }, { .key = "price", .value = "95" }, { .key = "city", .value = "new-york" }, { .key = "location", .value = "40.7505,-73.9934" }, }; MossDocumentInfo docs[] = { { .id = "doc1", .text = "Running shoes with breathable mesh for daily training.", .metadata = meta1, .metadata_count = 5 }, { .id = "doc2", .text = "Trail running shoes built for rocky mountain terrain.", .metadata = meta2, .metadata_count = 5 }, { .id = "doc3", .text = "Lightweight city backpack with laptop compartment.", .metadata = meta3, .metadata_count = 5 }, }; // 1. Create the index. MossMutationResult *cr = NULL; check(moss_client_create_index(client, index_name, docs, 3, NULL, &cr), "create_index"); moss_free_mutation_result(cr); // 2. Load the index locally (required for filtering). MossIndexInfo *loaded = NULL; check(moss_client_load_index(client, index_name, NULL, &loaded), "load_index"); moss_free_index_info(loaded); // 3. $eq - category == shoes printf("$eq: category == shoes\n"); MossQueryOptions eq_opts = { .top_k = 5, .alpha = 0.5f, .filter_json = "{\"field\": \"category\", \"condition\": {\"$eq\": \"shoes\"}}", }; MossSearchResult *eq_res = NULL; check(moss_client_query(client, index_name, "running gear", &eq_opts, &eq_res), "query_eq"); print_results(eq_res); moss_free_search_result(eq_res); // 4. $and - shoes AND price < 100 printf("\n$and: shoes and price < 100\n"); MossQueryOptions and_opts = { .top_k = 5, .alpha = 0.6f, .filter_json = "{\"$and\": [" "{\"field\": \"category\", \"condition\": {\"$eq\": \"shoes\"}}," "{\"field\": \"price\", \"condition\": {\"$lt\": \"100\"}}" "]}", }; MossSearchResult *and_res = NULL; check(moss_client_query(client, index_name, "running shoes", &and_opts, &and_res), "query_and"); print_results(and_res); moss_free_search_result(and_res); // 5. $in - city in [new-york] printf("\n$in: city in [new-york]\n"); MossQueryOptions in_opts = { .top_k = 5, .filter_json = "{\"field\": \"city\", \"condition\": {\"$in\": [\"new-york\"]}}", }; MossSearchResult *in_res = NULL; check(moss_client_query(client, index_name, "city essentials", &in_opts, &in_res), "query_in"); print_results(in_res); moss_free_search_result(in_res); // 6. $near - within 5km of Times Square ``` -------------------------------- ### Install Moss SDK Source: https://docs.moss.dev/docs/integrations/livekit Install the Moss SDK and python-dotenv for environment variable management. ```bash pip install moss \ python-dotenv ``` -------------------------------- ### Install Python Voice Server SDK Source: https://docs.moss.dev/docs/voice-agents/voice-agents Install the moss-voice-server package for Python applications. ```bash pip install moss-voice-server ``` -------------------------------- ### Install Moss SDK Source: https://docs.moss.dev/docs/start/quickstart Install the Moss SDK using npm for JavaScript or pip for Python. ```bash npm install @moss-dev/moss ``` ```bash pip install moss ``` -------------------------------- ### Install Node.js Voice Server SDK Source: https://docs.moss.dev/docs/voice-agents/voice-agents Install the @moss-tools/voice-server package for Node.js applications. ```bash npm install @moss-tools/voice-server ``` -------------------------------- ### Example Custom Authenticator Implementation Source: https://docs.moss.dev/docs/reference/swift/custom-authenticator Provides a concrete example of implementing the `Authenticator` protocol. This `MyAuth` class demonstrates fetching a token from a server and initializing the `MossClient` with it. ```swift import Moss final class MyAuth: Authenticator { func getAuthHeader() async throws -> String { // Fetch / refresh a bearer token from your server. try await myServer.fetchMossToken() } } let client = try MossClient(projectId: "your-project-id", authenticator: MyAuth()) defer { client.close() } ``` -------------------------------- ### Start Index Build Request Source: https://docs.moss.dev/docs/api-reference/v1/index-management/startBuild Use this `curl` command to send a POST request to the `v1/manage` endpoint to start an index build. Ensure you replace placeholders like `x-project-key` and `jobId` with your actual values. The `jobId` should be obtained from a previous `initUpload` call. ```bash curl -X POST "https://service.usemoss.dev/v1/manage" \ -H "Content-Type: application/json" \ -H "x-service-version: v1" \ -H "x-project-key: moss_access_key_xxxxx" \ -d '{ "action": "startBuild", "projectId": "project_123", "jobId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" }' ``` -------------------------------- ### Install agora-moss Package Source: https://docs.moss.dev/docs/integrations/agora Install the necessary Python package for integrating Moss with Agora. ```bash pip install agora-moss ``` -------------------------------- ### Install @moss-dev/moss-web Source: https://docs.moss.dev/docs/reference/browser/api Install the Moss Browser SDK using npm. The WebAssembly module and embedding model download on first use. ```bash npm install @moss-dev/moss-web ``` -------------------------------- ### Install Moss Package Source: https://docs.moss.dev/docs/integrations/nextjs Install the Moss Node.js package using npm. ```bash npm install @moss-dev/moss ``` -------------------------------- ### Install vapi-moss Package Source: https://docs.moss.dev/docs/integrations/vapi Install the necessary Python package for integrating Moss with VAPI. ```bash pip install vapi-moss ``` -------------------------------- ### Quick Start: Build, Push, and Load Index Source: https://docs.moss.dev/docs/reference/swift/api Demonstrates the core workflow: building an on-device index, querying it, pushing it to the cloud, and then loading it back into a new session for querying. ```swift import Moss let client = try MossClient(projectId: "your_project_id", projectKey: "your_project_key") default: client.close() // 1. Build an index on-device. Documents are embedded locally and can carry // metadata you filter on later. let session = try await client.session("products") try await session.addDocs([ .init(id: "p1", text: "Running shoes with breathable mesh.", metadata: ["category": "shoes", "brand": "swiftfit", "price": "79", "city": "new-york"]), .init(id: "p2", text: "Lightweight city backpack.", metadata: ["category": "bags", "brand": "urbanpack", "price": "95", "city": "seattle"]), ]) // 2. Query locally. Tune `alpha` and add metadata filters - see the Querying guide. let hits = try await session.query("something to run in", options: .init(topK: 3)) hits.docs.forEach { print($0.score, $0.id) } // 3. Push it to the cloud and wait for the job to finish. let push = try await session.pushIndex() session.close() while try await client.getJobStatus(push.jobId).status != "ready" { try await Task.sleep(nanoseconds: 1_000_000_000) } // 4. Load it back into a new session and query - still on-device. let restored = try await client.session(push.indexName) default: restored.close() _ = try await restored.loadIndex(push.indexName) let results = try await restored.query("something to run in", options: .init(topK: 3)) print(results.docs.map(\.id)) ``` -------------------------------- ### Elixir Session Example: Add Docs and Query Source: https://docs.moss.dev/docs/reference/elixir/classes/Session Demonstrates opening a client and session, adding documents, performing a query, and pushing the index to the cloud. ```elixir {:ok, client} = Moss.Client.new("project-id", "project-key") {:ok, session} = Moss.Client.session(client, "session-abc") docs = [ %Moss.DocumentInfo{id: "turn-1", text: "Customer: I need to cancel my subscription"}, %Moss.DocumentInfo{id: "turn-2", text: "Agent: I can help with that. Can I ask why?"} ] {:ok, {2, 0}} = Moss.Session.add_docs(session, docs) {:ok, result} = Moss.Session.query(session, "subscription cancellation", top_k: 2) {:ok, push_result} = Moss.Session.push_index(session) ``` -------------------------------- ### Quick Start: Create, Load, and Query Index Source: https://docs.moss.dev/docs/reference/python/api Initialize MossClient, create a new index with documents, load it into memory, and perform a query. Requires MOSS_PROJECT_ID and MOSS_PROJECT_KEY. ```python import asyncio from moss import MossClient, DocumentInfo, QueryOptions async def main(): client = MossClient(MOSS_PROJECT_ID, MOSS_PROJECT_KEY) await client.create_index("faqs", [ DocumentInfo(id="doc1", text="Track your order in your account.", metadata={"category": "shipping"}), DocumentInfo(id="doc2", text="30-day return policy for most items.", metadata={"category": "returns"}), ]) await client.load_index("faqs") results = await client.query("faqs", "return a damaged product", QueryOptions(top_k=3)) for doc in results.docs: print(doc.id, doc.score) asyncio.run(main()) ``` -------------------------------- ### Install LangChain and Moss Libraries Source: https://docs.moss.dev/docs/integrations/langchain Install the necessary Python packages for LangChain, Moss integration, OpenAI, and environment variable management. ```bash pip install moss langchain langchain-openai python-dotenv ``` -------------------------------- ### Python Example: Local Session Operations Source: https://docs.moss.dev/docs/build/real-time-local-indexing Demonstrates opening a local session, adding documents, and performing a query. Ensure you have MOSS_PROJECT_ID and MOSS_PROJECT_KEY configured. ```python import asyncio from moss import DocumentInfo, MossClient, QueryOptions async def main(): client = MossClient(MOSS_PROJECT_ID, MOSS_PROJECT_KEY) # Open a session: new local index, or load an existing cloud index by name. session = await client.session(index_name="notes") # Add documents (embedded and indexed locally). added, updated = await session.add_docs([ DocumentInfo(id="1", text="Ship the on-device SDK by Friday."), DocumentInfo(id="2", text="Follow up with the LiveKit team about latency."), ]) print(f"{added} added, {updated} updated, {session.doc_count} total") # Query the in-memory index. results = await session.query("what's due this week", QueryOptions(top_k=3)) for doc in results.docs: print(f"{doc.id} score={doc.score:.3f} {doc.text}") asyncio.run(main()) ``` -------------------------------- ### Install moss-voice-agent-manager Source: https://docs.moss.dev/docs/voice-agents/voice-agents Install the Python package for building voice agents. This package handles STT, LLM, and TTS provider configuration automatically. ```bash pip install moss-voice-agent-manager ``` -------------------------------- ### Python Example for Live-Call Context Management Source: https://docs.moss.dev/docs/build/live-call-context Demonstrates loading a long-term index, opening a session, adding documents, querying both indexes, and persisting the session. ```python import asyncio from datetime import datetime from moss import DocumentInfo, MossClient, QueryOptions async def main(): client = MossClient(MOSS_PROJECT_ID, MOSS_PROJECT_KEY) # Long-term context: load a persistent knowledge index. await client.load_index("support-faqs") # Short-term context: open a session for this call. call_id = f"call-{datetime.now():%Y%m%d-%H%M%S}" session = await client.session(index_name=call_id) # Index transcript turns into the session. await session.add_docs([ DocumentInfo(id="turn-1", text="Customer was billed twice for the same renewal."), DocumentInfo(id="turn-2", text="Customer requested a refund for the duplicate $49.99 charge."), ]) # Query both indexes and combine the results for the model. knowledge = await client.query("support-faqs", "duplicate charge refund policy", QueryOptions(top_k=3)) recent = await session.query("refund request", QueryOptions(top_k=3)) for doc in recent.docs: print(f"[session] {doc.id} score={doc.score:.3f} {doc.text}") for doc in knowledge.docs: print(f"[faqs] {doc.id} score={doc.score:.3f} {doc.text}") # Persist the session at call end. result = await session.push_index() print(f"Pushed {result.doc_count} docs to cloud index {result.index_name!r}") asyncio.run(main()) ``` -------------------------------- ### Start VitePress Development Server Source: https://docs.moss.dev/docs/integrations/vitepress Run the VitePress dev command to build and serve your site locally. Use Ctrl+K or Cmd+K to test the search functionality. ```bash vitepress dev docs ``` -------------------------------- ### Initialize and Use SessionIndex Source: https://docs.moss.dev/docs/reference/python/classes/SessionIndex Demonstrates how to initialize a SessionIndex, add documents, perform a query, and push the index to the cloud. The session automatically loads an existing index or starts fresh. ```python # Auto-loads from cloud if the index exists, starts fresh if not session = await client.session(index_name="session-abc") await session.add_docs([DocumentInfo(id="1", text="Customer asked about billing")]) results = await session.query("billing question") result = await session.push_index() # optionally: await client.get_job_status(result.job_id) ``` -------------------------------- ### Instantiate QueryOptions with Filter Source: https://docs.moss.dev/docs/reference/python/interfaces/QueryOptions Example of creating a QueryOptions object with specific top_k, alpha, and a complex filter combining AND conditions. ```python from moss import QueryOptions options = QueryOptions( top_k=5, alpha=0.6, filter={ "$and": [ {"field": "category", "condition": {"$eq": "shoes"}}, {"field": "price", "condition": {"$lt": 100}}, ], }, ) ``` -------------------------------- ### Install Moss CLI Source: https://docs.moss.dev/docs/integrations/moss-cli Install the Moss CLI using pip. This command installs the necessary package to manage Moss services from your terminal. ```bash pip install moss-cli ``` -------------------------------- ### Quick Start: Initialize Client, Create, Load, and Query Index Source: https://docs.moss.dev/docs/reference/elixir/api Demonstrates the basic workflow: initializing the client, preparing documents, creating a cloud index, loading it into memory, and performing a query. ```elixir alias Moss.{Client, DocumentInfo} # Initialize the client with your project credentials {:ok, client} = Client.new("your-project-id", "your-project-key") # Prepare documents to index documents = [ %DocumentInfo{ id: "doc1", text: "How do I track my order? Log into your account to see live status.", metadata: %{"category" => "shipping"} }, %DocumentInfo{ id: "doc2", text: "What is your return policy? We offer a 30-day return policy.", metadata: %{"category" => "returns"} } ] # Create a cloud index (defaults to the moss-minilm model) {:ok, _} = Client.create_index(client, "faqs", documents) # Load the index into memory before querying {:ok, _} = Client.load_index(client, "faqs") # Query the loaded index {:ok, result} = Client.query(client, "faqs", "How do I return a damaged product?", top_k: 3, alpha: 0.6) IO.puts("Query: #{result.query}") for doc <- result.docs do IO.puts("#{doc.id} (#{Float.round(doc.score, 4)}): #{doc.text}") end ``` -------------------------------- ### Moss CLI Authentication Methods Source: https://docs.moss.dev/docs/integrations/moss-cli Set up authentication for the Moss CLI. It supports interactive setup, environment variables, CLI flags, and configuration profiles. ```bash # Interactive setup (recommended) moss init moss init --profile staging # Environment variables export MOSS_PROJECT_ID="your-project-id" export MOSS_PROJECT_KEY="your-project-key" # Inline flags moss index list --project-id "..." --project-key "..." # Profile-based moss index list --profile staging moss profile list ``` -------------------------------- ### Quickstart: Initialize Client, Create, Load, and Query Index Source: https://docs.moss.dev/docs/reference/browser/api Initialize the MossClient, create a new index with documents, load it into the browser for local querying, and then perform a semantic search. Querying requires the index to be loaded first. ```typescript import { MossClient } from "@moss-dev/moss-web"; // 1. Initialize the client (WASM/model download happens on first use) const client = new MossClient("your-project-id", "your-project-key"); // 2. Create an index with documents await client.createIndex("knowledge-base", [ { id: "1", text: "Machine learning fundamentals" }, { id: "2", text: "Deep learning neural networks" }, ]); // 3. Load the index into the browser for fast local queries await client.loadIndex("knowledge-base"); // 4. Query - runs entirely in-browser const results = await client.query("knowledge-base", "AI and neural networks"); results.docs.forEach((doc) => { console.log(`${doc.id}: ${doc.text} (score: ${doc.score})`); }); ``` -------------------------------- ### C SDK: Session workflow example Source: https://docs.moss.dev/docs/reference/c/examples Demonstrates a complete session workflow: creating a client, opening a session, adding documents with metadata, querying locally, fetching documents, and pushing the index to the cloud. Requires project ID and key as command-line arguments. ```c #include "libmoss.h" #include #include static void check(MossResult r, const char *context) { if (r != OK) { const char *err = moss_last_error(); fprintf(stderr, "ERROR [%s]: %s\n", context, err ? err : "(no details)"); exit(1); } } int main(int argc, char *argv[]) { if (argc < 3) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } printf("Moss SDK version: %s\n\n", moss_sdk_version()); // 1. Create client. MossClient *client = NULL; check(moss_client_new(argv[1], argv[2], &client), "client_new"); // 2. Open a session. MossSession *session = NULL; check(moss_client_session(client, "c-sdk-demo", NULL, &session), "session"); printf("Session: name=%s, doc_count=%zu\n", moss_session_name(session), moss_session_doc_count(session)); // 3. Add documents with metadata. MossMetadataEntry meta1[] = { { .key = "type", .value = "billing" }, { .key = "priority", .value = "high" }, }; MossMetadataEntry meta2[] = { { .key = "type", .value = "gardening" }, }; MossDocumentInfo docs[] = { { .id = "doc-1", .text = "Customer requested a billing refund and invoice review.", .metadata = meta1, .metadata_count = 2 }, { .id = "doc-2", .text = "How to prune tomato plants in a home garden.", .metadata = meta2, .metadata_count = 1 }, }; size_t added = 0, updated = 0; check(moss_session_add_docs(session, docs, 2, NULL, &added, &updated), "add_docs"); printf("Added %zu, updated %zu. Total: %zu\n\n", added, updated, moss_session_doc_count(session)); // 4. Query. MossSearchResult *result = NULL; check(moss_session_query(session, "billing refund", NULL, &result), "query"); printf("Query \"%s\" - %zu results in %llu ms\n", result->query, result->doc_count, (unsigned long long)result->time_taken_ms); for (size_t i = 0; i < result->doc_count; i++) { printf(" %s score=%.4f\n", result->docs[i].id, result->docs[i].score); } moss_free_search_result(result); // 5. Query with a metadata filter. MossQueryOptions opts = { .top_k = 5, .alpha = 0.8f, .filter_json = "{\"field\": \"type\", \"condition\": {\"$eq\": \"billing\"}}", }; MossSearchResult *filtered = NULL; check(moss_session_query(session, "refund", &opts, &filtered), "query_filtered"); printf("\nFiltered query - %zu results\n", filtered->doc_count); for (size_t i = 0; i < filtered->doc_count; i++) { printf(" %s score=%.4f\n", filtered->docs[i].id, filtered->docs[i].score); } moss_free_search_result(filtered); // 6. Fetch all documents (NULL ids = all). MossDocumentInfo *fetched = NULL; size_t fetched_count = 0; check(moss_session_get_docs(session, NULL, 0, &fetched, &fetched_count), "get_docs"); printf("\nAll docs (%zu):\n", fetched_count); for (size_t i = 0; i < fetched_count; i++) { printf(" %s\n", fetched[i].id); } moss_free_documents(fetched, fetched_count); // 7. Push to the cloud. MossPushIndexResult *push = NULL; check(moss_session_push_index(session, &push), "push_index"); printf("\nPushed: job_id=%s status=%s doc_count=%zu\n", push->job_id, push->status, push->doc_count); moss_free_push_index_result(push); // 8. Cleanup. moss_session_free(session); moss_client_free(client); printf("\nDone.\n"); return 0; } ``` -------------------------------- ### Install Pipecat-Moss Package Source: https://docs.moss.dev/docs/integrations/pipecat Install the official Pipecat-Moss integration package using pip. ```bash pip install pipecat-moss ``` -------------------------------- ### Initialize MossClient and Use On-Device Session Source: https://docs.moss.dev/docs/reference/swift/classes/MossClient Constructs a MossClient with project ID and key, opens an on-device session, adds documents, and performs a query. Ensure to close the client when done. ```swift import Moss let client = try MossClient(projectId: "your-project-id", projectKey: "your-project-key") defer { client.close() } // Open an on-device session and search locally. let session = try await client.session("docs") try await session.addDocs([ .init(id: "1", text: "Machine learning fundamentals"), .init(id: "2", text: "Deep learning neural networks"), ]) let results = try await session.query("AI and neural networks") ``` -------------------------------- ### Install Agent CLI Source: https://docs.moss.dev/docs/voice-agents/voice-agents Install the moss-agent-cli package for managing voice agents from the command line. ```bash pip install moss-agent-cli ``` -------------------------------- ### Quick Start: Create, Load, and Query Index Source: https://docs.moss.dev/docs/reference/js/api Initialize the MossClient, create a new index with documents, load it into memory, and perform a query. Requires MOSS_PROJECT_ID and MOSS_PROJECT_KEY environment variables. ```typescript import { MossClient } from '@moss-dev/moss' const client = new MossClient(process.env.MOSS_PROJECT_ID!, process.env.MOSS_PROJECT_KEY!) await client.createIndex('faqs', [ { id: 'doc1', text: 'Track your order in your account.', metadata: { category: 'shipping' } }, { id: 'doc2', text: '30-day return policy for most items.', metadata: { category: 'returns' } }, ]) await client.loadIndex('faqs') const results = await client.query('faqs', 'return a damaged product', { topK: 3 }) results.docs.forEach(d => console.log(d.id, d.score)) ``` -------------------------------- ### Basic libmoss Workflow: Index, Query, and Push Source: https://docs.moss.dev/docs/reference/c/getting-started This snippet shows the complete cycle of opening a session, adding documents, performing a local query, and pushing the index to the cloud. It's suitable for understanding the core functionality. ```c #include "libmoss.h" #include int main(void) { MossClient *client = NULL; moss_client_new("your-project-id", "your-project-key", &client); // Open a session (auto-embeds with the built-in model). MossSession *session = NULL; moss_client_session(client, "my-index", NULL, &session); // Add documents. Metadata is optional; pass NULL / 0 to skip it. MossDocumentInfo docs[] = { { .id = "1", .text = "Billing refund request" }, { .id = "2", .text = "How to grow tomatoes" }, }; size_t added = 0, updated = 0; moss_session_add_docs(session, docs, 2, NULL, &added, &updated); // Query locally - no network round trip. MossSearchResult *result = NULL; moss_session_query(session, "refund", NULL, &result); for (size_t i = 0; i < result->doc_count; i++) { printf("%s score=%.4f\n", result->docs[i].id, result->docs[i].score); } moss_free_search_result(result); // Push to the cloud so other devices can load it. MossPushIndexResult *push = NULL; moss_session_push_index(session, &push); moss_free_push_index_result(push); moss_session_free(session); moss_client_free(client); return 0; } ``` -------------------------------- ### Get Index Metadata Source: https://docs.moss.dev/docs/reference/browser/classes/MossClient Retrieves metadata for a specific index. Use this to get information about an existing index. ```typescript const info = await client.getIndex("knowledge-base"); ``` -------------------------------- ### Initialize and Use MossSession Source: https://docs.moss.dev/docs/reference/swift/classes/MossSession Demonstrates how to initialize a MossSession, add documents, and perform a query. Ensure to close the session when done. ```swift let session = try await client.session("notes") defer { session.close() } _ = try await session.addDocs([ .init(id: "1", text: "first note"), .init(id: "2", text: "second note"), ]) let result = try await session.query("first") result.docs.forEach { print($0.score, $0.id) } ``` -------------------------------- ### Install elevenlabs-moss package Source: https://docs.moss.dev/docs/integrations/elevenlabs Install the necessary Python package for integrating ElevenLabs with Moss. Ensure you have Python 3.10+. ```bash pip install elevenlabs-moss ``` -------------------------------- ### Install Moss Python SDK Source: https://docs.moss.dev/docs/reference/python/api Install the Moss Python SDK using pip. Ensure you have Python 3.10 or higher. ```bash pip install moss ``` -------------------------------- ### Example Query Output Source: https://docs.moss.dev/docs/start/quickstart This is an example of the JSON output format for a query result, showing the document ID, score, and text. ```json { "id": "doc2", "score": 0.88, "text": "What is your return policy? We offer a 30-day return policy for most items." } ``` -------------------------------- ### Real-time Local Indexing with Moss Sessions (Python) Source: https://docs.moss.dev/docs/integrate/indexing-data Shows how to use Moss sessions for real-time, on-device indexing during live interactions. This example demonstrates creating or resuming a local session, adding documents locally without network calls, and optionally pushing the index to the cloud. ```python import asyncio from moss import DocumentInfo, MossClient async def main(): client = MossClient(project_id, project_key) # Create or resume a local index by name. session = await client.session(index_name="my-session-index") # Index locally in real time - embedded on-device, no network. await session.add_docs([ DocumentInfo(id="turn-1", text="Customer confirmed the refund was received."), ]) # Optionally push the session to the cloud when done. await session.push_index() asyncio.run(main()) ``` -------------------------------- ### Install vitepress-plugin-moss with yarn Source: https://docs.moss.dev/docs/integrations/vitepress Install the plugin using yarn. Ensure your project has "type": "module" in package.json. ```bash yarn add vitepress-plugin-moss ``` -------------------------------- ### Create and Use a SessionIndex Source: https://docs.moss.dev/docs/reference/js/classes/SessionIndex Demonstrates how to initialize a MossClient, create a new session, add documents, perform a query, and push the session index to the cloud. ```typescript import { MossClient } from '@moss-dev/moss'; const client = new MossClient('your-project-id', 'your-project-key'); const session = await client.session('chat-session-123'); await session.addDocs([{ id: '1', text: 'Customer asked about billing' }]); const results = await session.query('billing question'); await session.pushIndex(); ``` -------------------------------- ### Install vitepress-plugin-moss with pnpm Source: https://docs.moss.dev/docs/integrations/vitepress Install the plugin using pnpm. Ensure your project has "type": "module" in package.json. ```bash pnpm add vitepress-plugin-moss ``` -------------------------------- ### Create and Query a Session Source: https://docs.moss.dev/docs/reference/python/api Demonstrates how to create a new session, add documents, query the session, and push the index to the cloud. This is useful for real-time indexing and querying. ```python session = await client.session(index_name="call-123") await session.add_docs([DocumentInfo(id="turn-1", text="Customer reported a duplicate charge.")]) hits = await session.query("billing issue", QueryOptions(top_k=3)) await session.push_index() ``` -------------------------------- ### Install vitepress-plugin-moss with npm Source: https://docs.moss.dev/docs/integrations/vitepress Install the plugin using npm. Ensure your project has "type": "module" in package.json. ```bash npm install vitepress-plugin-moss ``` -------------------------------- ### Install DSPy and Moss Dependencies Source: https://docs.moss.dev/docs/integrations/dspy Install the necessary Python packages for integrating Moss with DSPy. This includes the moss client, dspy, and utilities for environment management and asynchronous operations. ```bash pip install moss dspy nest-asyncio python-dotenv ``` -------------------------------- ### Python Session Management Example Source: https://docs.moss.dev/docs/reference/python/sessions Demonstrates loading a long-term index, creating a short-term session, adding documents, querying both contexts, and persisting the session. Ensure MOSS_PROJECT_ID and MOSS_PROJECT_KEY are set in your environment. ```python import asyncio from moss import DocumentInfo, MossClient, QueryOptions async def main(): client = MossClient(MOSS_PROJECT_ID, MOSS_PROJECT_KEY) # Long-term context: a persistent cloud index, loaded for in-process queries. await client.load_index("support-faqs") # Short-term context: a session for this specific call. session = await client.session(index_name="call-abc") # As each turn arrives, index it locally (~1-5 ms). await session.add_docs([ DocumentInfo(id="turn-1", text="Customer was billed twice for the same renewal."), ]) # Query both for context on the current turn. user_turn = "why was I charged twice" recent = await session.query(user_turn, QueryOptions(top_k=3)) # this call knowledge = await client.query("support-faqs", user_turn, QueryOptions(top_k=3)) # all-time context = list(recent.docs) + list(knowledge.docs) for doc in context: print(f"{doc.id} score={doc.score:.3f} {doc.text}") # At call end, persist the session for future retrieval. await session.push_index() await client.unload_index("support-faqs") asyncio.run(main()) ``` -------------------------------- ### Initialize MossVapiSearch and Search Index Source: https://docs.moss.dev/docs/integrations/vapi Initialize the MossVapiSearch client with index details and load the index. Then, perform a search query and print the results and time taken. ```python from vapi_moss import MossVapiSearch, verify_vapi_signature # Initialize the search client search = MossVapiSearch( index_name="my-faq-index", top_k=5, alpha=0.8, ) # Load the index at startup await search.load_index() # Search result = await search.search("How do I return an item?") print(result.documents) # [{"content": "...", "similarity": 0.92}, ...] print(result.time_taken_ms) # 3 ``` -------------------------------- ### Install Vercel AI SDK Moss Package Source: https://docs.moss.dev/docs/integrations/vercel-ai-sdk Install the necessary packages for integrating Moss with the Vercel AI SDK. This includes the Moss SDK, Vercel SDK package, AI SDK, and Zod for schema definition. ```bash npm install @moss-tools/vercel-sdk @moss-dev/moss ai zod ``` -------------------------------- ### Initialize and Use MossClient Source: https://docs.moss.dev/docs/reference/js/classes/MossClient Initializes the MossClient with project credentials and demonstrates creating an index, adding documents, and querying the index. All mutation operations poll until completion. ```typescript import { MossClient } from '@moss-dev/moss'; const client = new MossClient('your-project-id', 'your-project-key'); // Create an index with documents (polls until complete) const result = await client.createIndex('docs', [ { id: '1', text: 'Machine learning fundamentals' }, { id: '2', text: 'Deep learning neural networks' } ]); // Add docs (polls until complete) await client.addDocs('docs', [ { id: '3', text: 'Natural language processing' } ]); // Query the index await client.loadIndex('docs'); const results = await client.query('docs', 'AI and neural networks'); ``` -------------------------------- ### Running the Agent Worker Source: https://docs.moss.dev/docs/integrations/livekit Commands to download necessary files and start the agent worker. ```bash python agent.py download-files python agent.py console ``` -------------------------------- ### JavaScript Example: Managing Agent Context Source: https://docs.moss.dev/docs/build/agent-context Demonstrates creating, loading, querying, and updating an agent context index using the MossClient. Use this to manage both working and durable context. ```typescript import { MossClient } from '@moss-dev/moss' const client = new MossClient(process.env.MOSS_PROJECT_ID!, process.env.MOSS_PROJECT_KEY!) const index = 'agent-context' await client.createIndex(index, [ { id: 'user_profile', text: 'User prefers concise answers.' } ], { modelId: 'moss-minilm' }) // Load before querying. await client.loadIndex(index) // Recall: pull relevant context for this turn. const context = await client.query(index, 'preferences for responses', { topK: 3 }) // Capture: write new insights back so the next turn can use them. await client.addDocs(index, [ { id: 'pref_format', text: 'User asked for bullet-point summaries.' } ], { upsert: true }) ``` -------------------------------- ### ISODate Example Source: https://docs.moss.dev/docs/reference/js/type-aliases/ISODate Demonstrates the string format for an ISODate, which adheres to the ISO 8601 standard. ```typescript "2025-09-26T15:04:05Z" ``` -------------------------------- ### Environment Variables for LiveKit and Moss Source: https://docs.moss.dev/docs/integrations/livekit Set up your .env file with LiveKit, Moss, and AI provider credentials. ```bash # LiveKit Credentials, keep it as it is for local deployment, don't change it. LIVEKIT_URL=ws://localhost:7880 LIVEKIT_API_KEY=devkey LIVEKIT_API_SECRET=secret # Moss Credentials MOSS_PROJECT_ID=your-moss-id MOSS_PROJECT_KEY=your-moss-key # AI Provider Keys OPENAI_API_KEY=sk-... DEEPGRAM_API_KEY=your-deepgram-key ``` -------------------------------- ### Get SDK Version Source: https://docs.moss.dev/docs/reference/swift/classes/MossClient Retrieves the version string of the native Moss runtime used by the SDK. ```swift static var sdkVersion: String ``` -------------------------------- ### listIndexes() Source: https://docs.moss.dev/docs/reference/browser/classes/MossClient Lists all available indexes within the system. This is useful for getting an overview of all managed indexes. ```APIDOC ## listIndexes() ### Description Lists all available indexes. ### Method client.listIndexes ### Request Example ```typescript const indexes = await client.listIndexes(); ``` ``` -------------------------------- ### LiveKit Agent Entrypoint Source: https://docs.moss.dev/docs/integrations/livekit Initializes and runs the LiveKit agent, connecting to Moss for context management and setting up the voice pipeline. ```python async def entrypoint(ctx: JobContext): await ctx.connect() # Initialize Moss moss_client = MossClient(project_id=MOSS_PROJECT_ID, project_key=MOSS_PROJECT_KEY) # Long-term context: load the persistent knowledge base for in-process queries. try: await moss_client.load_index(KNOWLEDGE_INDEX) logger.info(f"Loaded knowledge index: {KNOWLEDGE_INDEX}") except Exception as e: logger.warning(f"Knowledge index not loaded: {e}. Run build_index.py first.") # Short-term context: open a session keyed to this call. It auto-loads if a # cloud index with this name already exists (an earlier handoff), or starts # empty for a brand-new call. call_id = f"call-{ctx.room.name}" moss_session = await moss_client.session(index_name=call_id) logger.info(f"Opened session '{call_id}' ({moss_session.doc_count} docs loaded)") # When the call ends, push the session to the cloud so the conversation can # be resumed later or handed off to another agent. async def persist_session(): try: result = await moss_session.push_index() logger.info(f"Pushed session '{call_id}': {result.doc_count} docs") except Exception as e: logger.error(f"Failed to push session: {e}") ctx.add_shutdown_callback(persist_session) # Create the LiveKit voice pipeline. session = AgentSession( stt=deepgram.STT(), llm=openai.LLM(model="gpt-4o"), tts=openai.TTS(), turn_detection=EnglishModel(), vad=silero.VAD.load(), ) # Start the session with our custom MossSemanticRetrievalAgent. await session.start( agent=MossSemanticRetrievalAgent(moss_client, moss_session), room=ctx.room, ) if __name__ == "__main__": cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint)) ``` -------------------------------- ### MemoryPressureLevel Source: https://docs.moss.dev/docs/reference/swift/types Enum representing different levels of memory pressure, used to guide cache management. ```APIDOC ## MemoryPressureLevel Passed to [`onMemoryPressure`](./classes/MossClient#onmemorypressure_). ### Description Enum representing different levels of memory pressure, used to guide cache management. ### Cases - **low** (UInt8) - Hint to drop hot caches. - **critical** (UInt8) - Drop everything reclaimable; on-disk caches are kept. ``` -------------------------------- ### Set up environment variables Source: https://docs.moss.dev/docs/integrations/elevenlabs Create a .env file in your project root to store Moss and ElevenLabs credentials. This includes project IDs, keys, index names, and API keys. ```dotenv # Moss Credentials MOSS_PROJECT_ID=your_project_id MOSS_PROJECT_KEY=your_project_key MOSS_INDEX_NAME=support-docs # ElevenLabs Credentials ELEVENLABS_API_KEY=your_elevenlabs_api_key ELEVENLABS_AGENT_ID=your_agent_id ``` -------------------------------- ### Moss Index Information Retrieval Source: https://docs.moss.dev/docs/reference/c/api Functions to get information about a specific index or list all available indexes. ```c MossResult moss_client_get_index(MossClient *client, const char *name, MossIndexInfo **out); MossResult moss_client_list_indexes(MossClient *client, MossIndexInfo **out, uintptr_t *out_count); ``` -------------------------------- ### Environment Variables for Credentials Source: https://docs.moss.dev/docs/integrations/agora Set up your Moss and Agora credentials in a .env file for the application. ```bash # Moss Credentials MOSS_PROJECT_ID=your_project_id MOSS_PROJECT_KEY=your_project_key MOSS_INDEX_NAME=support-docs # Agora Credentials AGORA_APP_ID=your_app_id AGORA_APP_CERTIFICATE=your_app_certificate AGORA_CUSTOMER_ID=your_customer_id AGORA_CUSTOMER_SECRET=your_customer_secret ``` -------------------------------- ### Elixir Session: Get Documents Source: https://docs.moss.dev/docs/reference/elixir/classes/Session Retrieves documents from the session index. Can filter by a list of document IDs. ```elixir docs = Moss.Session.get_docs(session, doc_ids: ["turn-1"]) ``` -------------------------------- ### Initialize and Query MossClient Source: https://docs.moss.dev/docs/reference/browser/classes/MossClient Demonstrates creating a MossClient, adding documents to a new index, loading the index, and performing a semantic search query. The WebAssembly module and embedding model load on the first API call. ```typescript import { MossClient } from "@moss-dev/moss-web"; const client = new MossClient("your-project-id", "your-project-key"); // Create an index with documents await client.createIndex("docs", [ { id: "1", text: "Machine learning fundamentals" }, { id: "2", text: "Deep learning neural networks" }, ]); // Load the index into the browser, then query it await client.loadIndex("docs"); const results = await client.query("docs", "AI and neural networks"); ``` -------------------------------- ### List All Indexes Source: https://docs.moss.dev/docs/reference/js/classes/MossClient Fetches a list of all available indexes in the Moss system. Useful for getting an overview of your indexed data. ```typescript const indexes = await client.listIndexes(); indexes.forEach(index => { console.log(`${index.name}: ${index.docCount} docs`); }); ```