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
from praisonaiagents import EmbeddingAgent

agent = EmbeddingAgent()

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

Embedding Agent

📋 Text

🤖 EmbeddingAgent

🧠 Embedding Model

✅ Vector

How It Works

Diagram
Embedding ModelEmbeddingAgentUserEmbedding ModelEmbeddingAgentUserembed(“Hello world”)Request embeddingNumerical vectorList[float] (e.g. 1536 dims)

Quick Start

  1. Install
    bash
    pip install praisonaiagents litellm
    export OPENAI_API_KEY="your-key"
  2. Create Agent
    python
    from praisonaiagents import EmbeddingAgent
    
    agent = EmbeddingAgent()
  3. Generate Embedding
    python
    embedding = agent.embed("Hello world")
    print(f"Dimension: {len(embedding)}")

Methods

embed()

Generate embedding for a single text.

python
from praisonaiagents import EmbeddingAgent

agent = EmbeddingAgent()
embedding = agent.embed("Hello world")

print(f"Dimension: {len(embedding)}")
# Output: Dimension: 1536
text str

Text to embed

model str

Override model for this call

ResponseField List[float]

Embedding vector

embed_batch()

Generate embeddings for multiple texts efficiently.

python
embeddings = agent.embed_batch([
    "First document",
    "Second document",
    "Third document"
])

print(f"Generated {len(embeddings)} embeddings")
texts List[str]

List of texts to embed

similarity()

Calculate cosine similarity between two texts.

python
score = agent.similarity("Hello", "Hi there")
print(f"Similarity: {score:.2f}")
# Output: Similarity: 0.85
text1 str

First text

text2 str

Second text

ResponseField float

Cosine similarity score (0.0 to 1.0)

find_most_similar()

Find most similar texts to a query.

python
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

Query text

candidates List[str]

List of candidate texts

top_k int

Number of results to return


Configuration

Basic

python
from praisonaiagents import EmbeddingAgent

agent = EmbeddingAgent(
    name="MyEmbedder",
    llm="text-embedding-3-large",
    verbose=True
)

With Config

python
from praisonaiagents import EmbeddingAgent, EmbeddingConfig

config = EmbeddingConfig(
    dimensions=1024,
    encoding_format="float"
)

agent = EmbeddingAgent(embedding=config)

Dict Config

python
agent = EmbeddingAgent(
    embedding={
        "dimensions": 512
    }
)

EmbeddingConfig Parameters

ParameterTypeDefaultDescription
dimensionsintNoneOutput dimensions (model-specific)
encoding_formatstr"float"Format: float or base64
timeoutint60Request timeout in seconds

Supported Models


Examples

Semantic Search

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


Best Practices

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.

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.

Normalise before cosine similarity

Normalise vectors when your similarity metric assumes unit length. Skipping this skews rankings, especially across texts of very different lengths.

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