Skip to main content

Why use LangChain with Alchemyst AI?

LangChain is a popular open-source framework for building context-aware AI applications in Python. It lets you chain together LLMs, retrievers, memory, and tools to create powerful, production-ready AI agents. However, LLMs alone are “forgetful”—they don’t remember previous conversations, business rules, or your proprietary data. This is where context becomes critical. Without context, AI agents give generic, disconnected answers. With context, they become knowledgeable partners that can reason, personalize, and act based on your data and workflows. (See What is AI Context? and Why you need AI Context?) Alchemyst AI’s LangChain integration solves this by providing a plug-and-play memory system that connects your LangChain agents to the context stored in Alchemyst’s memory architecture. This means your agents can:
  • Instantly access relevant documents, files, and knowledge bases.
  • Maintain both short-term and long-term memory across sessions.
  • Personalize responses and follow complex workflows using your proprietary data.
  • Avoid repetitive questions and deliver context-aware outputs.
With Alchemyst, you simply upload your data, and the memory system handles context injection for you—no need to build your own memory system. (See How Alchemyst Works)

Installation

To get started with the Alchemyst LangChain Integration, install the alchemyst-langchain package from PyPI.
The alchemyst-langchain package includes all necessary Alchemyst dependencies. You’ll also need to install your preferred LLM provider:

View on PyPI

Usage

As Memory

The AlchemystMemory class can be used like any other Memory class in LangChain. See the example below:
groupName: The group name acts like a namespace which creates a scope for context. Documents with the same group name will be grouped together for better organization and retrieval. In this implementation, we use the session_id as the group name to isolate conversations by session.
memory.py

Memory Operations

The AlchemystMemory class provides several key operations: Load Memory Variables: Automatically retrieves relevant context based on the current input
Save Context: Stores both user input and AI output after each interaction
Clear Memory: Remove all stored context for a session

Multi-User Applications

For applications with multiple users, create separate sessions for each user:
multi_user.py

Hierarchical Session Organization

For complex applications, use hierarchical naming to organize conversations:
hierarchical_sessions.py
Hierarchical Naming Best Practice: Use underscores to separate logical layers in your session_id. This makes it easier to organize, search, and manage conversations at scale. Think of it like a file path: domain_category_specific_identifier

Topic-Based Sessions

Organize conversations by topic or purpose:
topic_sessions.py

Resuming Previous Conversations

Simply reuse the same session_id to continue where you left off:
resume_conversation.py

Complete Example

Here’s a comprehensive example demonstrating the full capabilities:
complete_example.py

Key Features

Persistent Memory: Context survives app restarts and persists indefinitely
Seamless Integration: Drop-in replacement for LangChain’s built-in memory
Session Isolation: Keep different conversations separate and organized
Automatic Context Retrieval: Smart relevance-based memory loading
Multi-User Support: Easy to implement user-specific memory
Production Ready: Built on Alchemyst’s robust memory infrastructure

Configuration Options

AlchemystMemory Parameters

Memory Variables

The memory exposes the following variables:
  • history: Contains the conversation history as a string

Best Practices

1. Session ID Naming Strategy

Use meaningful, hierarchical session IDs to organize conversations at scale:
Benefits of hierarchical naming:
  • Easy to filter and search conversations
  • Clear ownership and categorization
  • Scalable for large applications

2. Memory Lifecycle Management

Decide when to clear memory based on your use case:

3. Handle API Keys Securely

Always use environment variables for API keys, never hardcode them:

4. Session ID Persistence

For resumable conversations, store session IDs in your database:

5. Error Handling

The memory system handles errors gracefully, but monitor your logs:

Performance Considerations

Conversation Length

The memory system is optimized for typical conversation lengths:
  • Optimal: 10-100 message exchanges per session
  • Good: 100-500 message exchanges
  • Consider splitting: 500+ message exchanges
For very long conversations, consider creating new sessions periodically:

Context Retrieval Speed

The memory system uses semantic search for context retrieval:
  • Typical retrieval time: 100-300ms
  • Factors affecting speed:
    • Total documents in session
    • Query complexity
    • Network latency
For time-sensitive applications, consider caching or pre-loading context.

Troubleshooting

Memory not loading

Symptom: Previous conversation context not appearing in responses Solutions:
  1. Ensure your session_id remains consistent across requests:
  2. Verify the session_id has data:

API key errors

Symptom: Authentication errors or 401 responses Solutions:
  1. Check your environment variables:
  2. Verify API key format (should start with alch_)
  3. Use a .env file for local development:

Empty context returned

Symptom: history is empty even with previous messages Explanation: This is normal for the first message in a new session. Context builds up as the conversation progresses.

Import errors

Symptom: ModuleNotFoundError: No module named 'alchemyst_langchain' Solutions:
  1. Verify installation:
  2. Reinstall the package:
  3. Check Python environment (virtual env, conda, etc.)

Session ID conflicts

Symptom: Unexpected context from other conversations Cause: Two different conversations sharing the same session_id Solution: Use unique, namespaced session IDs:

How It Works Under the Hood

Automatic Deduplication

AlchemystMemory automatically handles message deduplication using internal identifiers. You don’t need to worry about duplicate messages being stored - the system intelligently manages updates.

Context Search Algorithm

When loading memory variables, AlchemystMemory:
  1. Takes your input query
  2. Searches through the session’s conversation history
  3. Returns relevant context based on semantic similarity
  4. Formats it as a string for the LLM

Metadata Structure

Each conversation turn is stored with minimal metadata following best practices:
This lean metadata approach ensures:
  • Fast queries and retrieval
  • Minimal storage overhead
  • No metadata bloat
  • Follows the “5-field rule” from best practices

Migration from Custom Implementation

If you were previously using a custom AlchemystMemory implementation, migrating to the published package is simple: Before (custom implementation):
After (using published package):
The interface remains exactly the same, so your existing code will work without any changes!

Summary

By combining LangChain’s workflow capabilities with Alchemyst’s persistent memory, developers can build intelligent agents that:
  • Retain user context and preferences across sessions
  • Continue conversations days, weeks, or months later
  • Improve personalization over time with accumulated context
  • Scale to production with reliable, persistent storage
  • Organize conversations by user, topic, or any custom grouping
This integration makes your LLM applications more human-like and contextually aware — without losing information after every run.