Complete the code to create a simple model abstraction using LangChain.
from langchain.llms import OpenAI llm = [1](temperature=0.7) print(llm("Say hello"))
The OpenAI class is used to create a language model instance in LangChain for text generation.
Complete the code to use model abstraction to switch between models easily.
def get_model(model_name): if model_name == "openai": return [1](temperature=0) elif model_name == "chat": return ChatOpenAI(temperature=0) model = get_model("openai") print(model("Hello!"))
Using OpenAI here allows the function to return the correct model instance based on the name, demonstrating abstraction.
Fix the error in the code by choosing the correct method to generate text from the model abstraction.
llm = OpenAI(temperature=0.5) response = llm.[1](["What is AI?"]) print(response.generations[0][0].text)
The generate method is the correct way to invoke the model instance to generate text in LangChain. It takes a list of prompts and returns an LLMResult.
Fill both blanks to create a flexible prompt and generate a response using model abstraction.
from langchain.prompts import [1] from langchain.llms import OpenAI prompt = [2](template="Say something about {topic}.") llm = OpenAI(temperature=0.3) text = prompt.format(topic="LangChain") response = llm(text) print(response)
PromptTemplate is used to create flexible prompts with placeholders, which can then be formatted with actual values.
Fill all three blanks to build a chain that uses model abstraction and prompt templates.
from langchain.chains import LLMChain from langchain.llms import [1] from langchain.prompts import [2] llm = [1](temperature=0.2) prompt = [2](template="Explain {concept} simply.") chain = LLMChain(llm=llm, prompt=prompt) result = chain.run(concept="model abstraction") print(result)
Using OpenAI for the model and PromptTemplate for the prompt creates a chain that abstracts the model and prompt logic.