Skip to main content

🔍 ctx-miner

🚀 A Python library for context-aware conversational AI using graph databases. Built on top of Graphiti Core, ctx-miner provides an easy-to-use interface for storing, retrieving, and analyzing conversational context using graph-based knowledge representation.

✨ Features

  • 🕸️ Graph-based Context Storage: Store conversations as interconnected knowledge graphs
  • 🔎 Semantic Search: Find relevant context using hybrid search (semantic + BM25)
  • 🤖 Multiple LLM Support: Configurable LLM providers (OpenAI, etc.)
  • 🧮 Flexible Embedding Models: Support for various embedding providers
  • 🗄️ FalkorDB Integration: Redis-based graph database backend
  • ⚡ Async/Await Support: Built for high-performance async applications
  • 🔒 Type Safety: Full type hints and Pydantic models

📦 Installation

uv add ctx-miner

🐍 Using pip

pip install ctx-miner

💻 Development Installation

git clone https://github.com/hienhayho/ctx-miner.git
cd ctx-miner
uv sync

🚀 Quick Start

1. 🔐 Environment Setup

Run falkor-db with docker:

docker run \
    -it -d \
    --restart always \
    -p 6379:6379 \
    -p 3000:3000 \
    --name falkordb \
    falkordb/falkordb:latest

Create a .env file with your configuration:

OPENAI_API_KEY=your_openai_api_key
FALKORDB_HOST=localhost
FALKORDB_PORT=6379
FALKORDB_USERNAME=
FALKORDB_PASSWORD=

2. 💡 Quick Usage

import asyncio
from ctx_miner import CtxMiner
from ctx_miner.core.schemas import CtxMinerEpisode, CtxMinerMessage
from ctx_miner.utils.helpers import load_config

async def main():
    # Configure the library
    config = load_config(group_id="demo_conversation", auto_build_indices=True)
    
    # Initialize CtxMiner
    miner = CtxMiner(config=config)
    
    try:
        await miner.initialize()
        # Create a conversation episode
        episode = CtxMinerEpisode(
            messages=[
                CtxMinerMessage(role="user", content="Hello! I need help with my internet plan."),
                CtxMinerMessage(role="assistant", content="Hi! I'd be happy to help you with your internet plan. What specific questions do you have?"),
                CtxMinerMessage(role="user", content="What's the fastest speed you offer?"),
                CtxMinerMessage(role="assistant", content="Our fastest plan is Super200 with 200 Mbps download speed.")
            ]
        )
        
        # Add episode to the knowledge graph
        episode_uuid = await miner.add_episode(episode)
        print(f"Added episode: {episode_uuid}")
        
        # Search for relevant context
        results = await miner.search_context(
            query="internet speed plans",
            limit=5
        )
        
        print(f"Found {len(results)} relevant contexts:")
        for result in results:
            print(f"- {result['fact']}")
        
        # Get statistics
        stats = await miner.get_stats()
        print(f"Database contains {stats['episode_count']} episodes")
        
    finally:
        await miner.close()

if __name__ == "__main__":
    asyncio.run(main())

⚙️ Configuration

🎛️ CtxMinerConfig

The main configuration object that combines all settings:

from ctx_miner.core.schemas import CtxMinerConfig, FalkorDBConfig, CtxMinerLLMConfig, EmbeddingConfig

config = CtxMinerConfig(
    falkordb_config=FalkorDBConfig(
        host="localhost",
        port=6379,
        database="my_app",
        username="",  # Optional
        password=""   # Optional
    ),
    llm_config=CtxMinerLLMConfig(
        provider="openai",
        model="gpt-4o-mini",
        temperature=0.0,
        max_tokens=8192
    ),
    embedding_config=EmbeddingConfig(
        provider="openai",
        model="text-embedding-3-small",
        dimensions=1536
    ),
    group_id="default",           # Logical grouping for conversations
    auto_build_indices=True       # Automatically create database indices
)

🌍 Environment Variables

Variable Description Default
OPENAI_API_KEY OpenAI API key Required
FALKORDB_HOST FalkorDB host localhost
FALKORDB_PORT FalkorDB port 6379
FALKORDB_USERNAME FalkorDB username (empty)
FALKORDB_PASSWORD FalkorDB password (empty)

📚 Core Concepts

📝 Episodes

Episodes are the fundamental units of conversation stored in the graph. Each episode contains a sequence of messages and gets processed to extract entities and relationships.

from ctx_miner.core.schemas import CtxMinerEpisode, CtxMinerMessage

episode = CtxMinerEpisode(
    messages=[
        CtxMinerMessage(role="user", content="What are your business hours?"),
        CtxMinerMessage(role="assistant", content="We're open Monday-Friday, 9 AM to 6 PM EST.")
    ]
)

🔍 Search and Retrieval

ctx-miner provides multiple search methods:

  1. Context Search: Find relevant facts and relationships
  2. Node Search: Search for specific entities
  3. Graph-based Reranking: Use graph distance for improved relevance
# Basic context search
results = await miner.search_context("business hours", limit=10)

# Search with center node reranking
results = await miner.search_context(
    query="customer support",
    center_node_uuid="some-node-uuid",
    limit=5
)

# Direct node search
nodes = await miner.search_nodes("customer", limit=5)

🎯 Advanced Usage

📦 Batch Processing

# Add multiple episodes efficiently
episodes = [
    CtxMinerEpisode(messages=[...]),
    CtxMinerEpisode(messages=[...]),
    # ... more episodes
]

uuids = await miner.add_episodes(episodes)
print(f"Added {len(uuids)} episodes")

🗂️ Episode Management

# List episodes
episodes = await miner.list_episodes(limit=50, offset=0)

# Get specific episode
episode_data = await miner.get_episode(episode_uuid)

# Delete episode
success = await miner.delete_episode(episode_uuid)

# Clear all episodes in group
await miner.clear_all()

🔧 Custom Search Configuration

from graphiti_core.search.search_config_recipes import NODE_HYBRID_SEARCH_RRF

# Use custom search configuration
custom_config = NODE_HYBRID_SEARCH_RRF.model_copy(deep=True)
custom_config.limit = 20

results = await miner.search_nodes(
    query="customer preferences",
    search_config=custom_config
)

📋 Requirements

  • 🐍 Python 3.8+
  • 🗄️ FalkorDB instance (Redis with graph capabilities)
  • 🔑 OpenAI API key (or other supported LLM provider)

📚 Dependencies

  • 🕸️ graphiti-core[falkordb]: Graph-based knowledge management
  • 📝 loguru: Structured logging
  • ✅ pydantic: Data validation and serialization
  • 📊 tqdm: Progress bars for batch operations
  • 🔐 python-dotenv: Environment variable management

📄 License

[Add your license information here]

🤝 Contributing

[Add contribution guidelines here]

💬 Support

For issues and questions:

Metadata

Release files for ctx-miner 0.1.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 ctx-miner 0.1.0
File Size Uploaded Provenance Actions
ctx_miner-0.1.0.tar.gz 58.1 kB Without provenance Details for ctx_miner-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ctx-miner 0.1.0
File Interpreter ABI Platform Actions
ctx_miner-0.1.0-py3-none-any.whl Python 3 none any Details for ctx_miner-0.1.0-py3-none-any.whl

Total release size: 73.9 kB

Release files / ctx_miner-0.1.0.tar.gz

Download URL ctx_miner-0.1.0.tar.gz
Size 58.1 kB
Tags Source
SHA-256 checksum
How to use checksums
656be90e17a565d0faa372d87adac8783e9000cf2572363fc2dc3a8becf41ac3
BLAKE2b-256 checksum
How to use checksums
1a677ee5e793abf15e00ad77e96ac6f11ef8760048e7cebc7deacca8ac8ee2b4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.6.10

Release files / ctx_miner-0.1.0-py3-none-any.whl

Download URL ctx_miner-0.1.0-py3-none-any.whl
Size 15.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b31a4feabe1aa9035ea2a89fe650f7c2c5330b64152fa5fd3bd3f246793d7ff6
BLAKE2b-256 checksum
How to use checksums
1ba70632482ed9ebf7f19645d96e98d28604b6b01f43ba96081773daec5a3de9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.6.10

Security for ctx-miner 0.1.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.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

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