langchain-practice/L6_student.ipynb

526 lines
13 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"id": "0fab81f5-a0ca-4574-b656-5fd1719dde71",
"metadata": {},
"source": [
"# Lesson 6: Shipping as a web API"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "18f6254b-5eaf-4867-999b-97d08f96cee9",
"metadata": {
"height": 31
},
"outputs": [],
"source": [
"import \"dotenv/config\";"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c326a7cc-d9be-432c-be10-7846d2b8e5e9",
"metadata": {
"height": 285
},
"outputs": [],
"source": [
"import { \n",
" loadAndSplitChunks, \n",
" initializeVectorstoreWithDocuments \n",
"} from \"./lib/helpers.ts\";\n",
"\n",
"const splitDocs = await loadAndSplitChunks({\n",
" chunkSize: 1536,\n",
" chunkOverlap: 128,\n",
"});\n",
"\n",
"const vectorstore = await initializeVectorstoreWithDocuments({\n",
" documents: splitDocs,\n",
"});\n",
"\n",
"const retriever = vectorstore.asRetriever();"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8b25e21c-28d0-4329-852e-b96a14c38529",
"metadata": {
"height": 149
},
"outputs": [],
"source": [
"import { \n",
" createDocumentRetrievalChain, \n",
" createRephraseQuestionChain \n",
"} from \"./lib/helpers.ts\";\n",
"\n",
"const documentRetrievalChain = createDocumentRetrievalChain();\n",
"const rephraseQuestionChain = createRephraseQuestionChain();"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "520b4a9b-89de-4652-b238-b7dddbd5a2c2",
"metadata": {
"height": 404
},
"outputs": [],
"source": [
"import { ChatPromptTemplate, MessagesPlaceholder } from \"@langchain/core/prompts\";\n",
"\n",
"const ANSWER_CHAIN_SYSTEM_TEMPLATE = `You are an experienced researcher,\n",
"expert at interpreting and answering questions based on provided sources.\n",
"Using the below provided context and chat history, \n",
"answer the user's question to the best of your ability\n",
"using only the resources provided. Be verbose!\n",
"\n",
"<context>\n",
"{context}\n",
"</context>`;\n",
"\n",
"const answerGenerationChainPrompt = ChatPromptTemplate.fromMessages([\n",
" [\"system\", ANSWER_CHAIN_SYSTEM_TEMPLATE],\n",
" new MessagesPlaceholder(\"history\"),\n",
" [\n",
" \"human\", \n",
" `Now, answer this question using the previous context and chat history:\n",
" \n",
" {standalone_question}`\n",
" ]\n",
"]);"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c325c8b5-9292-41f2-ad10-3ad0ad3df182",
"metadata": {
"height": 302
},
"outputs": [],
"source": [
"import { \n",
" RunnablePassthrough, \n",
" RunnableSequence \n",
"} from \"@langchain/core/runnables\";\n",
"import { ChatOpenAI } from \"@langchain/openai\";\n",
"\n",
"const conversationalRetrievalChain = RunnableSequence.from([\n",
" RunnablePassthrough.assign({\n",
" standalone_question: rephraseQuestionChain,\n",
" }),\n",
" RunnablePassthrough.assign({\n",
" context: documentRetrievalChain,\n",
" }),\n",
" answerGenerationChainPrompt,\n",
" new ChatOpenAI({ modelName: \"gpt-3.5-turbo-1106\" }),\n",
"]);"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f5fe1d4c-9075-47d4-8451-b9bbc1115668",
"metadata": {
"height": 132
},
"outputs": [],
"source": [
"import { HttpResponseOutputParser } from \"langchain/output_parsers\";\n",
"\n",
"// \"text/event-stream\" is also supported\n",
"const httpResponseOutputParser = new HttpResponseOutputParser({\n",
" contentType: \"text/plain\"\n",
"});"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9cb3853d-826c-4e1f-a413-9f9f0faf62fe",
"metadata": {
"height": 217
},
"outputs": [],
"source": [
"import { RunnableWithMessageHistory } from \"@langchain/core/runnables\"; \n",
"import { ChatMessageHistory } from \"langchain/stores/message/in_memory\";\n",
"\n",
"const messageHistory = new ChatMessageHistory();\n",
"\n",
"const finalRetrievalChain = new RunnableWithMessageHistory({\n",
" runnable: conversationalRetrievalChain,\n",
" getMessageHistory: (_sessionId) => messageHistory,\n",
" historyMessagesKey: \"history\",\n",
" inputMessagesKey: \"question\",\n",
"}).pipe(httpResponseOutputParser);"
]
},
{
"cell_type": "markdown",
"id": "ecaeb6ee-d3a0-4adb-b08c-e78a7ef92321",
"metadata": {},
"source": [
"Additionally, we'll want to bear in mind that users should not share chat histories, and we should create a new history object per session:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c8f81c9f-88d7-470a-b597-c4137c9d35a4",
"metadata": {
"height": 200
},
"outputs": [],
"source": [
"const messageHistories = {};\n",
"\n",
"const getMessageHistoryForSession = (sessionId) => {\n",
" if (messageHistories[sessionId] !== undefined) {\n",
" return messageHistories[sessionId];\n",
" } \n",
" const newChatSessionHistory = new ChatMessageHistory();\n",
" messageHistories[sessionId] = newChatSessionHistory;\n",
" return newChatSessionHistory;\n",
"};"
]
},
{
"cell_type": "markdown",
"id": "ae7291e9-6448-4931-bd56-f905f6324b4e",
"metadata": {},
"source": [
"We'll recreate our final chain with this new method:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "24bc88b0-851c-4304-a085-ac0cba9f615f",
"metadata": {
"height": 132
},
"outputs": [],
"source": [
"const finalRetrievalChain = new RunnableWithMessageHistory({\n",
" runnable: conversationalRetrievalChain,\n",
" getMessageHistory: getMessageHistoryForSession,\n",
" inputMessagesKey: \"question\",\n",
" historyMessagesKey: \"history\",\n",
"}).pipe(httpResponseOutputParser);"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f35a5209-e820-496b-9abc-60ade9f22d7c",
"metadata": {
"height": 30
},
"outputs": [],
"source": [
"const port = 8087;"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ebc26867-8376-4358-9525-221227967091",
"metadata": {
"height": 251
},
"outputs": [],
"source": [
"const handler = async (request: Request): Response => {\n",
" const body = await request.json();\n",
" const stream = await finalRetrievalChain.stream({\n",
" question: body.question\n",
" }, { configurable: { sessionId: body.session_id } });\n",
"\n",
" return new Response(stream, { \n",
" status: 200,\n",
" headers: {\n",
" \"Content-Type\": \"text/plain\"\n",
" },\n",
" });\n",
"};"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0ac36205-de1c-4cfb-81e8-9c9d1525b338",
"metadata": {
"height": 30
},
"outputs": [],
"source": [
"Deno.serve({ port }, handler);"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b547772d-4f1f-48e8-b381-138b30d993af",
"metadata": {
"height": 336
},
"outputs": [],
"source": [
"const decoder = new TextDecoder();\n",
"\n",
"// readChunks() reads from the provided reader and yields the results into an async iterable\n",
"function readChunks(reader) {\n",
" return {\n",
" async* [Symbol.asyncIterator]() {\n",
" let readResult = await reader.read();\n",
" while (!readResult.done) {\n",
" yield decoder.decode(readResult.value);\n",
" readResult = await reader.read();\n",
" }\n",
" },\n",
" };\n",
"}\n",
"\n",
"const sleep = async () => {\n",
" return new Promise((resolve) => setTimeout(resolve, 500));\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ac25b85d-dd40-42a1-8374-6c778e86c9d8",
"metadata": {
"height": 353
},
"outputs": [],
"source": [
"const response = await fetch(`http://localhost:${port}`, {\n",
" method: \"POST\",\n",
" headers: {\n",
" \"content-type\": \"application/json\",\n",
" },\n",
" body: JSON.stringify({\n",
" question: \"What are the prerequisites for this course?\",\n",
" session_id: \"1\", // Should randomly generate/assign\n",
" })\n",
"});\n",
"\n",
"// response.body is a ReadableStream\n",
"const reader = response.body?.getReader();\n",
"\n",
"for await (const chunk of readChunks(reader)) {\n",
" console.log(\"CHUNK:\", chunk);\n",
"}\n",
"\n",
"await sleep();"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7af107da-cf4c-4900-a456-d131ff8fbc80",
"metadata": {
"height": 353
},
"outputs": [],
"source": [
"const response = await fetch(`http://localhost:${port}`, {\n",
" method: \"POST\",\n",
" headers: {\n",
" \"content-type\": \"application/json\",\n",
" },\n",
" body: JSON.stringify({\n",
" question: \"Can you list them in bullet point format?\",\n",
" session_id: \"1\", // Should randomly generate/assign\n",
" })\n",
"});\n",
"\n",
"// response.body is a ReadableStream\n",
"const reader = response.body?.getReader();\n",
"\n",
"for await (const chunk of readChunks(reader)) {\n",
" console.log(\"CHUNK:\", chunk);\n",
"}\n",
"\n",
"await sleep();"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fbcaa28f-5057-4109-80c1-406ec47bd9eb",
"metadata": {
"height": 353
},
"outputs": [],
"source": [
"const response = await fetch(`http://localhost:${port}`, {\n",
" method: \"POST\",\n",
" headers: {\n",
" \"content-type\": \"application/json\",\n",
" },\n",
" body: JSON.stringify({\n",
" question: \"What did I just ask you?\",\n",
" session_id: \"2\", // Should randomly generate/assign\n",
" })\n",
"});\n",
"\n",
"// response.body is a ReadableStream\n",
"const reader = response.body?.getReader();\n",
"\n",
"for await (const chunk of readChunks(reader)) {\n",
" console.log(\"CHUNK:\", chunk);\n",
"}\n",
"\n",
"await sleep();"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "464b5f7d-75e0-4366-8adf-48053f19229d",
"metadata": {
"height": 30
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "e50feff9-72d1-4c1a-96b9-ec80ccde87f9",
"metadata": {
"height": 30
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "258343e5-e488-4c2c-938b-8c3189ef959d",
"metadata": {
"height": 30
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "6ec20e0c-389f-4cd1-b5df-67f6d706fb4e",
"metadata": {
"height": 30
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "a4b2b76f-f963-4226-95f1-42d15487f0ca",
"metadata": {
"height": 30
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "99a497d1-0587-431b-bc54-657e935af6df",
"metadata": {
"height": 30
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "12805d9a-d5fe-48d5-acf3-d88a929e9d21",
"metadata": {
"height": 30
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "56d65826-7917-4a51-b937-37d3d460c5eb",
"metadata": {
"height": 30
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "fc803c79-ef69-4539-b2eb-da3cd89cb134",
"metadata": {
"height": 30
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "9ca4ed79-d80a-4d26-9832-1c13b7eb9085",
"metadata": {
"height": 30
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "241f7da1-51d2-4bc8-8ea8-a76eb80a70cf",
"metadata": {
"height": 30
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "c838bf09-8369-4942-a78f-73a94b74d602",
"metadata": {
"height": 30
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Deno",
"language": "typescript",
"name": "deno"
},
"language_info": {
"file_extension": ".ts",
"mimetype": "text/x.typescript",
"name": "typescript",
"nb_converter": "script",
"pygments_lexer": "typescript",
"version": "5.3.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}