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

# Embedding Agent

> Specialized agent for generating text embeddings, batch processing, and similarity calculations.

Turn text into vectors for semantic search, similarity, and RAG with the `EmbeddingAgent`.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import EmbeddingAgent

agent = EmbeddingAgent()

embedding = agent.embed("Hello world")
print(f"Dimension: {len(embedding)}")
```

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Embedding Agent"
        User[📋 Text] --> Agent[🤖 EmbeddingAgent]
        Agent --> Model[🧠 Embedding Model]
        Model --> Result[✅ Vector]
    end

    classDef input fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef output fill:#10B981,stroke:#7C90A0,color:#fff

    class User,Agent input
    class Model process
    class Result output
```

> [!NOTE]
>
> EmbeddingAgent converts text into numerical vectors for semantic search, similarity matching, and RAG applications.

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant EmbeddingAgent
    participant Model as Embedding Model

    User->>EmbeddingAgent: embed("Hello world")
    EmbeddingAgent->>Model: Request embedding
    Model-->>EmbeddingAgent: Numerical vector
    EmbeddingAgent-->>User: List[float] (e.g. 1536 dims)
```

***

## Quick Start

**1. Install**

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
pip install praisonaiagents litellm
export OPENAI_API_KEY="your-key"
```

**2. Create Agent**

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import EmbeddingAgent

agent = EmbeddingAgent()
```

**3. Generate Embedding**

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
embedding = agent.embed("Hello world")
print(f"Dimension: {len(embedding)}")
```

***

## Methods

> [accordion] embed()
>
> Generate embedding for a single text.
>
> ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> from praisonaiagents import EmbeddingAgent
>
> agent = EmbeddingAgent()
> embedding = agent.embed("Hello world")
>
> print(f"Dimension: {len(embedding)}")
> # Output: Dimension: 1536
> ```
>
> **text** `str` *required*
>
> Text to embed
>
> **model** `str`
>
> Override model for this call
>
> **return** `List[float]`
>
> Embedding vector

> [accordion] embed\_batch()
>
> Generate embeddings for multiple texts efficiently.
>
> ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> embeddings = agent.embed_batch([
>     "First document",
>     "Second document",
>     "Third document"
> ])
>
> print(f"Generated {len(embeddings)} embeddings")
> ```
>
> **texts** `List[str]` *required*
>
> List of texts to embed
>
> > [!TIP]
> >
> > Batch embedding is more efficient than calling `embed()` multiple times.

> [accordion] similarity()
>
> Calculate cosine similarity between two texts.
>
> ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> score = agent.similarity("Hello", "Hi there")
> print(f"Similarity: {score:.2f}")
> # Output: Similarity: 0.85
> ```
>
> **text1** `str` *required*
>
> First text
>
> **text2** `str` *required*
>
> Second text
>
> **return** `float`
>
> Cosine similarity score (0.0 to 1.0)

> [accordion] find\_most\_similar()
>
> Find most similar texts to a query.
>
> ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> results = agent.find_most_similar(
>     query="What is machine learning?",
>     candidates=[
>         "ML is a subset of AI",
>         "Python is a programming language",
>         "Deep learning uses neural networks"
>     ],
>     top_k=2
> )
>
> for r in results:
>     print(f"{r['score']:.2f}: {r['text']}")
> ```
>
> **query** `str` *required*
>
> Query text
>
> **candidates** `List[str]` *required*
>
> List of candidate texts
>
> **top\_k** `int` (default: 5)
>
> Number of results to return

***

## Configuration

> [tab] Basic
>
> ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> from praisonaiagents import EmbeddingAgent
>
> agent = EmbeddingAgent(
>     name="MyEmbedder",
>     llm="text-embedding-3-large",
>     verbose=True
> )
> ```

> [tab] With Config
>
> ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> from praisonaiagents import EmbeddingAgent, EmbeddingConfig
>
> config = EmbeddingConfig(
>     dimensions=1024,
>     encoding_format="float"
> )
>
> agent = EmbeddingAgent(embedding=config)
> ```

> [tab] Dict Config
>
> ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> agent = EmbeddingAgent(
>     embedding={
>         "dimensions": 512
>     }
> )
> ```

### EmbeddingConfig Parameters

| Parameter | Type | Default | Description |
| - | - | - | - |
| `dimensions` | int | `None` | Output dimensions (model-specific) |
| `encoding_format` | str | `"float"` | Format: `float` or `base64` |
| `timeout` | int | `60` | Request timeout in seconds |

***

## Supported Models

> [card] OpenAI
>
> * `text-embedding-3-small` (default)
> * `text-embedding-3-large`
> * `text-embedding-ada-002`

> [card] Cohere
>
> * `cohere/embed-english-v3.0`
> * `cohere/embed-multilingual-v3.0`

> [card] Voyage
>
> * `voyage/voyage-3`
> * `voyage/voyage-3-lite`

> [card] Mistral
>
> * `mistral/mistral-embed`

***

## Examples

### Semantic Search

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import EmbeddingAgent

agent = EmbeddingAgent()

# Document corpus
documents = [
    "Python is a programming language",
    "Machine learning uses algorithms",
    "Neural networks are inspired by the brain",
    "Data science combines statistics and programming"
]

# Find relevant documents
results = agent.find_most_similar(
    query="How do computers learn?",
    candidates=documents,
    top_k=2
)

for r in results:
    print(f"Score: {r['score']:.3f} | {r['text']}")
```

### Document Similarity Matrix

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import EmbeddingAgent

agent = EmbeddingAgent()

docs = ["Doc A content", "Doc B content", "Doc C content"]
embeddings = agent.embed_batch(docs)

# Calculate pairwise similarities
for i, emb1 in enumerate(embeddings):
    for j, emb2 in enumerate(embeddings):
        if i < j:
            score = agent._cosine_similarity(emb1, emb2)
            print(f"Doc {i+1} vs Doc {j+1}: {score:.3f}")
```

### RAG Retrieval

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import EmbeddingAgent

agent = EmbeddingAgent(llm="text-embedding-3-large")

# Knowledge base
knowledge = [
    "The capital of France is Paris",
    "Python was created by Guido van Rossum",
    "The Earth orbits the Sun"
]

# User query
query = "Who created Python?"

# Find relevant context
results = agent.find_most_similar(query, knowledge, top_k=1)
context = results[0]["text"]

print(f"Retrieved: {context}")
# Output: Retrieved: Python was created by Guido van Rossum
```

### Async Usage

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import asyncio
from praisonaiagents import EmbeddingAgent

async def main():
    agent = EmbeddingAgent()
    
    # Async embedding
    embedding = await agent.aembed("Hello world")
    print(f"Dimension: {len(embedding)}")
    
    # Async batch
    embeddings = await agent.aembed_batch(["Text 1", "Text 2"])
    print(f"Generated: {len(embeddings)}")

asyncio.run(main())
```

***

## Use Cases

> [card] Semantic Search
>
> Find documents by meaning, not keywords

> [card] RAG
>
> Retrieve relevant context for LLM prompts

> [card] Clustering
>
> Group similar documents together

> [card] Deduplication
>
> Find and remove duplicate content

***

## Best Practices

> [accordion] Batch embeddings for throughput
>
> Use the batch method over a loop of single `embed()` calls. One batched request is far cheaper and faster than many round trips for large corpora.

> [accordion] Keep the model consistent across a corpus
>
> Vectors from different models aren't comparable. Embed queries and documents with the same model, or similarity scores become meaningless.

> [accordion] Normalise before cosine similarity
>
> Normalise vectors when your similarity metric assumes unit length. Skipping this skews rankings, especially across texts of very different lengths.

> [accordion] Pair with a vector store for RAG
>
> The agent produces vectors; a vector database stores and searches them. Combine the two to build retrieval-augmented generation pipelines.

## Related

> [card]
>
> Rewrite queries for better retrieval in RAG pipelines.
>
> [Open](https://praison.ai/docs/agents/query-rewriter.md)

> [card]
>
> Synthesise multiple sources into a report.
>
> [Open](https://praison.ai/docs/agents/research.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.