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 default model currently is text-davinci-003
llm=OpenAI(temperature=0)
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.
# Wrap a model downloaded from HuggingFace with the LangChain API
import torch
from transformers import pipeline
from langchain.llms import HuggingFacePipeline
pipe = pipeline(model="databricks/dolly-v2-3b", torch_dtype=torch.bfloat16, trust_remote_code=True, device=0)
llm = HuggingFacePipeline(pipeline=pipe)
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))