1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| from langchain.llms import OpenAI from langchain.prompts.example_selector import SemanticSimilarityExampleSelector from langchain.output_parsers import ResponseSchema, StructuredOutputParser from langchain.embeddings import OpenAIEmbeddings from langchain.vectorstores import FAISS from langchain.prompts import FewShotPromptTemplate, PromptTemplate
openai_api_key = "{{you_openai_api_key}}" llm: OpenAI = OpenAI( openai_proxy="127.0.0.1:4780", openai_api_key=openai_api_key)
response_schemas = [ ResponseSchema(name="user_input", description="这是用户的输入"), ResponseSchema(name="date", description="这是通过用户的输入得到的时间") ]
outputParser = StructuredOutputParser.from_response_schemas(response_schemas)
template = """
示例输入: {user_input} 示例输出: {output} """
example_prompt = PromptTemplate( template=template, input_variables=["user_input", "output"], )
examples = [ {"user_input": "今天是2023-08-01,今天吃米饭用了10元", "output": """date:2023-08-01,amount:10, user_input:昨天早上吃米饭用了10元"""}, {"user_input": "今天是2023-08-02,昨天早上吃米饭用了10.1元", "output": """date:2023-08-01,amount:10.1, user_input:昨天早上吃米饭用了10元"""}, {"user_input": "今天是2023-08-03,前天早上吃米饭用了11元", "output": """date:2023-08-01, amount:11, user_input:前天早上吃米饭用了11元"""}, ]
example_selector = SemanticSimilarityExampleSelector.from_examples( examples=examples, embeddings=OpenAIEmbeddings(openai_api_key=openai_api_key), vectorstore_cls=FAISS, k=3 )
similar_prompt = FewShotPromptTemplate( example_selector=example_selector, example_prompt=example_prompt, prefix="您将从用户那得到一段文字, 解析相关内容并且返回相关的内容", suffix="用户输入:{user_input}\n解析结果:", input_variables=["user_input"], )
print(similar_prompt.format(user_input="今天是2023-08-03,今天吃米饭用了10元"))
print(llm(similar_prompt.format(user_input="今天是2023-08-01,前天吃米饭用了3.3元")))
|