from langchain.llms import OpenAI from langchain.prompts import PromptTemplate from langchain.output_parsers import CommaSeparatedListOutputParser from langchain.chat_models import ChatOpenAI
# Initialize the Chat Model chat_model = ChatOpenAI(openai_api_key="YOUR_OPENAI_API_KEY")
# Initialize the parser and get instructions on how the LLM output should be formatted output_parser = CommaSeparatedListOutputParser() format_instructions = output_parser.get_format_instructions()
# Use a prompt template to get a list of items prompt = PromptTemplate( template="The user will pass in a category. Your job is to return a comma-separated list of 10 values.\n{format_instructions}\n{query}\n", input_variables=["category"], partial_variables={"format_instructions": format_instructions}, )
# Define the category to pass to the model category = "animals"
# Chain together the prompt and model, then invoke the model to get structured output prompt_and_model = prompt | chat_model output = prompt_and_model.invoke({"query": category})
# Invoke the parser to get the parsed output parsed_result = output_parser.invoke(output)
# Print the parsed result print(parsed_result)
Example 1: Basic LLM Interaction
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
from langchain.llms import OpenAI from langchain.prompts import PromptTemplate from langchain.chains import LLMChain
# Initialize the LLM llm = OpenAI(temperature=0.7)
# Create a prompt template prompt = PromptTemplate( input_variables=["topic"], template="Write a short paragraph about {topic}." )
# Create a chain that combines the LLM and the prompt chain = LLMChain(llm=llm, prompt=prompt)
# Run the chain result = chain.run(topic="artificial intelligence") print(result)
Example 2: Document Question-Answering
1 2 3 4 5 6 7 8 9 10 11 12
from langchain.document_loaders import TextLoader from langchain.indexes import VectorstoreIndexCreator