• Stars
    star
    409
  • Rank 105,709 (Top 3 %)
  • Language
    Python
  • License
    MIT License
  • Created over 1 year ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Build robust LLM applications with true composability πŸ”—

πŸͺ½πŸ”— LiteChain

Release Notes tests docs License: MIT

LiteChain is a lighter alternative to LangChain for building LLMs application, instead of having a massive amount of features and classes, LiteChain focuses on having a single small core, that is easy to learn, easy to adapt, well documented, fully typed and truly composable.

Documentation

Quick Install

pip install litechain

πŸ”— The Chain building block

The Chain is the building block for LiteChain, an LLM is a Chain, an output parser is a Chain, a group of chains can be composed as another Chain, it's Chains all the way down.

Take a look at the documentation for guides on building on chains and building LLM applications, or go straight to the reference for the core concept and modules available.

Quick Example

Here is a ChatBot that answers anything you ask using only emojis:

from litechain.contrib import OpenAIChatChain, OpenAIChatMessage, OpenAIChatDelta
from typing import Iterable

# Creating a GPT-4 EmojiChain
emoji_chain = OpenAIChatChain[str, OpenAIChatDelta](
    "EmojiChain",
    lambda user_message: [
        OpenAIChatMessage(
            role="user", content=f"{user_message}. Reply in emojis"
        )
    ],
    model="gpt-4",
    temperature=0,
)

# Now interacting with it
async for output in emoji_chain("Hey there, how is it going?"):
    print(output.data.content, end="")

#=> πŸ‘‹πŸ˜ŠπŸ‘πŸ’»πŸŒž

async for output in emoji_chain("What is answer to the ultimate question of life, the universe, and everything?"):
    print(output.data.content, end="")

#=> 4️⃣2️⃣

In this simple example, we are creating a GPT4 Chain that takes the user message and appends ". Reply in emojis" to it for building the prompt, following the OpenAI chat structure and with zero temperature.

Then, as you can see, we have an async loop going over each token output from emoji_chain. In LiteChain, everything is an async stream using Python's AsyncGenerator class, and the most powerful part of it, is that you can connect those streams by composing two Chains together:

# Creating another Chain to translate back from emoji
translator_chain = OpenAIChatChain[Iterable[OpenAIChatDelta], OpenAIChatDelta](
    "TranslatorChain",
    lambda emoji_tokens: [
        OpenAIChatMessage(
            role="user", content=f"Translate this emoji message {[token.content for token in emoji_tokens]} to plain english"
        )
    ],
    model="gpt-4",
)

# Connecting the two Chains together
chain = emoji_chain.and_then(translator_chain)

# Trying out the whole flow
async for output in chain("Hey there, how is it going?"):
    print(output.data.content, end="")

#=> πŸ‘‹πŸ˜ŠπŸ‘πŸ’»πŸŒž"Hello, have a nice day working on your computer!"

As you can see, it's easy enough to connect two Chains together using the and_then function. There are other functions available for composition such as map, collect, join and gather, they form the small set of abstractions you need to learn to build complex Chain compositions for your application, and they behave as you would expect if you have Function Programming knowledge. You can read all about it in the reference. Once you learn those functions, any Chain will follow the same patterns, enabling you to build complex LLM applications.

As you may also have noticed, Chains accept type signatures, EmojiChain has the type [str, OpenAIChatDelta], while TranslatorChain has the type [Iterable[OpenAIChatDelta], OpenAIChatDelta], those mean respectively the input and output types of each Chain. Since the EmojiChain is taking user output, it simply takes a str as input, and since it's using OpenAI Chat API with GPT-4, it produces OpenAIChatDelta, which is the tokens that GPT-4 produces one at a time. TranslatorChain then takes Iterable[OpenAIChatDelta] as input, since it's connected with the output from EmojiChain, it takes the full list of the generated tokens to later extract their content and form its own prompt.

The type signatures are an important part of LiteChain, having them can save a lot of time preventing bugs and debugging issues caused for example when Chain B is not expecting the output of Chain A. Using an editor like VSCode with PyLance allows you to get warned that Chain A doesn't fit into Chain B before you even try to run the code, you can read about LiteChain typing here.

Last but not least, you may also have noticed that both the emojis and the translation got printed in the final output, this is by design. In LiteChain, you always have access to everything that has gone through the whole chain in the final stream, this means that debugging it is very trivial, and a debug function is available to make it even easier. A property output.final : bool is available to be checked if you want to print just the results of the final Chain, but there are also more utility functions available to help you work with output stream as you wish, check out more about it on our Why Streams? guide and the reference.

Prompts on the outside

In our experience, when working with LLM applications, the main part you must spend tunning are your prompts, which are not always portable if you switch LLMs. The content one chain produces might change a lot how another chain should be written, the prompt carry the personality and the goal of your app, doing good prompt engineering can really make it or break it.

That's why LiteChain does not hide prompts away in agents, we will give examples in the documentation, but believe you should build your own agents, to be able to customize them and their prompts later. LiteChain simply wants to facilitate and standardize the piping and connection between different parts, so you can focus on what is really important, we don't want you to spend time with LiteChain itself.

Bring your own integration

In addition, as the name implies, LiteChain wants to stay light, not embrace the world, the goal is that you really understand the Chain, making it very easy for your to add your own integration, without any additional layers in between.

In our experience, wrappers can hurt more than they help, because instead of using the library or API you want to connect directly, now you need to learn another layer of indirection, which might not accept the same parameters to work the way you expect, it gets in the way.

We do provide some integrations for OpenAI and GPT4All for example, but then we try to have a very thin layer, and to stay as close as possible to the original API, to the point that you can use the oficial documentation for it.

πŸ“– Learn more

To continue developing with LiteChain, take a look at our documentation so you can find:

  • Getting started
  • Detailed guides
  • How-to examples
  • Reference

πŸ‘₯ Community

Join our discord community to connect with other LiteChain developers, ask questions, get support, and stay updated with the latest news and announcements.

Join our Discord community

πŸš™ Roadmap

  • Add an example for document retrieval using vector search
  • Add a filter function
  • Add docs for debugging
  • Add default error handling
  • Add a simple default memory mechanism

πŸ™‹ Contributing

As a very new project in a rapidly developing field LiteChain is extremely open to contributions, we need a lot of help with integrations, documentation and guides content, feel free to send MRs and open issues. The project is very easy to run (check out the Makefile, it's all you need), but more complete contibuting guidelines to be written (we need help with that too!)

If you want to help me pay the bills and keep developing this project, you can:

Buy Me A Coffee

More Repositories

1

npm-force-resolutions

Force npm to install a specific transitive dependency version
Clojure
565
star
2

spades

Start an Elm SPA ready to the real world
Elm
302
star
3

driver

Python
117
star
4

feedless

Swift
102
star
5

elm-peer-tweet

Decentralized feeds using BitTorrent's DHT. Based on lmatteis' peer-tweet.
Elm
85
star
6

structured-elm-todomvc

Structured TodoMVC with Elm to exemplify real-world apps
72
star
7

bmo

BMO is a ChatGPT voice assistant
Python
67
star
8

remote-retrospectives

Have fun retrospectives using Google Docs
46
star
9

elm-test-bdd-style

BDD-style matchers for elm-test
Elm
37
star
10

react-decompiler

Decompile react components back into jsx format
JavaScript
28
star
11

pictureit-editor

TypeScript
26
star
12

jasmine-react-diff

Outputs nicely formated jsx when diffing two react components
JavaScript
24
star
13

NodeJS-MotionCAPTCHA

josscrowcroft's MotionCAPTCHA server-side validated with NodeJS
JavaScript
19
star
14

elm-suspense

Recreating react-suspense features using elm
Elm
15
star
15

notebooks

I'll munch some data here
Jupyter Notebook
11
star
16

rastreiounico

Rastreie qualquer coisa, pra qualquer um, com um clique, de graça, sem cadastro.
JavaScript
11
star
17

elm-todomvc-pwa

elm-todomvc with pwa features
Elm
10
star
18

unbreakablejs

JavaScript without runtime errors
Elm
9
star
19

llm-cost

NodeJS utility for counting tokens and estimating the cost of LLMs
TypeScript
7
star
20

codesearch

TypeScript
7
star
21

safe-externals-loader

Load webpack externals only if they are available globally, else require them
JavaScript
6
star
22

elm-ternary

Ternary and Null Coalescing operators for Elm
Elm
6
star
23

elm-test-example

Elm
6
star
24

Reactbox

A true responsive lightbox, when in mobile, it allows you to zoom and scroll the bigger image
JavaScript
6
star
25

rubber

Evaluate LaTeX math code
Elm
5
star
26

ml-101

Jupyter Notebook
5
star
27

unit

Universal Test Generator
Rust
5
star
28

bayes-akinator

Building Akinator with Python using BayesΒ Theorem
Python
5
star
29

simple-platform

Docker Machine + Ngninx + Prometheus + Grafana to provision on a single host
Shell
5
star
30

oltwitter

Good Ol' Twitter UI, rebuilt
Swift
4
star
31

atom-spec-finder

Shortcut for atom editor to switch between the file and its spec
CoffeeScript
3
star
32

gpt2-bot

Python
3
star
33

require-js-plugins-loader

A webpack loader to lazy load RequireJS plugins
JavaScript
3
star
34

sublime-spec-finder

Shortcut for sublime text to switch between the file and it's spec
Python
3
star
35

ptbr-datascience-crawler

Scrapes links from Pt-BR Data Science telegram group because they are too good to miss
Python
3
star
36

FOADocs

Sistema de controle de arquivos e versΓ£o para projetos acadΓͺmicos utilizando cloud storage
Ruby
3
star
37

signal-concat-map

ConcatMap for Elm Signals
JavaScript
3
star
38

mle

Elm
2
star
39

backbone-indexeddb-offline

Allows your Backbone.js app to work offline using indexeddb
2
star
40

elm-testable-css-helpers

Wraper for elm-testable of helper functions for using elm-css with elm-html
Elm
2
star
41

chatje

basic version of workchat, because the facebook one is slow as hell
Elm
2
star
42

dotfiles

Shell
2
star
43

perl-tdd-runner

Run Perl tests continuously
Perl
2
star
44

blog

my php (personal home page)
Stylus
2
star
45

astah-anycode-rails

Generate scaffolds from your astah classes
2
star
46

offline-gpt

TypeScript
2
star
47

stop-touching-your-face

Uses your camera to buzz you when you touch your face
JavaScript
2
star
48

react_editable_content

let you edit block of text or image in any page on your Rails application
JavaScript
2
star
49

matrizes-clifford

cΓ‘lculos simples de matriz para a aula do clifford
Ruby
2
star
50

memekombat

The best game that existed on facebook circa 2012
JavaScript
2
star
51

Combina--o-de-Conjuntos

Ruby
1
star
52

newgen-js-bundlers

Comparing new generation of JS bundlers
JavaScript
1
star
53

log-filter

filter repetitive logs and focus on the different ones
Perl
1
star
54

Jogo-da-Ket

Online Multiplayer Facebook Card Game in Node.JS with socket.io
JavaScript
1
star
55

hastext

Clone of a social network based on micro-blogging in Elm
Haskell
1
star
56

prepack-elm-poc

Elm
1
star
57

JavaScript-vs-CSS-animations-tests

JavaScript
1
star
58

forecaster

probability weighted weather forecasts
Jupyter Notebook
1
star
59

babel-plugin-unbreakablejs

No runtime errors for javascript!
JavaScript
1
star
60

SEO-Friendly-Single-Page-Website

Create a stylish single-page website without losing links based navigation ;)
JavaScript
1
star
61

spree_pagseguro

deprecated - nΓ£o use
Ruby
1
star
62

yyyy_mm_dd

Easy string-based date manipulation library for Python
Python
1
star
63

langchain-docs-bot

A simple docs retrieval bot, indexing markdown and jupyter notebooks, which also can have a conversation, built using langchain and vectordb, with a nice chainlit UI
Python
1
star