pyvespa Python API

repository·master·Indexed 41 days ago

https://github.com/vespa-engine/pyvespa

A Pythonic interface for the Vespa search engine that allows developers to programmatically define, deploy, and manage Vespa applications and queries. It features a Vespa Tag (VT) system for expressing XML configurations in Python, support for ApplicationPackage generation, and tools for tuning ANN parameters via VespaNNParameterOptimizer. The library also includes a Python wrapper for the Vespa CLI and utilities for deploying to local Docker containers or Vespa Cloud.

Tokens
68.3K
Snippets
178
Records
206
Agent score
49%

What's inside pyvespa

  1. Overview of pyvespa features

    master

    pyvespa aims for > 95% feature parity with Vespa and supports the following core capabilities:

    • Application Management: Create and deploy application packages including schemas, rank profiles, services.xml, and query profiles.
    • Custom Extensions: Ship custom Java bundles (searchers, document processors, request handlers) using ApplicationPackage(include_files=...).
    • Data Operations: Feed and retrieve documents using the /document/v1/ API.
    • Querying: Query applications using the /search/ API or build complex queries using the QueryBuilder DSL API.
    • Machine Learning & Evaluation:
      • Collect training data for ML using VespaFeatureCollector.
      • Evaluate applications using VespaEvaluator or VespaMatchEvaluator.
  2. Overview of pyvespa

    master

    pyvespa is a Python API for Vespa, a scalable open-source serving engine for storing, computing, and ranking big data at user serving time.

    Using pyvespa, developers can:

    • Create Vespa applications
    • Modify existing applications
    • Deploy applications to Vespa instances
    • Interact with running Vespa instances

    The library is designed to facilitate faster prototyping and easier exploration of Vespa features.

  3. Configure two-phase ranking for ColPali

    master

    To scale ColPali retrieval, use a two-phase ranking approach in your RankProfile:

    1. First Phase: Use a fast metric like bm25 (for text) or an approximate MaxSim using inverted Hamming distance (for binary embeddings) to narrow down candidates.
    2. Second Phase: Perform the full MaxSim operation using float representations of the embeddings to re-rank the top-k results.

    Vespa's unpack_bits function is used to convert compressed binary vectors back to float for the second phase.

    from vespa.package import RankProfile, Function, FirstPhaseRanking, SecondPhaseRanking
    
    colpali_profile = RankProfile(
        name="default",
        inputs=[("query(qt)", "tensor<float>(querytoken{}, v[128])")],
        functions=[
            Function(
                name="max_sim",
                expression="""
                    sum(
                        reduce(
                            sum(
                                query(qt) * unpack_bits(attribute(embedding)) , v
                            ),
                            max, patch
                        ),
                        querytoken
                    )
                """,
            ),
            Function(name="bm25_score", expression="bm25(title) + bm25(text)"),
        ],
        first_phase=FirstPhaseRanking(expression="bm25_score"),
        second_phase=SecondPhaseRanking(expression="max_sim", rerank_count=100),
    )
    colpali_schema.add_rank_profile(colpali_profile)
  4. Understand the pyvespa Control-plane and Data-plane APIs

    master

    pyvespa provides two distinct interfaces to interact with Vespa, which require different authentication methods:

    1. Control-plane API

    Used for deploying and managing Vespa applications (schemas, rank profiles, services.xml, etc.).

    • VespaCloud: Interface for managing applications on Vespa Cloud.
    • VespaDocker: Interface for managing applications on a local Vespa instance running via Docker or Podman.

    2. Data-plane API

    Used for interacting with the data within your deployed applications.

    • Vespa: Interface used to feed and query data (via /document/v1/ and /search/ APIs).
  5. Tune ANN parameters with VespaNNParameterOptimizer

    master

    When performing Approximate Nearest Neighbor (ANN) search in Vespa that combines vector similarity with metadata filtering, you can optimize performance using the VespaNNParameterOptimizer class from the vespa.evaluation module.

    This optimizer analyzes a sample of queries to determine the best values for parameters that control how Vespa handles the interaction between ANN and filtering. It performs measurements and returns a report containing suggestions for the following parameters:

    • ranking.matching.approximateThreshold
    • ranking.matching.filterFirstThreshold
    • ranking.matching.filterFirstExploration
    • ranking.matching.postFilterThreshold

    To use it, provide your Vespa application instance, a list of queries, and the number of target hits used in those queries.

    from vespa.evaluation import VespaNNParameterOptimizer
    
    optimizer = VespaNNParameterOptimizer(
        app=my_vespa_app,
        queries=my_list_of_queries,
        hits=number_of_target_hits_used_in_my_queries,
    )
    report = optimizer.run()
    
    suggested_parameters = {
        "ranking.matching.approximateThreshold": report["approximateThreshold"]["suggestion"],
        "ranking.matching.filterFirstThreshold": report["filterFirstThreshold"]["suggestion"],
        "ranking.matching.filterFirstExploration": report["filterFirstExploration"]["suggestion"],
        "ranking.matching.postFilterThreshold": report["postFilterThreshold"]["suggestion"],
    }
  6. Run pyvespa notebooks in Jupyter

    master

    To run the provided documentation notebooks in a browser, install Jupyter Notebook and clone the repository to access the source files. Navigate to the notebook directory to start the server.

    Note: Many guides and notebooks use Docker. Ensure your system meets the minimum memory requirement of 4 GB.

    $ git clone --depth 1 https://github.com/vespa-engine/pyvespa.git
    $ jupyter notebook --notebook-dir pyvespa/docs/sphinx/source
  7. Keep Vespa and pyvespa versions synchronized

    master

    Both Vespa and pyvespa APIs change regularly. To avoid compatibility issues, ensure you are using the latest versions:

    1. Update your Vespa Docker image:
      docker pull vespaengine/vespa
    2. Reinstall/update pyvespa.

    You can check your current pyvespa version using:

    python3 -m pip show pyvespa
    docker pull vespaengine/vespa
    python3 -m pip show pyvespa
  8. Instruct your AI assistant to use pyvespa documentation

    master

    To improve the accuracy of AI coding assistants (like Claude Code, GitHub Copilot, or Cursor) when working with pyvespa, provide them with specific instructions to fetch Markdown versions of the documentation instead of scraping HTML. This ensures the LLM receives clean, structured text optimized for consumption.

    Add the following block to your project's instruction files (e.g., CLAUDE.md, AGENTS.md, .cursorrules, or .github/copilot-instructions.md):

    ## pyvespa
    
    When looking up pyvespa documentation, prefer fetching the Markdown versions
    instead of scraping HTML pages:
    
    - Documentation index: https://vespa-engine.github.io/pyvespa/llms.txt
    - Full documentation: https://vespa-engine.github.io/pyvespa/llms-full.txt
    - Per-page markdown: replace `.html` with `.md.txt` in any docs URL
    
    Examples:
    - https://vespa-engine.github.io/pyvespa/reads-writes.md.txt
    - https://vespa-engine.github.io/pyvespa/api/vespa/application.md.txt
  9. Deploy Nanobeir Hybrid Evaluation to Hugging Face Spaces

    master

    To deploy the Nanobeir Hybrid Evaluation to a Hugging Face Space while ensuring only the necessary files (index.html, NanoBEIR/models.js, and README.md) are uploaded, run the following commands from the directory containing the README. This prevents unnecessary files from being included in the Space.

    hf upload vespa-engine/nanobeir-hybrid-evaluation index.html index.html --repo-type space 
    hf upload vespa-engine/nanobeir-hybrid-evaluation NanoBEIR/models.js NanoBEIR/models.js --repo-type space
    hf upload vespa-engine/nanobeir-hybrid-evaluation README.md README.md --repo-type space