austinbv commited on
Commit
48dd198
·
1 Parent(s): 2c9f2c4

Create working frontend chat for langserve rag

Browse files
app/rag_chain.py CHANGED
@@ -4,8 +4,8 @@ from typing import TypedDict
4
 
5
  from dotenv import load_dotenv
6
  from langchain_community.vectorstores.pgvector import PGVector
7
- from langchain_core.output_parsers import StrOutputParser
8
  from langchain_core.prompts import ChatPromptTemplate
 
9
  from langchain_openai import ChatOpenAI, OpenAIEmbeddings
10
 
11
  from config import PG_COLLECTION_NAME
@@ -35,11 +35,13 @@ class RagInput(TypedDict):
35
 
36
 
37
  final_chain = (
38
- {
39
- "context": itemgetter("question") | vector_store.as_retriever(),
40
- "question": itemgetter("question")
41
- }
42
- | ANSWER_PROMPT
43
- | llm
44
- | StrOutputParser()
 
 
45
  ).with_types(input_type=RagInput)
 
4
 
5
  from dotenv import load_dotenv
6
  from langchain_community.vectorstores.pgvector import PGVector
 
7
  from langchain_core.prompts import ChatPromptTemplate
8
+ from langchain_core.runnables import RunnableParallel
9
  from langchain_openai import ChatOpenAI, OpenAIEmbeddings
10
 
11
  from config import PG_COLLECTION_NAME
 
35
 
36
 
37
  final_chain = (
38
+ RunnableParallel(
39
+ context=(itemgetter("question") | vector_store.as_retriever()),
40
+ question=itemgetter("question")
41
+ ) |
42
+ RunnableParallel(
43
+ answer=(ANSWER_PROMPT | llm),
44
+ docs=itemgetter("context")
45
+ )
46
+
47
  ).with_types(input_type=RagInput)
app/server.py CHANGED
@@ -1,12 +1,24 @@
1
  from fastapi import FastAPI
2
  from fastapi.responses import RedirectResponse
3
  from langserve import add_routes
 
 
4
 
5
  from app.rag_chain import final_chain
6
 
7
  app = FastAPI()
8
 
9
-
 
 
 
 
 
 
 
 
 
 
10
  @app.get("/")
11
  async def redirect_root_to_docs():
12
  return RedirectResponse("/docs")
 
1
  from fastapi import FastAPI
2
  from fastapi.responses import RedirectResponse
3
  from langserve import add_routes
4
+ from fastapi.middleware.cors import CORSMiddleware
5
+ from starlette.staticfiles import StaticFiles
6
 
7
  from app.rag_chain import final_chain
8
 
9
  app = FastAPI()
10
 
11
+ app.add_middleware(
12
+ CORSMiddleware,
13
+ allow_origins=[
14
+ "http://localhost:3000"
15
+ ],
16
+ allow_credentials=True,
17
+ allow_methods=["*"],
18
+ allow_headers=["*"],
19
+ )
20
+
21
+ app.mount("/rag/static", StaticFiles(directory="./source_docs"), name="static")
22
  @app.get("/")
23
  async def redirect_root_to_docs():
24
  return RedirectResponse("/docs")
frontend/.gitignore ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2
+
3
+ # dependencies
4
+ /node_modules
5
+ /.pnp
6
+ .pnp.js
7
+
8
+ # testing
9
+ /coverage
10
+
11
+ # production
12
+ /build
13
+
14
+ # misc
15
+ .DS_Store
16
+ .env.local
17
+ .env.development.local
18
+ .env.test.local
19
+ .env.production.local
20
+
21
+ npm-debug.log*
22
+ yarn-debug.log*
23
+ yarn-error.log*
frontend/README.md ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Getting Started with Create React App
2
+
3
+ This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
4
+
5
+ ## Available Scripts
6
+
7
+ In the project directory, you can run:
8
+
9
+ ### `npm start`
10
+
11
+ Runs the app in the development mode.\
12
+ Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
13
+
14
+ The page will reload if you make edits.\
15
+ You will also see any lint errors in the console.
16
+
17
+ ### `npm test`
18
+
19
+ Launches the test runner in the interactive watch mode.\
20
+ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
21
+
22
+ ### `npm run build`
23
+
24
+ Builds the app for production to the `build` folder.\
25
+ It correctly bundles React in production mode and optimizes the build for the best performance.
26
+
27
+ The build is minified and the filenames include the hashes.\
28
+ Your app is ready to be deployed!
29
+
30
+ See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
31
+
32
+ ### `npm run eject`
33
+
34
+ **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
35
+
36
+ If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
37
+
38
+ Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
39
+
40
+ You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
41
+
42
+ ## Learn More
43
+
44
+ You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
45
+
46
+ To learn React, check out the [React documentation](https://reactjs.org/).
frontend/package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
frontend/package.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "frontend",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "dependencies": {
6
+ "@microsoft/fetch-event-source": "^2.0.1",
7
+ "@testing-library/jest-dom": "^5.17.0",
8
+ "@testing-library/react": "^13.4.0",
9
+ "@testing-library/user-event": "^13.5.0",
10
+ "@types/jest": "^27.5.2",
11
+ "@types/node": "^16.18.76",
12
+ "@types/react": "^18.2.48",
13
+ "@types/react-dom": "^18.2.18",
14
+ "react": "^18.2.0",
15
+ "react-dom": "^18.2.0",
16
+ "react-scripts": "5.0.1",
17
+ "typescript": "^4.9.5",
18
+ "web-vitals": "^2.1.4"
19
+ },
20
+ "scripts": {
21
+ "start": "react-scripts start",
22
+ "build": "react-scripts build",
23
+ "test": "react-scripts test",
24
+ "eject": "react-scripts eject"
25
+ },
26
+ "eslintConfig": {
27
+ "extends": [
28
+ "react-app",
29
+ "react-app/jest"
30
+ ]
31
+ },
32
+ "browserslist": {
33
+ "production": [
34
+ ">0.2%",
35
+ "not dead",
36
+ "not op_mini all"
37
+ ],
38
+ "development": [
39
+ "last 1 chrome version",
40
+ "last 1 firefox version",
41
+ "last 1 safari version"
42
+ ]
43
+ },
44
+ "devDependencies": {
45
+ "tailwindcss": "^3.4.1"
46
+ }
47
+ }
frontend/public/favicon.ico ADDED
frontend/public/index.html ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
7
+ <meta name="theme-color" content="#000000" />
8
+ <meta
9
+ name="description"
10
+ content="Web site created using create-react-app"
11
+ />
12
+ <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
13
+ <!--
14
+ manifest.json provides metadata used when your web app is installed on a
15
+ user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
16
+ -->
17
+ <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
18
+ <!--
19
+ Notice the use of %PUBLIC_URL% in the tags above.
20
+ It will be replaced with the URL of the `public` folder during the build.
21
+ Only files inside the `public` folder can be referenced from the HTML.
22
+
23
+ Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
24
+ work correctly both with client-side routing and a non-root public URL.
25
+ Learn how to configure a non-root public URL by running `npm run build`.
26
+ -->
27
+ <title>React App</title>
28
+ </head>
29
+ <body>
30
+ <noscript>You need to enable JavaScript to run this app.</noscript>
31
+ <div id="root"></div>
32
+ <!--
33
+ This HTML file is a template.
34
+ If you open it directly in the browser, you will see an empty page.
35
+
36
+ You can add webfonts, meta tags, or analytics to this file.
37
+ The build step will place the bundled scripts into the <body> tag.
38
+
39
+ To begin the development, run `npm start` or `yarn start`.
40
+ To create a production bundle, use `npm run build` or `yarn build`.
41
+ -->
42
+ </body>
43
+ </html>
frontend/public/logo192.png ADDED
frontend/public/logo512.png ADDED
frontend/public/manifest.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "short_name": "React App",
3
+ "name": "Create React App Sample",
4
+ "icons": [
5
+ {
6
+ "src": "favicon.ico",
7
+ "sizes": "64x64 32x32 24x24 16x16",
8
+ "type": "image/x-icon"
9
+ },
10
+ {
11
+ "src": "logo192.png",
12
+ "type": "image/png",
13
+ "sizes": "192x192"
14
+ },
15
+ {
16
+ "src": "logo512.png",
17
+ "type": "image/png",
18
+ "sizes": "512x512"
19
+ }
20
+ ],
21
+ "start_url": ".",
22
+ "display": "standalone",
23
+ "theme_color": "#000000",
24
+ "background_color": "#ffffff"
25
+ }
frontend/public/robots.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # https://www.robotstxt.org/robotstxt.html
2
+ User-agent: *
3
+ Disallow:
frontend/src/App.css ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .App {
2
+ text-align: center;
3
+ }
4
+
5
+ .App-logo {
6
+ height: 40vmin;
7
+ pointer-events: none;
8
+ }
9
+
10
+ @media (prefers-reduced-motion: no-preference) {
11
+ .App-logo {
12
+ animation: App-logo-spin infinite 20s linear;
13
+ }
14
+ }
15
+
16
+ .App-header {
17
+ background-color: #282c34;
18
+ min-height: 100vh;
19
+ display: flex;
20
+ flex-direction: column;
21
+ align-items: center;
22
+ justify-content: center;
23
+ font-size: calc(10px + 2vmin);
24
+ color: white;
25
+ }
26
+
27
+ .App-link {
28
+ color: #61dafb;
29
+ }
30
+
31
+ @keyframes App-logo-spin {
32
+ from {
33
+ transform: rotate(0deg);
34
+ }
35
+ to {
36
+ transform: rotate(360deg);
37
+ }
38
+ }
frontend/src/App.tsx ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, {useState} from 'react';
2
+ import './App.css';
3
+ import {fetchEventSource} from "@microsoft/fetch-event-source";
4
+
5
+
6
+ interface Message {
7
+ message: string;
8
+ isUser: boolean;
9
+ sources?: string[];
10
+ }
11
+
12
+ function App() {
13
+ const [inputValue, setInputValue] = useState("")
14
+ const [messages, setMessages] = useState<Message[]>([]);
15
+
16
+ const setPartialMessage = (chunk: string, sources: string[] = []) => {
17
+ setMessages(prevMessages => {
18
+ let lastMessage = prevMessages[prevMessages.length - 1];
19
+ if (prevMessages.length === 0 || !lastMessage.isUser) {
20
+ return [...prevMessages.slice(0, -1), {
21
+ message: lastMessage.message + chunk,
22
+ isUser: false,
23
+ sources: lastMessage.sources ? [...lastMessage.sources, ...sources] : sources
24
+ }];
25
+ }
26
+
27
+ return [...prevMessages, {message: chunk, isUser: false, sources}];
28
+ })
29
+ }
30
+
31
+ function handleReceiveMessage(data: string) {
32
+ let parsedData = JSON.parse(data);
33
+
34
+ if (parsedData.answer) {
35
+ setPartialMessage(parsedData.answer.content)
36
+ }
37
+
38
+ if (parsedData.docs) {
39
+ setPartialMessage("", parsedData.docs.map((doc: any) => doc.metadata.source))
40
+ }
41
+ }
42
+
43
+ const handleSendMessage = async (message: string) => {
44
+ setInputValue("")
45
+
46
+ setMessages(prevMessages => [...prevMessages, {message, isUser: true}]);
47
+
48
+ await fetchEventSource(`${"http://localhost:8000"}/rag/stream`, {
49
+ method: 'POST',
50
+ headers: {
51
+ 'Content-Type': 'application/json',
52
+ },
53
+ body: JSON.stringify({
54
+ input: {
55
+ question: message,
56
+ }
57
+ }),
58
+ onmessage(event) {
59
+ if (event.event === "data") {
60
+ handleReceiveMessage(event.data);
61
+ }
62
+ },
63
+ })
64
+ }
65
+
66
+ const handleKeyPress = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
67
+ if (event.key === "Enter" && !event.shiftKey) {
68
+ handleSendMessage(inputValue.trim())
69
+ }
70
+ }
71
+
72
+ function formatSource(source: string) {
73
+ return source.split("/").pop() || "";
74
+ }
75
+
76
+ return (
77
+ <div className="min-h-screen bg-gray-900 flex flex-col">
78
+ <header className="bg-gray-800 text-white text-center p-4">
79
+ Epic v. Apple Legal Assistant
80
+ </header>
81
+ <main className="flex-grow container mx-auto p-4 flex-col">
82
+ <div className="flex-grow bg-gray-700 shadow overflow-hidden sm:rounded-lg">
83
+ <div className="border-b border-gray-600 p-4">
84
+ {messages.map((msg, index) => (
85
+ <div key={index}
86
+ className={`p-3 my-3 rounded-lg text-white ml-auto ${msg.isUser ? "bg-gray-800" : "bg-gray-900"}`}>
87
+ {msg.message}
88
+ {/* Source */}
89
+ {!msg.isUser && (
90
+ <div className={"text-xs"}>
91
+ <hr className="border-b mt-5 mb-5"></hr>
92
+ {msg.sources?.map((source, index) => (
93
+ <div>
94
+ <a
95
+ target="_blank"
96
+ download
97
+ href={`${"http://localhost:8000"}/rag/static/${encodeURI(formatSource(source))}`}
98
+ rel="noreferrer"
99
+ >{formatSource(source)}</a>
100
+ </div>
101
+ ))}
102
+ </div>
103
+ )}
104
+ </div>
105
+ ))}
106
+ </div>
107
+ <div className="p-4 bg-gray-800">
108
+ <textarea
109
+ className="form-textarea w-full p-2 border rounded text-white bg-gray-900 border-gray-600 resize-none h-auto"
110
+ placeholder="Enter your message here..."
111
+ onKeyUp={handleKeyPress}
112
+ onChange={(e) => setInputValue(e.target.value)}
113
+ value={inputValue}
114
+ ></textarea>
115
+ <button
116
+ className="mt-2 bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded"
117
+ onClick={() => handleSendMessage(inputValue.trim())}
118
+ >
119
+ Send
120
+ </button>
121
+ </div>
122
+ </div>
123
+
124
+ </main>
125
+ <footer className="bg-gray-800 text-white text-center p-4 text-xs">
126
+ *AI Agents can make mistakes. Consider checking important information.
127
+ <br/>
128
+ All training data derived from public records
129
+ <br/>
130
+ <br/>
131
+ © 2024 Focused Labs
132
+ </footer>
133
+
134
+ </div>
135
+ );
136
+ }
137
+
138
+ export default App;
frontend/src/index.css ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ @tailwind base;
2
+ @tailwind components;
3
+ @tailwind utilities;
frontend/src/index.tsx ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import ReactDOM from 'react-dom/client';
3
+ import './index.css';
4
+ import App from './App';
5
+ import reportWebVitals from './reportWebVitals';
6
+
7
+ const root = ReactDOM.createRoot(
8
+ document.getElementById('root') as HTMLElement
9
+ );
10
+ root.render(
11
+ <React.StrictMode>
12
+ <App />
13
+ </React.StrictMode>
14
+ );
15
+
16
+ // If you want to start measuring performance in your app, pass a function
17
+ // to log results (for example: reportWebVitals(console.log))
18
+ // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
19
+ reportWebVitals();
frontend/src/logo.svg ADDED
frontend/src/react-app-env.d.ts ADDED
@@ -0,0 +1 @@
 
 
1
+ /// <reference types="react-scripts" />
frontend/src/reportWebVitals.ts ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { ReportHandler } from 'web-vitals';
2
+
3
+ const reportWebVitals = (onPerfEntry?: ReportHandler) => {
4
+ if (onPerfEntry && onPerfEntry instanceof Function) {
5
+ import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
6
+ getCLS(onPerfEntry);
7
+ getFID(onPerfEntry);
8
+ getFCP(onPerfEntry);
9
+ getLCP(onPerfEntry);
10
+ getTTFB(onPerfEntry);
11
+ });
12
+ }
13
+ };
14
+
15
+ export default reportWebVitals;
frontend/tailwind.config.js ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ /** @type {import('tailwindcss').Config} */
2
+ module.exports = {
3
+ content: ["./src/**/*.{js,jsx,ts,tsx}"],
4
+ theme: {
5
+ extend: {},
6
+ },
7
+ plugins: [],
8
+ }
9
+
frontend/tsconfig.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es5",
4
+ "lib": [
5
+ "dom",
6
+ "dom.iterable",
7
+ "esnext"
8
+ ],
9
+ "allowJs": true,
10
+ "skipLibCheck": true,
11
+ "esModuleInterop": true,
12
+ "allowSyntheticDefaultImports": true,
13
+ "strict": true,
14
+ "forceConsistentCasingInFileNames": true,
15
+ "noFallthroughCasesInSwitch": true,
16
+ "module": "esnext",
17
+ "moduleResolution": "node",
18
+ "resolveJsonModule": true,
19
+ "isolatedModules": true,
20
+ "noEmit": true,
21
+ "jsx": "react-jsx"
22
+ },
23
+ "include": [
24
+ "src"
25
+ ]
26
+ }