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

pull/565/head
Harrison Chase 1 year ago committed by GitHub
parent 1511606799
commit b06a2a6191
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -31,7 +31,8 @@
"from langchain.text_splitter import CharacterTextSplitter\n",
"from langchain.vectorstores.elastic_vector_search import ElasticVectorSearch\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"
]
},
{
@ -81,6 +82,46 @@
"from langchain.llms import OpenAI"
]
},
{
"cell_type": "markdown",
"id": "5b119026",
"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": 13,
"id": "3722373b",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'output_text': ' The president thanked Justice Breyer for his service.\\nSOURCES: 30-pl'}"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type=\"stuff\")\n",
"query = \"What did the president say about Justice Breyer\"\n",
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
{
"cell_type": "markdown",
"id": "bdaf9268",
"metadata": {},
"source": [
"If you want more control and understanding over what is happening, please see the information below."
]
},
{
"cell_type": "markdown",
"id": "d82f899a",
@ -123,6 +164,51 @@
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
{
"cell_type": "markdown",
"id": "e966aea8",
"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": "426c570b",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'output_text': '\\nNon so cosa abbia detto il presidente riguardo a Justice Breyer.\\nSOURCES: 30, 31, 33'}"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"template = \"\"\"Given the following extracted parts of a long document and a question, create a final answer with references (\"SOURCES\"). \n",
"If you don't know the answer, just say that you don't know. Don't try to make up an answer.\n",
"ALWAYS return a \"SOURCES\" part in your answer.\n",
"Respond in Italian.\n",
"\n",
"QUESTION: {question}\n",
"=========\n",
"{summaries}\n",
"=========\n",
"FINAL ANSWER IN ITALIAN:\"\"\"\n",
"PROMPT = PromptTemplate(template=template, input_variables=[\"summaries\", \"question\"])\n",
"\n",
"chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type=\"stuff\", 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": "markdown",
"id": "c5dbb304",
@ -210,6 +296,66 @@
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
{
"cell_type": "markdown",
"id": "d56e101a",
"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": 8,
"id": "47f0d517",
"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",
" ' Non pertinente.',\n",
" ' Non rilevante.',\n",
" \" Non c'è testo pertinente.\"],\n",
" 'output_text': ' Non conosco la risposta. SOURCES: 30, 31, 33, 20.'}"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"\n",
"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 in 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 with references (\"SOURCES\"). \n",
"If you don't know the answer, just say that you don't know. Don't try to make up an answer.\n",
"ALWAYS return a \"SOURCES\" part in your answer.\n",
"Respond in Italian.\n",
"\n",
"QUESTION: {question}\n",
"=========\n",
"{summaries}\n",
"=========\n",
"FINAL ANSWER IN ITALIAN:\"\"\"\n",
"COMBINE_PROMPT = PromptTemplate(\n",
" template=combine_prompt_template, input_variables=[\"summaries\", \"question\"]\n",
")\n",
"\n",
"chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type=\"map_reduce\", return_intermediate_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": "5bf0e1ab",
@ -297,6 +443,81 @@
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
{
"cell_type": "markdown",
"id": "cf08c8a1",
"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": 9,
"id": "97e33bd9",
"metadata": {},
"outputs": [],
"source": [
"refine_template = (\n",
" \"The original question is as follows: {question}\\n\"\n",
" \"We have provided an existing answer, including sources: {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 (in Italian)\"\n",
" \"If you do update it, please update the sources as well. \"\n",
" \"If the context isn't useful, return the original answer.\"\n",
")\n",
"refine_prompt = PromptTemplate(\n",
" input_variables=[\"question\", \"existing_answer\", \"context_str\"],\n",
" template=refine_template,\n",
")\n",
"\n",
"\n",
"question_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 in Italian: {question}\\n\"\n",
")\n",
"question_prompt = PromptTemplate(\n",
" input_variables=[\"context_str\", \"question\"], template=question_template\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "41565992",
"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.',\n",
" \"\\n\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha onorato la sua carriera e ha contribuito a costruire un consenso. Ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Inoltre, ha sottolineato l'importanza di avanzare la libertà e la giustizia attraverso la sicurezza delle frontiere e la risoluzione del sistema di immigrazione. Ha anche menzionato le nuove tecnologie come scanner all'avanguardia per rilevare meglio il traffico di droga, le pattuglie congiunte con Messico e Guatemala per catturare più trafficanti di esseri umani, l'istituzione di giudici di immigrazione dedicati per far sì che le famiglie che fuggono da per\",\n",
" \"\\n\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha onorato la sua carriera e ha contribuito a costruire un consenso. Ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Inoltre, ha sottolineato l'importanza di avanzare la libertà e la giustizia attraverso la sicurezza delle frontiere e la risoluzione del sistema di immigrazione. Ha anche menzionato le nuove tecnologie come scanner all'avanguardia per rilevare meglio il traffico di droga, le pattuglie congiunte con Messico e Guatemala per catturare più trafficanti di esseri umani, l'istituzione di giudici di immigrazione dedicati per far sì che le famiglie che fuggono da per\",\n",
" \"\\n\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha onorato la sua carriera e ha contribuito a costruire un consenso. Ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Inoltre, ha sottolineato l'importanza di avanzare la libertà e la giustizia attraverso la sicurezza delle frontiere e la risoluzione del sistema di immigrazione. Ha anche menzionato le nuove tecnologie come scanner all'avanguardia per rilevare meglio il traffico di droga, le pattuglie congiunte con Messico e Guatemala per catturare più trafficanti di esseri umani, l'istituzione di giudici di immigrazione dedicati per far sì che le famiglie che fuggono da per\"],\n",
" 'output_text': \"\\n\\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha onorato la sua carriera e ha contribuito a costruire un consenso. Ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Inoltre, ha sottolineato l'importanza di avanzare la libertà e la giustizia attraverso la sicurezza delle frontiere e la risoluzione del sistema di immigrazione. Ha anche menzionato le nuove tecnologie come scanner all'avanguardia per rilevare meglio il traffico di droga, le pattuglie congiunte con Messico e Guatemala per catturare più trafficanti di esseri umani, l'istituzione di giudici di immigrazione dedicati per far sì che le famiglie che fuggono da per\"}"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type=\"refine\", return_intermediate_steps=True, question_prompt=question_prompt, refine_prompt=refine_prompt)\n",
"chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
{
"cell_type": "markdown",
"id": "07ff756e",
@ -374,10 +595,89 @@
"result[\"intermediate_steps\"]"
]
},
{
"cell_type": "markdown",
"id": "b94bfeb6",
"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": 11,
"id": "cb46ba3f",
"metadata": {},
"outputs": [],
"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",
"chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type=\"map_rerank\", metadata_keys=['source'], return_intermediate_steps=True, prompt=PROMPT)\n",
"query = \"What did the president say about Justice Breyer\"\n",
"result = chain({\"input_documents\": docs, \"question\": query}, return_only_outputs=True)"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "fee7b055",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'source': 30,\n",
" '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": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"result"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e66b8160",
"id": "5a51c987",
"metadata": {},
"outputs": [],
"source": []

@ -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": []

@ -21,7 +21,7 @@
},
{
"cell_type": "code",
"execution_count": 3,
"execution_count": 7,
"id": "e9db25f3",
"metadata": {},
"outputs": [],
@ -29,6 +29,7 @@
"from langchain import OpenAI, PromptTemplate, LLMChain\n",
"from langchain.text_splitter import CharacterTextSplitter\n",
"from langchain.chains.mapreduce import MapReduceChain\n",
"from langchain.prompts import PromptTemplate\n",
"\n",
"llm = OpenAI(temperature=0)\n",
"\n",
@ -37,7 +38,7 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 2,
"id": "99bbe19b",
"metadata": {},
"outputs": [],
@ -49,7 +50,7 @@
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": 3,
"id": "baa6e808",
"metadata": {},
"outputs": [],
@ -61,7 +62,7 @@
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": 4,
"id": "27989fc4",
"metadata": {},
"outputs": [],
@ -69,6 +70,45 @@
"from langchain.chains.summarize import load_summarize_chain"
]
},
{
"cell_type": "markdown",
"id": "21284c47",
"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": 14,
"id": "5cfa89b2",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\" In response to Russia's aggression in Ukraine, the United States and its allies have imposed economic sanctions and are taking other measures to hold Putin accountable. The US is also providing economic and military assistance to Ukraine, protecting NATO countries, and investing in American products to create jobs. President Biden and Vice President Harris have passed the American Rescue Plan and the Bipartisan Infrastructure Law to help working people and rebuild America.\""
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"chain = load_summarize_chain(llm, chain_type=\"map_reduce\")\n",
"chain.run(docs)"
]
},
{
"cell_type": "markdown",
"id": "1bc784bd",
"metadata": {},
"source": [
"If you want more control and understanding over what is happening, please see the information below."
]
},
{
"cell_type": "markdown",
"id": "ea2d5c99",
@ -81,7 +121,7 @@
},
{
"cell_type": "code",
"execution_count": 9,
"execution_count": 5,
"id": "f01f3196",
"metadata": {},
"outputs": [],
@ -91,7 +131,7 @@
},
{
"cell_type": "code",
"execution_count": 10,
"execution_count": 6,
"id": "da4d9801",
"metadata": {},
"outputs": [
@ -101,7 +141,7 @@
"' In his speech, President Biden addressed the crisis in Ukraine, the American Rescue Plan, and the Bipartisan Infrastructure Law. He discussed the need to invest in America, educate Americans, and build the economy from the bottom up. He also announced the release of 60 million barrels of oil from reserves around the world, and the creation of a dedicated task force to go after the crimes of Russian oligarchs. He concluded by emphasizing the need to Buy American and use taxpayer dollars to rebuild America.'"
]
},
"execution_count": 10,
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
@ -110,6 +150,46 @@
"chain.run(docs)"
]
},
{
"cell_type": "markdown",
"id": "42b6d8ae",
"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": 8,
"id": "71dc4212",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\"\\n\\nIn questa serata, il Presidente degli Stati Uniti ha annunciato una serie di misure per affrontare la crisi in Ucraina, causata dall'aggressione di Putin. Ha anche annunciato l'invio di aiuti economici, militari e umanitari all'Ucraina. Ha anche annunciato che gli Stati Uniti e i loro alleati stanno imponendo sanzioni economiche a Putin e stanno rilasciando 60 milioni di barili di petrolio dalle riserve di tutto il mondo. Inoltre, ha annunciato che il Dipartimento di Giustizia degli Stati Uniti sta creando una task force dedicata ai crimini degli oligarchi russi. Il Presidente ha anche annunciato l'approvazione della legge bipartitica sull'infrastruttura, che prevede investimenti per la ricostruzione dell'America. Questo porterà a creare posti\""
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"prompt_template = \"\"\"Write a concise summary of the following:\n",
"\n",
"\n",
"{text}\n",
"\n",
"\n",
"CONCISE SUMMARY IN ITALIAN:\"\"\"\n",
"PROMPT = PromptTemplate(template=prompt_template, input_variables=[\"text\"])\n",
"chain = load_summarize_chain(llm, chain_type=\"stuff\", prompt=PROMPT)\n",
"chain.run(docs)"
]
},
{
"cell_type": "markdown",
"id": "9c868e86",
@ -168,7 +248,7 @@
"metadata": {},
"outputs": [],
"source": [
"chain = load_summarize_chain(OpenAI(temperature=0), chain_type=\"map_reduce\", return_map_steps=True)"
"chain = load_summarize_chain(OpenAI(temperature=0), chain_type=\"map_reduce\", return_intermediate_steps=True)"
]
},
{
@ -195,6 +275,49 @@
"chain({\"input_documents\": docs}, return_only_outputs=True)"
]
},
{
"cell_type": "markdown",
"id": "255c8993",
"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": 10,
"id": "b65d5069",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'intermediate_steps': [\"\\n\\nQuesta sera, ci incontriamo come democratici, repubblicani e indipendenti, ma soprattutto come americani. La Russia di Putin ha cercato di scuotere le fondamenta del mondo libero, ma ha sottovalutato la forza della gente ucraina. Gli Stati Uniti e i loro alleati stanno ora imponendo sanzioni economiche a Putin e stanno tagliando l'accesso della Russia alla tecnologia. Il Dipartimento di Giustizia degli Stati Uniti sta anche creando una task force dedicata per andare dopo i crimini degli oligarchi russi.\",\n",
" \"\\n\\nStiamo unendo le nostre forze con quelle dei nostri alleati europei per sequestrare yacht, appartamenti di lusso e jet privati di Putin. Abbiamo chiuso lo spazio aereo americano ai voli russi e stiamo fornendo più di un miliardo di dollari in assistenza all'Ucraina. Abbiamo anche mobilitato le nostre forze terrestri, aeree e navali per proteggere i paesi della NATO. Abbiamo anche rilasciato 60 milioni di barili di petrolio dalle riserve di tutto il mondo, di cui 30 milioni dalla nostra riserva strategica di petrolio. Stiamo affrontando una prova reale e ci vorrà del tempo, ma alla fine Putin non riuscirà a spegnere l'amore dei popoli per la libertà.\",\n",
" \"\\n\\nIl Presidente Biden ha lottato per passare l'American Rescue Plan per aiutare le persone che soffrivano a causa della pandemia. Il piano ha fornito sollievo economico immediato a milioni di americani, ha aiutato a mettere cibo sulla loro tavola, a mantenere un tetto sopra le loro teste e a ridurre il costo dell'assicurazione sanitaria. Il piano ha anche creato più di 6,5 milioni di nuovi posti di lavoro, il più alto numero di posti di lavoro creati in un anno nella storia degli Stati Uniti. Il Presidente Biden ha anche firmato la legge bipartitica sull'infrastruttura, la più ampia iniziativa di ricostruzione della storia degli Stati Uniti. Il piano prevede di modernizzare le strade, gli aeroporti, i porti e le vie navigabili in\"],\n",
" 'output_text': \"\\n\\nIl Presidente Biden sta lavorando per aiutare le persone che soffrono a causa della pandemia attraverso l'American Rescue Plan e la legge bipartitica sull'infrastruttura. Gli Stati Uniti e i loro alleati stanno anche imponendo sanzioni economiche a Putin e tagliando l'accesso della Russia alla tecnologia. Stanno anche sequestrando yacht, appartamenti di lusso e jet privati di Putin e fornendo più di un miliardo di dollari in assistenza all'Ucraina. Alla fine, Putin non riuscirà a spegnere l'amore dei popoli per la libertà.\"}"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"prompt_template = \"\"\"Write a concise summary of the following:\n",
"\n",
"\n",
"{text}\n",
"\n",
"\n",
"CONCISE SUMMARY IN ITALIAN:\"\"\"\n",
"PROMPT = PromptTemplate(template=prompt_template, input_variables=[\"text\"])\n",
"chain = load_summarize_chain(OpenAI(temperature=0), chain_type=\"map_reduce\", return_intermediate_steps=True, map_prompt=PROMPT, combine_prompt=PROMPT)\n",
"chain({\"input_documents\": docs}, return_only_outputs=True)"
]
},
{
"cell_type": "markdown",
"id": "f61350f9",
@ -259,15 +382,81 @@
}
],
"source": [
"chain = load_summarize_chain(OpenAI(temperature=0), chain_type=\"refine\", return_refine_steps=True)\n",
"chain = load_summarize_chain(OpenAI(temperature=0), chain_type=\"refine\", return_intermediate_steps=True)\n",
"\n",
"chain({\"input_documents\": docs}, return_only_outputs=True)"
]
},
{
"cell_type": "markdown",
"id": "822be0d2",
"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": "ffe37bec",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'intermediate_steps': [\"\\n\\nQuesta sera, ci incontriamo come democratici, repubblicani e indipendenti, ma soprattutto come americani. La Russia di Putin ha cercato di scuotere le fondamenta del mondo libero, ma ha sottovalutato la forza della gente ucraina. Insieme ai nostri alleati, stiamo imponendo sanzioni economiche, tagliando l'accesso della Russia alla tecnologia e bloccando i suoi più grandi istituti bancari dal sistema finanziario internazionale. Il Dipartimento di Giustizia degli Stati Uniti sta anche assemblando una task force dedicata per andare dopo i crimini degli oligarchi russi.\",\n",
" \"\\n\\nQuesta sera, ci incontriamo come democratici, repubblicani e indipendenti, ma soprattutto come americani. La Russia di Putin ha cercato di scuotere le fondamenta del mondo libero, ma ha sottovalutato la forza della gente ucraina. Insieme ai nostri alleati, stiamo imponendo sanzioni economiche, tagliando l'accesso della Russia alla tecnologia, bloccando i suoi più grandi istituti bancari dal sistema finanziario internazionale e chiudendo lo spazio aereo americano a tutti i voli russi. Il Dipartimento di Giustizia degli Stati Uniti sta anche assemblando una task force dedicata per andare dopo i crimini degli oligarchi russi. Stiamo fornendo più di un miliardo di dollari in assistenza diretta all'Ucraina e fornendo assistenza militare,\",\n",
" \"\\n\\nQuesta sera, ci incontriamo come democratici, repubblicani e indipendenti, ma soprattutto come americani. La Russia di Putin ha cercato di scuotere le fondamenta del mondo libero, ma ha sottovalutato la forza della gente ucraina. Insieme ai nostri alleati, stiamo imponendo sanzioni economiche, tagliando l'accesso della Russia alla tecnologia, bloccando i suoi più grandi istituti bancari dal sistema finanziario internazionale e chiudendo lo spazio aereo americano a tutti i voli russi. Il Dipartimento di Giustizia degli Stati Uniti sta anche assemblando una task force dedicata per andare dopo i crimini degli oligarchi russi. Stiamo fornendo più di un miliardo di dollari in assistenza diretta all'Ucraina e fornendo assistenza militare.\"],\n",
" 'output_text': \"\\n\\nQuesta sera, ci incontriamo come democratici, repubblicani e indipendenti, ma soprattutto come americani. La Russia di Putin ha cercato di scuotere le fondamenta del mondo libero, ma ha sottovalutato la forza della gente ucraina. Insieme ai nostri alleati, stiamo imponendo sanzioni economiche, tagliando l'accesso della Russia alla tecnologia, bloccando i suoi più grandi istituti bancari dal sistema finanziario internazionale e chiudendo lo spazio aereo americano a tutti i voli russi. Il Dipartimento di Giustizia degli Stati Uniti sta anche assemblando una task force dedicata per andare dopo i crimini degli oligarchi russi. Stiamo fornendo più di un miliardo di dollari in assistenza diretta all'Ucraina e fornendo assistenza militare.\"}"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"prompt_template = \"\"\"Write a concise summary of the following:\n",
"\n",
"\n",
"{text}\n",
"\n",
"\n",
"CONCISE SUMMARY IN ITALIAN:\"\"\"\n",
"PROMPT = PromptTemplate(template=prompt_template, input_variables=[\"text\"])\n",
"refine_template = (\n",
" \"Your job is to produce a final summary\\n\"\n",
" \"We have provided an existing summary up to a certain point: {existing_answer}\\n\"\n",
" \"We have the opportunity to refine the existing summary\"\n",
" \"(only if needed) with some more context below.\\n\"\n",
" \"------------\\n\"\n",
" \"{text}\\n\"\n",
" \"------------\\n\"\n",
" \"Given the new context, refine the original summary in Italian\"\n",
" \"If the context isn't useful, return the original summary.\"\n",
")\n",
"refine_prompt = PromptTemplate(\n",
" input_variables=[\"existing_answer\", \"text\"],\n",
" template=refine_template,\n",
")\n",
"chain = load_summarize_chain(OpenAI(temperature=0), chain_type=\"refine\", return_intermediate_steps=True, question_prompt=PROMPT, refine_prompt=refine_prompt)\n",
"chain({\"input_documents\": docs}, return_only_outputs=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5175b1d4",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3.9.0 64-bit ('llm-env')",
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
@ -281,7 +470,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.0"
"version": "3.10.9"
},
"vscode": {
"interpreter": {

@ -3,6 +3,14 @@
Question answering involves fetching multiple documents, and then asking a question of them.
The LLM response will contain the answer to your question, based on the content of the documents.
The recommended way to get started using a question answering chain is:
```python
from langchain.chains.question_answering import load_qa_chain
chain = load_qa_chain(llm, chain_type="stuff")
chain.run(input_documents=docs, question=query)
```
The following resources exist:
- [Question Answering Notebook](/modules/chains/combine_docs_examples/question_answering.ipynb): A notebook walking through how to accomplish this task.
- [VectorDB Question Answering Notebook](/modules/chains/combine_docs_examples/vector_db_qa.ipynb): A notebook walking through how to do question answering over a vector database. This can often be useful for when you have a LOT of documents, and you don't want to pass them all to the LLM, but rather first want to do some semantic search over embeddings.
@ -11,6 +19,14 @@ The following resources exist:
There is also a variant of this, where in addition to responding with the answer the language model will also cite its sources (eg which of the documents passed in it used).
The recommended way to get started using a question answering with sources chain is:
```python
from langchain.chains.qa_with_sources import load_qa_with_sources_chain
chain = load_qa_with_sources_chain(llm, chain_type="stuff")
chain({"input_documents": docs, "question": query}, return_only_outputs=True)
```
The following resources exist:
- [QA With Sources Notebook](/modules/chains/combine_docs_examples/qa_with_sources.ipynb): A notebook walking through how to accomplish this task.
- [VectorDB QA With Sources Notebook](/modules/chains/combine_docs_examples/vector_db_qa_with_sources.ipynb): A notebook walking through how to do question answering with sources over a vector database. This can often be useful for when you have a LOT of documents, and you don't want to pass them all to the LLM, but rather first want to do some semantic search over embeddings.

@ -1,7 +1,15 @@
# Summarization
Summarization involves creating a smaller summary of multiple longer documents.
This can be useful for distilling long documents into the core pieces of information
This can be useful for distilling long documents into the core pieces of information.
The recommended way to get started using a summarization chain is:
```python
from langchain.chains.summarize import load_summarize_chain
chain = load_summarize_chain(llm, chain_type="map_reduce")
chain.run(docs)
```
The following resources exist:
- [Summarization Notebook](/modules/chains/combine_docs_examples/summarize.ipynb): A notebook walking through how to accomplish this task.

Loading…
Cancel
Save