> ## Documentation Index
> Fetch the complete documentation index at: https://developer.swytcho.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Generate Embeddings for Semantic Search with Swytcho

> Convert text into dense vectors with the Swytcho embeddings endpoint. Power semantic search, RAG pipelines, clustering, and content recommendation systems.

Embeddings transform text into arrays of floating-point numbers — dense vectors that capture the semantic meaning of the input. Text with similar meaning ends up close together in vector space, regardless of whether the exact words match. This makes embeddings the foundation for semantic search, retrieval-augmented generation (RAG), document clustering, and content recommendation.

## Common Use Cases

* **Semantic search** — find documents that are conceptually related to a query, not just keyword-matched
* **Retrieval-augmented generation (RAG)** — embed your knowledge base, retrieve the most relevant chunks at query time, and pass them as context to a chat completion
* **Document clustering** — group large document sets by topic without predefined labels
* **Recommendation** — surface items similar to what a user has already engaged with
* **Classification** — train a lightweight classifier on top of embeddings as features

## Generate an Embedding

Make a `POST` request to `https://api.swytcho.com/v1/embeddings` with your model and the input text.

<CodeGroup>
  ```python Python theme={null}
  import os
  import requests

  response = requests.post(
      "https://api.swytcho.com/v1/embeddings",
      headers={
          "Authorization": f"Bearer {os.environ['SWYTCHO_API_KEY']}",
          "Content-Type": "application/json",
      },
      json={
          "model": "swytcho-embed",
          "input": "Semantic search retrieves results based on meaning, not keywords.",
      },
  )

  result = response.json()
  embedding = result["data"][0]["embedding"]
  print(f"Dimensions: {len(embedding)}")
  # → Dimensions: 1536
  ```

  ```javascript Node.js theme={null}
  import fetch from "node-fetch";

  const response = await fetch("https://api.swytcho.com/v1/embeddings", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.SWYTCHO_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "swytcho-embed",
      input: "Semantic search retrieves results based on meaning, not keywords.",
    }),
  });

  const result = await response.json();
  const embedding = result.data[0].embedding;
  console.log(`Dimensions: ${embedding.length}`);
  // → Dimensions: 1536
  ```

  ```bash curl theme={null}
  curl https://api.swytcho.com/v1/embeddings \
    -H "Authorization: Bearer $SWYTCHO_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "swytcho-embed",
      "input": "Semantic search retrieves results based on meaning, not keywords."
    }'
  ```
</CodeGroup>

## Response Format

The API returns an object with a `data` array. Each entry corresponds to one input string and contains the embedding vector at `embedding`.

```json theme={null}
{
  "object": "list",
  "model": "swytcho-embed",
  "data": [
    {
      "object": "embedding",
      "index": 0,
      "embedding": [0.0023, -0.0094, 0.0112, "...1533 more values..."]
    }
  ],
  "usage": {
    "prompt_tokens": 12,
    "total_tokens": 12
  }
}
```

Access the vector with `result["data"][0]["embedding"]`. Store it as a list of floats in your database or vector store.

## Batch Embedding

Pass an array of strings as `input` to embed multiple texts in a single API call. The response `data` array preserves the original order via the `index` field.

```python Python theme={null}
import os
import requests

documents = [
    "How do I reset my password?",
    "What payment methods do you accept?",
    "How do I cancel my subscription?",
    "Where can I find my invoice?",
]

response = requests.post(
    "https://api.swytcho.com/v1/embeddings",
    headers={
        "Authorization": f"Bearer {os.environ['SWYTCHO_API_KEY']}",
        "Content-Type": "application/json",
    },
    json={
        "model": "swytcho-embed",
        "input": documents,
    },
)

result = response.json()
# Sort by index to guarantee order
embeddings = [item["embedding"] for item in sorted(result["data"], key=lambda x: x["index"])]
print(f"Embedded {len(embeddings)} documents")
```

Batching is more efficient than sending one request per document — use it whenever you are embedding more than a handful of strings.

## Computing Cosine Similarity

Cosine similarity measures how closely two embedding vectors point in the same direction. A score of `1.0` means identical meaning; `0.0` means unrelated.

```python Python theme={null}
import numpy as np

def cosine_similarity(vec_a: list[float], vec_b: list[float]) -> float:
    a = np.array(vec_a)
    b = np.array(vec_b)
    return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))

# Embed a query and a candidate document
query_embedding = get_embedding("How do I reset my password?")
doc_embedding = get_embedding("Steps to change or recover your account password")

score = cosine_similarity(query_embedding, doc_embedding)
print(f"Similarity: {score:.4f}")
# → Similarity: 0.9312
```

For production search at scale, use a dedicated vector database (such as Pinecone, Weaviate, or pgvector) rather than computing pairwise similarity in Python — these systems index vectors for approximate nearest-neighbor search across millions of entries.

## Storage and Dimensions

<Note>
  The `swytcho-embed` model produces 1,536-dimensional vectors. Each dimension is a 32-bit float (4 bytes), so a single embedding occupies roughly 6 KB. Plan your storage accordingly: one million embeddings require approximately 6 GB of raw vector storage before any index overhead. If your use case is storage-constrained, check whether your vector database supports product quantization or dimensionality reduction.
</Note>

## Chunking Long Documents

<Tip>
  Embeddings are computed on the full input text, but most embedding models have a token limit (typically 512–8,192 tokens). If you submit text that exceeds the limit, it will be silently truncated, and the resulting embedding will not represent your full document. Split long documents into overlapping chunks (e.g., 512 tokens with a 64-token overlap) before embedding, store each chunk with a reference to its source document, and embed your query at retrieval time to find the most relevant chunks.
</Tip>
