Skip to main content

🎯 FewShots: The best few shots with LLMs

Python 3.8+ License: MIT

Ever wished your AI model had a better memory? Meet few-shots - the simple yet powerful library for managing and retrieving few-shot examples with style! 🧠✨

🌟 Features

  • 🎮 Easy to Use: Simple, intuitive API for managing your AI's example database
  • 🔄 Structured Output: Support for structured outputs

💡 Use Cases

  • 🤖 Enhance your chatbot with dynamic example retrieval
  • 📚 Build a self-improving knowledge base
  • 🎯 Implement context-aware few-shot learning

🛠️ Core Components

  • Shot: The fundamental unit representing an input-output pair with a unique ID (bring your own ID or let FewShots hash the inputs)
  • Embed: Converts inputs into vector embeddings for similarity search
  • Store: Manages storage and retrieval of examples
  • Client: Ties everything together with a clean, simple interface

🔧 Installation

pip install few-shots
rye add few-shots
poetry add few-shots

🚀 Quick Start

from few_shots.client import FewShots
from few_shots.embed.openai import OpenAIEmbed
from few_shots.store.memory import MemoryStore # see below for different vectorstores
from few_shots.types import Shot

from openai import OpenAI

shots = FewShots(
    embed=OpenAIEmbed(
        OpenAI().embeddings.create,
        model="...",
        **kwargs,
    ),
    store=MemoryStore()
)

# Works with strings or dictionaries (for structured inputs/outputs)
shots.add(
    inputs=str | dict,
    outputs=str | dict,
    id=str | None # For upserts, FewShots will hash the inputs by default to generate a UUID5, or, bring your own str(ID)
)

# When a user calls your app, you can use the `get` method to retrieve cached, known good examples
shot: Shot | None = shots.get(inputs=...)
if not shot:
    # Get similar examples
    knn_shots = shots.list(inputs=..., limit=10) # default = 5

    for distance, shot in knn_shots:
        print(f"Found match (distance: {distance:.2f}):")
        print(f"Q: {shot.inputs}")
        print(f"A: {shot.outputs}")

    # Use with your LLM
    from few_shots.utils.format import shots_to_messages

    response = openai.chat.completions.create(
        ...,
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            *shots_to_messages(knn_shots),
            {"role": "user", "content": "What's the recipe for pizza?"},
        ]
    )

🎮 Usage Examples

Working with Structured Output I/O

# Add structured data
shots.add(
    inputs={"type": "greeting", "language": "English"},
    outputs={"text": "Hello, world!"}
)

# Search with similar inputs
best_shots = shots.list({"type": "greeting", "language": "English"})

Using persistent Vector Stores

from few_shots.store.pg import PGStore, AsyncPGStore
from few_shots.store.chroma import ChromaStore, AsyncChromaStore
from few_shots.store.qdrant import QdrantStore, AsyncQdrantStore
from few_shots.store.weaviate import WeaviateStore, AsyncWeaviateStore
from few_shots.store.turbopuffer import TurboPufferStore, AsyncTurboPufferStore # Untested
from few_shots.store.milvus import MilvusStore, AsyncMilvusStore # Untested

# check out the store's .setup method to see how to configure it
# this method creates the table, collection, indexes, etc. and is idempotent

Using OpenAI / LiteLLM for Embeddings

The OpenAIEmbed and AsyncOpenAIEmbed classes are compatible with all OpenAI-compatible SDKs.

from few_shots import AsyncFewShots
from few_shots.embed.openai import OpenAIEmbed, AsyncOpenAIEmbed # Compatible with all OpenAI

from openai import OpenAI

shots = FewShots(
    embed=OpenAIEmbed(
        OpenAI().embeddings.create,
        model="...",
        **kwargs,
    ),
    store=MemoryStore()
)

from litellm import aembedding

shots = AsyncFewShots(
    embed=AsyncOpenAIEmbed(
        aembedding,
        model="...",
        **kwargs,
    ),
    store=MemoryStore()
)

🤝 Contributing

We love contributions! Feel free to:

  1. Fork the repository
  2. Create a feature branch
  3. Submit a pull request

📝 License

MIT License - feel free to use it in your projects!


Made with ❤️ by developers who believe in the power of learning from examples.

Remember: The best AI is the one that learns from experience! 🌟

Metadata

Release files for few-shots 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for few-shots 0.4.0
File Size Uploaded Provenance Actions
few_shots-0.4.0.tar.gz 19.6 kB Without provenance Details for few_shots-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for few-shots 0.4.0
File Interpreter ABI Platform Actions
few_shots-0.4.0-py3-none-any.whl Python 3 none any Details for few_shots-0.4.0-py3-none-any.whl

Total release size: 38.9 kB

Release files / few_shots-0.4.0.tar.gz

Download URL few_shots-0.4.0.tar.gz
Size 19.6 kB
Tags Source
SHA-256 checksum
How to use checksums
4cb2fa98093b3fdf05b415d3e8fd18f54656786acb2db028b7ab474b5959ab63
BLAKE2b-256 checksum
How to use checksums
6287d56332133a97286163794df2a9246e15e506614adea0a0b7c6d554b0a1f2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.12.2

Release files / few_shots-0.4.0-py3-none-any.whl

Download URL few_shots-0.4.0-py3-none-any.whl
Size 19.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c0e78d1aff794a7a77b53eb5a0485e4ba2380e89007945368b25231945626895
BLAKE2b-256 checksum
How to use checksums
6323d5ae34e265805fa8c64099684c4496f53586a63bde2012ddec197f46c5a7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.12.2

Security for few-shots 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page