|
1 | 1 | from langchain.chat_models import ChatOpenAI |
2 | | -from langchain.prompts.chat import ( |
3 | | - ChatPromptTemplate, |
4 | | - SystemMessagePromptTemplate, |
5 | | - HumanMessagePromptTemplate, |
6 | | -) |
7 | | -from langchain.chains import LLMChain |
8 | | -from langchain.schema import BaseOutputParser |
9 | | - |
10 | | -# my first langchain |
11 | | -chat_model = ChatOpenAI() |
12 | | -print(chat_model.predict("hi!")) |
13 | | - |
14 | | - |
15 | | -# create templates |
16 | | -system_template = """You are a helpful assistant who generates comma separated lists. |
17 | | -A user will pass in a category, and you should generated 5 objects in that category in a comma separated list. |
18 | | -ONLY return a comma separated list, and nothing more.""" |
19 | | -system_message_prompt = SystemMessagePromptTemplate.from_template(system_template) |
20 | | - |
21 | | -human_template = "{text}" |
22 | | -human_message_prompt = HumanMessagePromptTemplate.from_template(human_template) |
23 | | - |
24 | | -# create full prompt |
25 | | -chat_prompt = ChatPromptTemplate.from_messages( |
26 | | - [system_message_prompt, human_message_prompt]) |
27 | | - |
28 | | -# process output |
29 | | -class CommaSeparatedListOutputParser(BaseOutputParser): |
30 | | - """Parse the output of an LLM call to a comma-separated list.""" |
31 | | - |
32 | | - def parse(self, text: str): |
33 | | - """Parse the output of an LLM call.""" |
34 | | - return text.strip().split(", ") |
35 | | - |
36 | | -# build a chain |
37 | | -chain = LLMChain( |
38 | | - llm=ChatOpenAI(), |
39 | | - prompt=chat_prompt, |
40 | | - output_parser=CommaSeparatedListOutputParser() |
41 | | -) |
42 | | -print(chain.run("colors")) |
0 commit comments