LangChain LLM Examples¶
LangChain is a framework that provides, among others, a set of Python APIs to ease the use of Large Language Models.
This notebook shows a few basic examples to get started, see https://python.langchain.com/en/latest/
OpenAI example¶
OpenAI provides a state of the art LLM, via an API. The model inference is perfomed on OpenAI platform. You need to register to get an API key. There is a limited amount of compute that can be done for free, see also pricing: https://openai.com/pricing
from langchain.llms import OpenAI
import os
from getpass import getpass
OPENAI_API_KEY = getpass()
# Get an OpenAI API Key from https://platform.openai.com/
os.environ['OPENAI_API_KEY'] = OPENAI_API_KEY
# This will use OpenAI models, the specified model, see also https://openai.com/pricing
model = "gpt-3.5-turbo-instruct"
llm=OpenAI(model=model)
llm.json()
from langchain import PromptTemplate, LLMChain
template = """Question: {question}
Answer: Let's think step by step."""
prompt = PromptTemplate(template=template, input_variables=["question"])
llm_chain = LLMChain(prompt=prompt, llm=llm)
question = "How to cook rice?"
print(llm_chain.run(question))
Open access models, download and run on local GPU¶
There is a variety of models available for open access. However they currently do not perfom as well as the commercial ones and require machine with powerful GPUs to run the more advanced model.
Here we just provide some basic example of small models that can fit on a T4.
Note download the models from the web and uploading the weights into the GPU can take a few minutes.
import torch
from transformers import pipeline
from langchain.llms import HuggingFacePipeline
from langchain import PromptTemplate, LLMChain
# model = "EleutherAI/pythia-2.8b"
model = "databricks/dolly-v2-3b" # Or try another model
pipe = pipeline(
model=model,
torch_dtype=torch.bfloat16,
trust_remote_code=True,
device=0,
max_length=200,
)
llm = HuggingFacePipeline(pipeline=pipe)
template = """Question: {question}
Answer: Let's think step by step."""
prompt = PromptTemplate(template=template, input_variables=["question"])
llm_chain = LLMChain(prompt=prompt, llm=llm, verbose=True, memory=None)
question = "How to cook rice?"
print(llm_chain.run(question))