improve documentation on how to pass in custom prompts (#561)

This commit is contained in:
Harrison Chase
2023-01-08 19:20:13 -08:00
committed by GitHub
parent 1511606799
commit b06a2a6191
5 changed files with 807 additions and 21 deletions

View File

@@ -21,7 +21,7 @@
},
{
"cell_type": "code",
"execution_count": 11,
"execution_count": 1,
"id": "17fcbc0f",
"metadata": {},
"outputs": [],
@@ -29,12 +29,13 @@
"from langchain.embeddings.openai import OpenAIEmbeddings\n",
"from langchain.text_splitter import CharacterTextSplitter\n",
"from langchain.vectorstores.faiss import FAISS\n",
"from langchain.docstore.document import Document"
"from langchain.docstore.document import Document\n",
"from langchain.prompts import PromptTemplate"
]
},
{
"cell_type": "code",
"execution_count": 12,
"execution_count": 2,
"id": "291f0117",
"metadata": {},
"outputs": [],
@@ -49,7 +50,7 @@
},
{
"cell_type": "code",
"execution_count": 13,
"execution_count": 3,
"id": "fd9666a9",
"metadata": {},
"outputs": [],
@@ -59,7 +60,7 @@
},
{
"cell_type": "code",
"execution_count": 14,
"execution_count": 4,
"id": "d1eaf6e6",
"metadata": {},
"outputs": [],
@@ -70,7 +71,7 @@
},
{
"cell_type": "code",
"execution_count": 15,
"execution_count": 5,
"id": "a16e3453",
"metadata": {},
"outputs": [],
@@ -79,6 +80,46 @@
"from langchain.llms import OpenAI"
]
},
{
"cell_type": "markdown",
"id": "2f64b7f8",
"metadata": {},
"source": [
"## Quickstart\n",
"If you just want to get started as quickly as possible, this is the recommended way to do it:"
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "fd9e6190",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"' The president said that he was honoring Justice Breyer for his service to the country and that he was a Constitutional scholar, Army veteran, and retiring Justice of the United States Supreme Court.'"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"stuff\")\n",
"query = \"What did the president say about Justice Breyer\"\n",
"chain.run(input_documents=docs, question=query)"
]
},
{
"cell_type": "markdown",
"id": "eea01309",
"metadata": {},
"source": [
"If you want more control and understanding over what is happening, please see the information below."
]
},
{
"cell_type": "markdown",
"id": "f78787a0",
@@ -121,6 +162,47 @@
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
{
"cell_type": "markdown",
"id": "84794d4c",
"metadata": {},
"source": [
"**Custom Prompts**\n",
"\n",
"You can also use your own prompts with this chain. In this example, we will respond in Italian."
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "5558c9e0",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'output_text': ' Il presidente ha detto che Justice Breyer ha dedicato la sua vita a servire questo paese e ha onorato la sua carriera come giudice della Corte Suprema degli Stati Uniti.'}"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"prompt_template = \"\"\"Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\n",
"\n",
"{context}\n",
"\n",
"Question: {question}\n",
"Answer in Italian:\"\"\"\n",
"PROMPT = PromptTemplate(\n",
" template=prompt_template, input_variables=[\"context\", \"question\"]\n",
")\n",
"chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"stuff\", prompt=PROMPT)\n",
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
{
"cell_type": "markdown",
"id": "91522e29",
@@ -208,6 +290,62 @@
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
{
"cell_type": "markdown",
"id": "93c51102",
"metadata": {},
"source": [
"**Custom Prompts**\n",
"\n",
"You can also use your own prompts with this chain. In this example, we will respond in Italian."
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "af03a578",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'intermediate_steps': [\"\\nStasera vorrei onorare qualcuno che ha dedicato la sua vita a servire questo paese: il giustizia Stephen Breyer - un veterano dell'esercito, uno studioso costituzionale e un giustizia in uscita della Corte Suprema degli Stati Uniti. Giustizia Breyer, grazie per il tuo servizio.\",\n",
" '\\nNessun testo pertinente.',\n",
" \"\\nCome ho detto l'anno scorso, soprattutto ai nostri giovani americani transgender, avrò sempre il tuo sostegno come tuo Presidente, in modo che tu possa essere te stesso e raggiungere il tuo potenziale donato da Dio.\",\n",
" '\\nNella mia amministrazione, i guardiani sono stati accolti di nuovo. Stiamo andando dietro ai criminali che hanno rubato miliardi di dollari di aiuti di emergenza destinati alle piccole imprese e a milioni di americani. E stasera, annuncio che il Dipartimento di Giustizia nominerà un procuratore capo per la frode pandemica.'],\n",
" 'output_text': ' Non conosco la risposta alla tua domanda su cosa abbia detto il Presidente riguardo al Giustizia Breyer.'}"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"question_prompt_template = \"\"\"Use the following portion of a long document to see if any of the text is relevant to answer the question. \n",
"Return any relevant text translated into italian.\n",
"{context}\n",
"Question: {question}\n",
"Relevant text, if any, in Italian:\"\"\"\n",
"QUESTION_PROMPT = PromptTemplate(\n",
" template=question_prompt_template, input_variables=[\"context\", \"question\"]\n",
")\n",
"\n",
"combine_prompt_template = \"\"\"Given the following extracted parts of a long document and a question, create a final answer italian. \n",
"If you don't know the answer, just say that you don't know. Don't try to make up an answer.\n",
"\n",
"QUESTION: {question}\n",
"=========\n",
"{summaries}\n",
"=========\n",
"Answer in Italian:\"\"\"\n",
"COMBINE_PROMPT = PromptTemplate(\n",
" template=combine_prompt_template, input_variables=[\"summaries\", \"question\"]\n",
")\n",
"chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"map_reduce\", return_map_steps=True, question_prompt=QUESTION_PROMPT, combine_prompt=COMBINE_PROMPT)\n",
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
{
"cell_type": "markdown",
"id": "6ea50ad0",
@@ -295,6 +433,72 @@
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
{
"cell_type": "markdown",
"id": "4f0bcae4",
"metadata": {},
"source": [
"**Custom Prompts**\n",
"\n",
"You can also use your own prompts with this chain. In this example, we will respond in Italian."
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "6664bda7",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'intermediate_steps': ['\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese e ha onorato la sua carriera. Ha anche detto che la sua nomina di Circuit Court of Appeals Judge Ketanji Brown Jackson continuerà il suo eccezionale lascito.',\n",
" \"\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese e ha onorato la sua carriera. Ha anche detto che la sua nomina di Circuit Court of Appeals Judge Ketanji Brown Jackson continuerà il suo eccezionale lascito. Ha sottolineato che la sua esperienza come avvocato di alto livello in pratica privata, come ex difensore federale pubblico e come membro di una famiglia di educatori e agenti di polizia, la rende una costruttrice di consenso. Ha anche sottolineato che, dalla sua nomina, ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani.\",\n",
" \"\\n\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese e ha onorato la sua carriera. Ha anche detto che la sua nomina di Circuit Court of Appeals Judge Ketanji Brown Jackson continuerà il suo eccezionale lascito. Ha sottolineato che la sua esperienza come avvocato di alto livello in pratica privata, come ex difensore federale pubblico e come membro di una famiglia di educatori e agenti di polizia, la rende una costruttrice di consenso. Ha anche sottolineato che, dalla sua nomina, ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Ha inoltre sottolineato che la nomina di Justice Breyer è un passo importante verso l'uguaglianza per tutti gli americani, in partic\",\n",
" \"\\n\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese e ha onorato la sua carriera. Ha anche detto che la sua nomina di Circuit Court of Appeals Judge Ketanji Brown Jackson continuerà il suo eccezionale lascito. Ha sottolineato che la sua esperienza come avvocato di alto livello in pratica privata, come ex difensore federale pubblico e come membro di una famiglia di educatori e agenti di polizia, la rende una costruttrice di consenso. Ha anche sottolineato che, dalla sua nomina, ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Ha inoltre sottolineato che la nomina di Justice Breyer è un passo importante verso l'uguaglianza per tutti gli americani, in partic\"],\n",
" 'output_text': \"\\n\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese e ha onorato la sua carriera. Ha anche detto che la sua nomina di Circuit Court of Appeals Judge Ketanji Brown Jackson continuerà il suo eccezionale lascito. Ha sottolineato che la sua esperienza come avvocato di alto livello in pratica privata, come ex difensore federale pubblico e come membro di una famiglia di educatori e agenti di polizia, la rende una costruttrice di consenso. Ha anche sottolineato che, dalla sua nomina, ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Ha inoltre sottolineato che la nomina di Justice Breyer è un passo importante verso l'uguaglianza per tutti gli americani, in partic\"}"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"refine_prompt_template = (\n",
" \"The original question is as follows: {question}\\n\"\n",
" \"We have provided an existing answer: {existing_answer}\\n\"\n",
" \"We have the opportunity to refine the existing answer\"\n",
" \"(only if needed) with some more context below.\\n\"\n",
" \"------------\\n\"\n",
" \"{context_str}\\n\"\n",
" \"------------\\n\"\n",
" \"Given the new context, refine the original answer to better \"\n",
" \"answer the question. \"\n",
" \"If the context isn't useful, return the original answer. Reply in Italian.\"\n",
")\n",
"refine_prompt = PromptTemplate(\n",
" input_variables=[\"question\", \"existing_answer\", \"context_str\"],\n",
" template=refine_prompt_template,\n",
")\n",
"\n",
"\n",
"initial_qa_template = (\n",
" \"Context information is below. \\n\"\n",
" \"---------------------\\n\"\n",
" \"{context_str}\"\n",
" \"\\n---------------------\\n\"\n",
" \"Given the context information and not prior knowledge, \"\n",
" \"answer the question: {question}\\nYour answer should be in Italian.\\n\"\n",
")\n",
"initial_qa_prompt = PromptTemplate(\n",
" input_variables=[\"context_str\", \"question\"], template=initial_qa_template\n",
")\n",
"chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"refine\", return_refine_steps=True,\n",
" question_prompt=initial_qa_prompt, refine_prompt=refine_prompt)\n",
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
{
"cell_type": "markdown",
"id": "521a77cb",
@@ -375,10 +579,79 @@
"results[\"intermediate_steps\"]"
]
},
{
"cell_type": "markdown",
"id": "5e47a818",
"metadata": {},
"source": [
"**Custom Prompts**\n",
"\n",
"You can also use your own prompts with this chain. In this example, we will respond in Italian."
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "41b83cd8",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'intermediate_steps': [{'answer': ' Il presidente ha detto che Justice Breyer ha dedicato la sua vita a servire questo paese e ha onorato la sua carriera.',\n",
" 'score': '100'},\n",
" {'answer': ' Il presidente non ha detto nulla sulla Giustizia Breyer.',\n",
" 'score': '100'},\n",
" {'answer': ' Non so.', 'score': '0'},\n",
" {'answer': ' Il presidente non ha detto nulla sulla giustizia Breyer.',\n",
" 'score': '100'}],\n",
" 'output_text': ' Il presidente ha detto che Justice Breyer ha dedicato la sua vita a servire questo paese e ha onorato la sua carriera.'}"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from langchain.prompts.base import RegexParser\n",
"\n",
"output_parser = RegexParser(\n",
" regex=r\"(.*?)\\nScore: (.*)\",\n",
" output_keys=[\"answer\", \"score\"],\n",
")\n",
"\n",
"prompt_template = \"\"\"Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\n",
"\n",
"In addition to giving an answer, also return a score of how fully it answered the user's question. This should be in the following format:\n",
"\n",
"Question: [question here]\n",
"Helpful Answer In Italian: [answer here]\n",
"Score: [score between 0 and 100]\n",
"\n",
"Begin!\n",
"\n",
"Context:\n",
"---------\n",
"{context}\n",
"---------\n",
"Question: {question}\n",
"Helpful Answer In Italian:\"\"\"\n",
"PROMPT = PromptTemplate(\n",
" template=prompt_template,\n",
" input_variables=[\"context\", \"question\"],\n",
" output_parser=output_parser,\n",
")\n",
"\n",
"chain = load_qa_chain(OpenAI(temperature=0), chain_type=\"map_rerank\", return_intermediate_steps=True, prompt=PROMPT)\n",
"query = \"What did the president say about Justice Breyer\"\n",
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c4f86521",
"id": "e0f0bbdf",
"metadata": {},
"outputs": [],
"source": []