> ## 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
```

<Info>
  EmbeddingAgent converts text into numerical vectors for semantic search, similarity matching, and RAG applications.
</Info>

## 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

<Steps>
  <Step title="Install">
    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    pip install praisonaiagents litellm
    export OPENAI_API_KEY="your-key"
    ```
  </Step>

  <Step title="Create Agent">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import EmbeddingAgent

    agent = EmbeddingAgent()
    ```
  </Step>

  <Step title="Generate Embedding">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    embedding = agent.embed("Hello world")
    print(f"Dimension: {len(embedding)}")
    ```
  </Step>
</Steps>

***

## Methods

<AccordionGroup>
  <Accordion title="embed()" icon="cube">
    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
    ```

    <ParamField path="text" type="str" required>
      Text to embed
    </ParamField>

    <ParamField path="model" type="str">
      Override model for this call
    </ParamField>

    <ResponseField name="return" type="List[float]">
      Embedding vector
    </ResponseField>
  </Accordion>

  <Accordion title="embed_batch()" icon="layer-group">
    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")
    ```

    <ParamField path="texts" type="List[str]" required>
      List of texts to embed
    </ParamField>

    <Tip>Batch embedding is more efficient than calling `embed()` multiple times.</Tip>
  </Accordion>

  <Accordion title="similarity()" icon="equals">
    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
    ```

    <ParamField path="text1" type="str" required>
      First text
    </ParamField>

    <ParamField path="text2" type="str" required>
      Second text
    </ParamField>

    <ResponseField name="return" type="float">
      Cosine similarity score (0.0 to 1.0)
    </ResponseField>
  </Accordion>

  <Accordion title="find_most_similar()" icon="ranking-star">
    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']}")
    ```

    <ParamField path="query" type="str" required>
      Query text
    </ParamField>

    <ParamField path="candidates" type="List[str]" required>
      List of candidate texts
    </ParamField>

    <ParamField path="top_k" type="int" default="5">
      Number of results to return
    </ParamField>
  </Accordion>
</AccordionGroup>

***

## Configuration

<Tabs>
  <Tab title="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>

  <Tab title="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>

  <Tab title="Dict Config">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    agent = EmbeddingAgent(
        embedding={
            "dimensions": 512
        }
    )
    ```
  </Tab>
</Tabs>

### 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

<CardGroup cols={2}>
  <Card title="OpenAI" icon="robot">
    * `text-embedding-3-small` (default)
    * `text-embedding-3-large`
    * `text-embedding-ada-002`
  </Card>

  <Card title="Cohere" icon="c">
    * `cohere/embed-english-v3.0`
    * `cohere/embed-multilingual-v3.0`
  </Card>

  <Card title="Voyage" icon="ship">
    * `voyage/voyage-3`
    * `voyage/voyage-3-lite`
  </Card>

  <Card title="Mistral" icon="m">
    * `mistral/mistral-embed`
  </Card>
</CardGroup>

***

## 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

<CardGroup cols={2}>
  <Card title="Semantic Search" icon="magnifying-glass">
    Find documents by meaning, not keywords
  </Card>

  <Card title="RAG" icon="database">
    Retrieve relevant context for LLM prompts
  </Card>

  <Card title="Clustering" icon="object-group">
    Group similar documents together
  </Card>

  <Card title="Deduplication" icon="clone">
    Find and remove duplicate content
  </Card>
</CardGroup>

***

## Best Practices

<AccordionGroup>
  <Accordion title="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>

  <Accordion title="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>

  <Accordion title="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>

  <Accordion title="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.
  </Accordion>
</AccordionGroup>

## Related

<CardGroup cols={2}>
  <Card icon="wand-magic-sparkles" href="/docs/agents/query-rewriter">
    Rewrite queries for better retrieval in RAG pipelines.
  </Card>

  <Card icon="magnifying-glass-chart" href="/docs/agents/research">
    Synthesise multiple sources into a report.
  </Card>
</CardGroup>
