Skip to main content

Python lib created only for RAG related text based enterprise solutions

Project description

ORICHAIN

It is a custom wrapper made for RAG use cases made to be integrated with your endpoints. It caters:

  • Embedding creation

    • AWS Bedrock
      • Cohere embeddings
      • Titian embeddings
    • OpenAI Embeddings
    • Azure OpenAI Embeddings
    • Sentence Transformers
  • Knowledge base (Vector Databases)

    • Pinecone
    • ChromaDB
  • Large Language Models

    • OpenAI
    • Azure OpenAI
    • Anthropic
    • AWS Bedrock
      • Anthropic models (Series 3, 3.5, 3.7, 4)
      • LLAMA models (Series 3, 3.1, 3.2, 3.3, 4)
      • Amazon Titan text models
      • Amazon Nova series models
      • Mistral models
      • Inference Profiles

This library was built to make the applications of all the codes easy to write and review. It can be said that it was inspired by LangChain but is optimized for better performance. The entire codebase is asynchronous and threaded, eliminating the need for you to worry about optimization.

Table of Contents

Installation

🚧 The Library was rewritten in v2.0.0 released in March of 2025. There were significant changes made. Starting from version 2.0.1 (May 2025), a provider argument is now required when initializing the LLM and EmbeddingModel classes.

Just do this

pip install orichain

We have added Sentence Transformers and Lingua Language Detector as optional packages, so if you want to use them, please do one of the following:

Installation Options

1. Install with orichain:

  • For sentence-transformers:
pip install "orichain[sentence-transformers]"
  • For lingua-language-detector:
pip install "orichain[lingua-language-detector]"

2. Install directly:

  • For sentence-transformers:
pip install sentence-transformers==3.4.1
  • For lingua-language-detector:
pip install lingua-language-detector==2.1.0

Usage

A quick example of how to use Orichain:

from orichain.llm import AsyncLLM
import os
from dotenv import load_dotenv

load_dotenv()

llm = AsyncLLM(
    model_name="gpt-4o-mini", 
    provider="OpenAI",
    api_key=os.getenv("OPENAI_KEY")
)

user_message = "I am feeling sad"

system_prompt = """You need to return a JSON object with a key emotion and detect the user emotion like this:
{
    "emotion": return the detected emotion of user
}"""

llm_response = await llm(
                user_message=user_message,
                system_prompt=system_prompt,
                do_json=True # This insures that the response will be a json
            )

Features

Reasons to use Orichain:

  • Supports Both Sync and Async: Provides flexibility for different use cases.
  • Optimized Performance: Utilizes threading for efficiency, especially when used with FastAPI.
  • Hot-Swappable Components: Easily modify RAG components as project requirements evolve, ensuring high flexibility.

Documentation

Coming soon...

Example

Here is a basic example of how to use this code:

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, Response, StreamingResponse

from orichain.embeddings import AsyncEmbeddingModel
from orichain.knowledge_base import AsyncKnowledgeBase
from orichain.llm import AsyncLLM

import os
from dotenv import load_dotenv
from typing import Dict

load_dotenv()

embedding_model = AsyncEmbeddingModel(
    model_name="text-embedding-ada-002",
    provider="OpenAI",
    api_key=os.getenv("OPENAI_KEY")
)

knowledge_base_manager = AsyncKnowledgeBase(
    vector_db_type="pinecone",
    api_key=os.getenv("PINECONE_KEY"),
    index_name="<depends on your creds>", 
    namespace="<choose your desired namespace",
)

llm = AsyncLLM(
    model_name="gpt-4o-mini", 
    provider="OpenAI",
    api_key=os.getenv("OPENAI_KEY")
)

app = FastAPI(redoc_url=None, docs_url=None)

@app.post("/generative_response")
async def generate(request: Request) -> Response:
    # Fetching data from the request recevied
    request_json = await request.json()

    # Fetching valid keys
    user_message = request_json.get("user_message")
    prev_pairs = request_json.get("prev_pairs")
    metadata = request_json.get("metadata")

    # Embedding creation for retrieval
    user_message_vector = await embedding_model(user_message=user_message)

    # Checking for error while embedding generation
    if isinstance(user_message_vector, Dict):
        return JSONResponse(user_message_vector)

    # Fetching relevant data chunks from knowledgebase
    retrived_chunks = await knowledge_base_manager(
        user_message_vector=user_message_vector,
        num_of_chunks=5,
    )

    # Checking for error while fetching relevant data chunks
    if isinstance(retrived_chunks, Dict) and "error" in retrived_chunks:
        return JSONResponse(user_message_vector)

    matched_sentence = convert_to_text_list(retrived_chunks) # Create a funtion that converts your data into a list of relevant information

    system_prompt = f"""As a helpful, engaging and friendly chatbot, you will answer the user's query based on the following information provided: 
    <data>
    {"\n\n".join(matched_sentence)}
    </data>"""

    # Streaming
    if metadata.get("stream"):
        return StreamingResponse(
            llm.stream(
                request=request,
                user_message=user_message,
                matched_sentence=matched_sentence,
                system_prompt=system_prompt,
                chat_hist=prev_pairs
            ),
            headers={
                "Content-Type": "text/event-stream",
                "Cache-Control": "no-cache",
                "X-Accel-Buffering": "no",
            },
            media_type="text/event-stream",
        )
    # Non streaming
    else:
        llm_response = await llm(
            request=request,
            user_message=user_message,
            matched_sentence=matched_sentence,
            system_prompt=system_prompt,
            chat_hist=prev_pairs
        )

        return JSONResponse(llm_response)

Roadmap

Here's our plan for upcoming features and improvements:

Short-term goals

  • Do testing of the latest version
  • Release stable 1.0.0 version
  • Create Documentation
  • Write class and function definitions

Long-term goals

  • Publish it to pypi
  • Refactor the code for better readability

Contributing

We welcome contributions to help us achieve these goals!

Steps

  1. Stage all changes
git add .
  1. Commit the changes
git commit -m "Release vX.X.X"
  1. Create a new tag
git tag vX.X.X
  1. Push commits to main branch
git push origin main
  1. Push the new tag
git push origin vX.X.X

Deleting Tags:

  • Delete a Local Tag
git tag -d vX.X.X
  • Delete a Remote Tag
git push origin --delete vX.X.X

License

Apache 2.0

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

orichain-2.1.1.tar.gz (31.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

orichain-2.1.1-py3-none-any.whl (50.3 kB view details)

Uploaded Python 3

File details

Details for the file orichain-2.1.1.tar.gz.

File metadata

  • Download URL: orichain-2.1.1.tar.gz
  • Upload date:
  • Size: 31.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for orichain-2.1.1.tar.gz
Algorithm Hash digest
SHA256 eaf6639e769ec631cc73db316f7c6dcd0e504ff260e02fca54165c42a19824cc
MD5 61689c1c401026ee96802d38517c4fc5
BLAKE2b-256 eed4c213452a02fc235b331e7942a9700f523b6eead27484a90903ea0cb75a90

See more details on using hashes here.

Provenance

The following attestation bundles were made for orichain-2.1.1.tar.gz:

Publisher: publish.yml on OriserveAI/orichain

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file orichain-2.1.1-py3-none-any.whl.

File metadata

  • Download URL: orichain-2.1.1-py3-none-any.whl
  • Upload date:
  • Size: 50.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for orichain-2.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 e29f95d0d236092e2f4d132b3e8fd6d4f4ee47e17926c9a7421031d20e0e242e
MD5 04f25e48e584646d695f8010651b61b0
BLAKE2b-256 0b10d1ed9f5638486e62a3c8f93edd5370fc1232ecd56c26be9d1691852fc9dd

See more details on using hashes here.

Provenance

The following attestation bundles were made for orichain-2.1.1-py3-none-any.whl:

Publisher: publish.yml on OriserveAI/orichain

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page