├── DFCI-GPT4DFCI-Backend
├── app
│ ├── __init__.py
│ ├── utils.py
│ ├── models.py
│ └── main.py
├── tests
│ ├── test_add_messages.py
│ ├── test_get_convo.py
│ ├── test_get_messages.py
│ ├── test_create_completion.py
│ ├── conftest.py
│ ├── test_update_convo.py
│ ├── test_get_convos.py
│ └── test_create_convo.py
├── gunicorn.conf.py
├── Dockerfile
├── ocr-pipeline.yaml
├── pyproject.toml
└── README.md
├── DFCI-GPT4DFCI
├── src
│ ├── vite-env.d.ts
│ ├── components
│ │ ├── Layout
│ │ │ ├── index.ts
│ │ │ ├── LayoutDrawer.tsx
│ │ │ └── Layout.tsx
│ │ ├── Sidebar
│ │ │ ├── index.ts
│ │ │ └── Sidebar.tsx
│ │ ├── ConvoList
│ │ │ ├── index.ts
│ │ │ ├── ConvoList.tsx
│ │ │ └── ConvoListItem.tsx
│ │ ├── ModelSelect
│ │ │ ├── index.ts
│ │ │ └── ModelSelect.tsx
│ │ ├── OptionsMenu
│ │ │ ├── index.ts
│ │ │ ├── AboutModal.tsx
│ │ │ └── OptionsMenu.tsx
│ │ ├── UserProfile
│ │ │ ├── index.ts
│ │ │ └── UserProfile.tsx
│ │ ├── ConvoDisplay
│ │ │ ├── index.ts
│ │ │ └── ConvoDisplay.tsx
│ │ ├── LandingDisplay
│ │ │ ├── index.ts
│ │ │ ├── dfci-logo.jpg
│ │ │ └── LandingDisplay.tsx
│ │ ├── MessageBubble
│ │ │ ├── index.ts
│ │ │ └── MessageBubble.tsx
│ │ ├── ExpandableInput
│ │ │ ├── index.ts
│ │ │ ├── utils.ts
│ │ │ └── ExpandableInput.tsx
│ │ └── ConfirmationDialog
│ │ │ ├── index.ts
│ │ │ └── ConfirmationDialog.tsx
│ ├── utils.ts
│ ├── theme.ts
│ ├── hooks
│ │ ├── useAutoScrollToBottom.ts
│ │ ├── useConvos.ts
│ │ └── useAPI.ts
│ ├── main.tsx
│ ├── services
│ │ ├── UserService.ts
│ │ ├── AssistantService.ts
│ │ └── StorageService.ts
│ ├── models
│ │ └── index.ts
│ ├── assets
│ │ └── react.svg
│ └── App.tsx
├── public
│ └── favicon.ico
├── tsconfig.node.json
├── index.html
├── tests
│ ├── App.spec.ts
│ ├── ConvoList.spec.ts
│ ├── ExpandableInput.ts
│ └── mocks
│ │ ├── UserService.ts
│ │ ├── AssistantService.ts
│ │ └── StorageService.ts
├── vite.config.ts
├── tsconfig.json
├── README.md
├── package.json
└── playwright.config.ts
├── GPT4DFCI User Technical Training
└── GPT4DFCI Training v204.pdf
├── .github
└── ISSUE_TEMPLATE
│ └── bug_report.md
├── DFCI-GPT4DFCI-infra
├── README.md
└── infra-pulumi-alpha.py
├── CITATION.cff
├── README.md
└── LICENSE
/DFCI-GPT4DFCI-Backend/app/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI-Backend/tests/test_add_messages.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/vite-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/Layout/index.ts:
--------------------------------------------------------------------------------
1 | import Layout from "./Layout";
2 |
3 | export default Layout;
4 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/Sidebar/index.ts:
--------------------------------------------------------------------------------
1 | import Sidebar from "./Sidebar";
2 |
3 | export default Sidebar;
4 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/ConvoList/index.ts:
--------------------------------------------------------------------------------
1 | import ConvoList from "./ConvoList";
2 |
3 | export default ConvoList;
4 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Dana-Farber-AIOS/GPT4DFCI/HEAD/DFCI-GPT4DFCI/public/favicon.ico
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/ModelSelect/index.ts:
--------------------------------------------------------------------------------
1 | import ModelSelect from "./ModelSelect";
2 |
3 | export default ModelSelect;
4 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/OptionsMenu/index.ts:
--------------------------------------------------------------------------------
1 | import OptionsMenu from "./OptionsMenu";
2 |
3 | export default OptionsMenu;
4 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/UserProfile/index.ts:
--------------------------------------------------------------------------------
1 | import UserProfile from "./UserProfile";
2 |
3 | export default UserProfile;
4 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/ConvoDisplay/index.ts:
--------------------------------------------------------------------------------
1 | import ConvoDisplay from "./ConvoDisplay";
2 |
3 | export default ConvoDisplay;
4 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/LandingDisplay/index.ts:
--------------------------------------------------------------------------------
1 | import LandingDisplay from "./LandingDisplay";
2 |
3 | export default LandingDisplay;
4 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/MessageBubble/index.ts:
--------------------------------------------------------------------------------
1 | import MessageBubble from "./MessageBubble";
2 |
3 | export default MessageBubble;
4 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/ExpandableInput/index.ts:
--------------------------------------------------------------------------------
1 | import ExpandableInput from "./ExpandableInput";
2 |
3 | export default ExpandableInput;
4 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/ConfirmationDialog/index.ts:
--------------------------------------------------------------------------------
1 | import ConfirmationDialog from "./ConfirmationDialog";
2 |
3 | export default ConfirmationDialog;
4 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/LandingDisplay/dfci-logo.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Dana-Farber-AIOS/GPT4DFCI/HEAD/DFCI-GPT4DFCI/src/components/LandingDisplay/dfci-logo.jpg
--------------------------------------------------------------------------------
/GPT4DFCI User Technical Training/GPT4DFCI Training v204.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Dana-Farber-AIOS/GPT4DFCI/HEAD/GPT4DFCI User Technical Training/GPT4DFCI Training v204.pdf
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/tsconfig.node.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "composite": true,
4 | "skipLibCheck": true,
5 | "module": "ESNext",
6 | "moduleResolution": "bundler",
7 | "allowSyntheticDefaultImports": true
8 | },
9 | "include": ["vite.config.ts"]
10 | }
11 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI-Backend/gunicorn.conf.py:
--------------------------------------------------------------------------------
1 | # Gunicorn configuration file
2 | import multiprocessing
3 |
4 | max_requests = 1000
5 | max_requests_jitter = 50
6 |
7 | log_file = "-"
8 |
9 | bind = "0.0.0.0:3100"
10 |
11 | worker_class = "uvicorn.workers.UvicornWorker"
12 | workers = (multiprocessing.cpu_count() * 2) + 1
13 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/ExpandableInput/utils.ts:
--------------------------------------------------------------------------------
1 | export const numLineBreaks = (text: string) => {
2 | const pattern = /\n|\r\n|\r/g;
3 | const matches = text.match(pattern) || [];
4 |
5 | return matches.length;
6 | };
7 |
8 | export const numRows = (text: string, maxRows: number) => {
9 | return Math.min(Math.max(numLineBreaks(text) + 1, 1), maxRows);
10 | };
11 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | GPT4DFCI
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/utils.ts:
--------------------------------------------------------------------------------
1 | // eslint-disable-next-line @typescript-eslint/no-explicit-any
2 | export type Newable = { new (...args: any[]): T };
3 |
4 | export const throwResponseError = (response: Response) => {
5 | if (!response.ok) {
6 | throw new Error(
7 | `${response.statusText} (status: ${response.status}, type: ${response.type})`
8 | );
9 | }
10 | return response.json() as Promise;
11 | };
12 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI-Backend/Dockerfile:
--------------------------------------------------------------------------------
1 | # syntax=docker/dockerfile:1
2 |
3 | FROM python:3.10
4 |
5 | WORKDIR /code
6 |
7 | COPY pyproject.toml poetry.lock .
8 |
9 | RUN pip install "poetry==1.6.1"
10 | RUN poetry --version
11 | RUN poetry export --without-hashes --format=requirements.txt > requirements.txt
12 | RUN pip install --no-cache-dir --upgrade -r requirements.txt
13 |
14 | COPY . .
15 |
16 | EXPOSE 3100
17 |
18 | CMD ["gunicorn", "app.main:app"]
19 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/theme.ts:
--------------------------------------------------------------------------------
1 | import "@fontsource/inter/400.css";
2 | import "@fontsource/inter/500.css";
3 | import "@fontsource/inter/600.css";
4 | import "@fontsource/inter/700.css";
5 |
6 | import { extendTheme } from "@chakra-ui/react";
7 |
8 | const colors = {};
9 | const fonts = {
10 | heading: `'Inter', sans-serif`,
11 | body: `'Inter', sans-serif`,
12 | };
13 |
14 | const theme = extendTheme({ colors, fonts });
15 |
16 | export default theme;
17 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/tests/App.spec.ts:
--------------------------------------------------------------------------------
1 | import { test, expect } from "@playwright/test";
2 |
3 | test("page has GPT4DFCI in title", async ({ page }) => {
4 | await page.goto("/");
5 |
6 | await expect(page).toHaveTitle(/GPT4DFCI/);
7 | });
8 |
9 | test("landing display appears on page load", async ({ page }) => {
10 | await page.goto("/");
11 |
12 | const LandingDisplay = await page.getByTestId("landing-display");
13 |
14 | await expect(LandingDisplay).toBeVisible();
15 | });
16 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/vite.config.ts:
--------------------------------------------------------------------------------
1 | import { defineConfig } from "vite";
2 | import react from "@vitejs/plugin-react";
3 | import path from "path";
4 |
5 | // https://vitejs.dev/config/
6 | export default defineConfig({
7 | plugins: [react()],
8 | resolve: {
9 | alias: {
10 | "@": path.resolve(__dirname, "./src"),
11 | },
12 | },
13 | build: {
14 | outDir: "build",
15 | },
16 | server: {
17 | watch: {
18 | usePolling: true,
19 | },
20 | },
21 | });
22 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI-Backend/app/utils.py:
--------------------------------------------------------------------------------
1 | import datetime
2 | import uuid
3 |
4 |
5 | def generate_uuid():
6 | return str(uuid.uuid4())
7 |
8 |
9 | def generate_timestamp():
10 | return datetime.datetime.utcnow().isoformat()
11 |
12 |
13 | def is_valid_uuid(to_check: str, version: int = 4):
14 | # reference: https://stackoverflow.com/a/33245493
15 | try:
16 | uuid_obj = uuid.UUID(to_check, version=version)
17 |
18 | except ValueError:
19 | return False
20 |
21 | return str(uuid_obj) == to_check
22 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/hooks/useAutoScrollToBottom.ts:
--------------------------------------------------------------------------------
1 | import { DependencyList, useEffect, useRef } from "react";
2 |
3 | const useAutoScrollToBottom = (dependencies: DependencyList) => {
4 | const ref = useRef(null);
5 | const scrollToBottom = () => {
6 | ref.current?.scrollIntoView({ behavior: "smooth" });
7 | };
8 |
9 | /* eslint-disable react-hooks/exhaustive-deps */
10 | useEffect(() => {
11 | scrollToBottom();
12 | }, dependencies);
13 |
14 | return ref;
15 | };
16 |
17 | export default useAutoScrollToBottom;
18 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/main.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import ReactDOM from "react-dom/client";
3 | import App from "./App.tsx";
4 | import { ChakraProvider } from "@chakra-ui/react";
5 | import theme from "./theme.ts";
6 |
7 | /* Reference for cssVarsRoot=":root"
8 | https://github.com/chakra-ui/chakra-ui/issues/6253 */
9 | ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
10 |
11 |
12 |
13 |
14 |
15 | );
16 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI-Backend/app/models.py:
--------------------------------------------------------------------------------
1 | from typing import List, Literal, Optional
2 | from pydantic import BaseModel
3 |
4 |
5 | class Message(BaseModel):
6 | id: str
7 | text: str
8 | sender: Literal["user", "assistant"]
9 | timestamp: str
10 | status: Literal["success", "error"]
11 | statusMessage: Optional[str] = None
12 |
13 |
14 | class Convo(BaseModel):
15 | id: Optional[str]
16 | userId: str
17 | title: str
18 | model: str
19 | timestamp: Optional[str] = None
20 | isArchived: bool = False
21 |
22 |
23 | class ChatCompletion(BaseModel):
24 | id: str
25 | object: str
26 | created: int
27 | model: str
28 | choices: List[dict]
29 | usage: dict
30 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI-Backend/ocr-pipeline.yaml:
--------------------------------------------------------------------------------
1 | trigger:
2 | - main # Change this to your branch name
3 |
4 | pr:
5 | - main
6 |
7 | jobs:
8 | - job: BuildAndPush
9 | pool:
10 | vmImage: 'ubuntu-latest'
11 | steps:
12 | - checkout: self
13 |
14 | # - task: Docker@2
15 | # inputs:
16 | # containerRegistry: ''
17 | # repository: 'myapp'
18 | # command: 'buildAndPush'
19 | # Dockerfile: '**/Dockerfile'
20 | # tags: '$(Build.BuildId)'
21 | - task: Docker@2
22 | inputs:
23 | containerRegistry: ${{ secrets.AZURE_CONTAINER_REGISTRY }}
24 | repository: ${{ secrets.AZURE_CONTAINER_REPOSITORY }}
25 | command: 'buildAndPush'
26 | Dockerfile: '**/Dockerfile'
27 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI-Backend/pyproject.toml:
--------------------------------------------------------------------------------
1 | [tool.poetry]
2 | name = "dfci-GPT4DFCI-backend"
3 | version = "0.1.0"
4 | description = ""
5 | authors = ["Your Name "]
6 | readme = "README.md"
7 | packages = [{include = "app"}]
8 |
9 | [tool.poetry.dependencies]
10 | python = "^3.10"
11 | azure-cosmos = "^4.5.0"
12 | azure-identity = "^1.14.0"
13 | fastapi = "^0.101.1"
14 | uvicorn = {extras = ["standard"], version = "^0.23.2"}
15 | python-dotenv = "^1.0.0"
16 | gunicorn = "^21.2.0"
17 | openai = "^0.27.8"
18 | mypy = "^1.5.1"
19 |
20 |
21 | [tool.poetry.group.dev.dependencies]
22 | ruff = "^0.0.284"
23 | black = "^23.7.0"
24 | pytest = "^7.4.0"
25 | httpx = "^0.24.1"
26 |
27 |
28 | [build-system]
29 | requires = ["poetry-core"]
30 | build-backend = "poetry.core.masonry.api"
31 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "ES2020",
4 | "useDefineForClassFields": true,
5 | "lib": ["ES2020", "DOM", "DOM.Iterable"],
6 | "module": "ESNext",
7 | "skipLibCheck": true,
8 |
9 | /* Bundler mode */
10 | "moduleResolution": "bundler",
11 | "allowImportingTsExtensions": true,
12 | "resolveJsonModule": true,
13 | "isolatedModules": true,
14 | "noEmit": true,
15 | "jsx": "react-jsx",
16 |
17 | /* Linting */
18 | "strict": true,
19 | "noUnusedLocals": true,
20 | "noUnusedParameters": true,
21 | "noFallthroughCasesInSwitch": true,
22 |
23 | /* For alias */
24 | "paths": {
25 | "@/*": ["./src/*", "./dist/*"]
26 | }
27 | },
28 | "include": ["src", "tests"],
29 | "references": [{ "path": "./tsconfig.node.json" }]
30 | }
31 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/ModelSelect/ModelSelect.tsx:
--------------------------------------------------------------------------------
1 | import { GPTModel } from "@/models";
2 | import { Select, SelectProps } from "@chakra-ui/react";
3 |
4 | interface ModelSelectProps extends Omit {
5 | value: GPTModel;
6 | options: GPTModel[];
7 | onChange: (model: GPTModel) => void;
8 | }
9 |
10 | const ModelSelect = ({
11 | value,
12 | options,
13 | onChange,
14 | ...props
15 | }: ModelSelectProps): JSX.Element => {
16 | return (
17 |
29 | );
30 | };
31 |
32 | export default ModelSelect;
33 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/tests/ConvoList.spec.ts:
--------------------------------------------------------------------------------
1 | import { test, expect } from "@playwright/test";
2 |
3 | test("new list item is created when prompt is submitted", async ({ page }) => {
4 | await page.goto("/");
5 |
6 | const countBefore = await page
7 | .getByTestId("convo-list")
8 | .getByRole("listitem")
9 | .count();
10 |
11 | console.log(`Count before ${countBefore}`);
12 | const PromptInput = await page.getByTestId("prompt-input");
13 |
14 | await PromptInput.click();
15 | await PromptInput.fill("Hello, world");
16 | await PromptInput.press("Enter");
17 |
18 | const countAfter = await page
19 | .getByTestId("convo-list")
20 | .getByRole("listitem")
21 | .count();
22 |
23 | await expect(countAfter).toBe(countBefore + 1);
24 | });
25 |
26 | // test("archive list item works", async ({ page }) => {
27 | // });
28 |
29 | // test("delete list item works", async ({ page }) => {
30 | // });
31 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/OptionsMenu/AboutModal.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | Modal,
3 | ModalBody,
4 | ModalCloseButton,
5 | ModalContent,
6 | ModalFooter,
7 | ModalHeader,
8 | ModalOverlay,
9 | UseDisclosureReturn,
10 | } from "@chakra-ui/react";
11 |
12 | interface AboutModalProps {
13 | disclosure: UseDisclosureReturn;
14 | }
15 |
16 | const AboutModal = ({ disclosure }: AboutModalProps): JSX.Element => {
17 | const { isOpen, onClose } = disclosure;
18 |
19 | return (
20 |
21 |
22 |
23 | About GPT4DFCI
24 |
25 | (Content goes here.)
26 |
27 |
28 |
29 | );
30 | };
31 |
32 | export default AboutModal;
33 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI-Backend/README.md:
--------------------------------------------------------------------------------
1 | # DFCI-GPT4DFCI-Backend
2 |
3 | ## Development setup
4 |
5 | 1. Install [Poetry](https://python-poetry.org/docs/)
6 | 2. Run `poetry install` in the project root
7 | 3. Run `poetry shell` to activate the virtual environment (also creates a sub-shell)
8 | 4. Run `uvnicorn main:app --reload` to start the local server
9 | 5. If the command was successful, http://127.0.0.1:8000/docs should show a Swagger/OpenAPI docs page
10 |
11 | ## Build notes
12 | https://learn.microsoft.com/en-us/azure/developer/python/tutorial-containerize-simple-web-app-for-app-service?tabs=web-app-fastapi
13 |
14 | * The `gunicorn.conf.py` file is from this tutorial.
15 | * Startup command is `gunicorn main:app`
16 |
17 | **How to export requirements.txt (if needed for build step)**
18 | ```
19 | poetry export --without-hashes --format=requirements.txt > requirements.txt
20 | ```
21 |
22 |
23 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 | - OS: [e.g. iOS]
28 | - Browser [e.g. chrome, safari]
29 | - Version [e.g. 22]
30 |
31 | **Smartphone (please complete the following information):**
32 | - Device: [e.g. iPhone6]
33 | - OS: [e.g. iOS8.1]
34 | - Browser [e.g. stock browser, safari]
35 | - Version [e.g. 22]
36 |
37 | **Additional context**
38 | Add any other context about the problem here.
39 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/UserProfile/UserProfile.tsx:
--------------------------------------------------------------------------------
1 | import { User } from "@/models";
2 | import { Avatar, Flex, Text } from "@chakra-ui/react";
3 |
4 | interface UserSettingsProps {
5 | user?: User;
6 | }
7 |
8 | const UserSettings = ({ user }: UserSettingsProps): JSX.Element => {
9 | return (
10 |
19 |
20 |
21 |
22 | {user ? `${user?.displayName}` : "Loading user..."}
23 |
24 |
25 | {user?.email}
26 |
27 |
28 |
29 | );
30 | };
31 |
32 | export default UserSettings;
33 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/hooks/useConvos.ts:
--------------------------------------------------------------------------------
1 | import { ConversationMetadata } from "@/models";
2 | import { useState } from "react";
3 |
4 | /** Hook for editing "convos" state */
5 | const useConvos = () => {
6 | const [convos, setConvos] = useState([]);
7 |
8 | const createConvo = (convo: ConversationMetadata) => {
9 | setConvos([...convos, convo]);
10 | };
11 |
12 | const editTitle = (convo: ConversationMetadata, title: string) => {
13 | const index = convos.findIndex((c) => c.id === convo.id);
14 |
15 | const edited = [...convos];
16 | edited[index].title = title;
17 |
18 | setConvos(edited);
19 | };
20 |
21 | const archiveConvo = (convo: ConversationMetadata) => {
22 | setConvos(convos.filter((_convo) => _convo.id !== convo.id));
23 | };
24 |
25 | const archiveAllConvos = () => {
26 | setConvos([]);
27 | };
28 |
29 | return {
30 | convos,
31 | createConvo,
32 | editTitle,
33 | archiveConvo,
34 | archiveAllConvos,
35 | setConvos,
36 | };
37 | };
38 |
39 | export default useConvos;
40 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI-Backend/tests/test_get_convo.py:
--------------------------------------------------------------------------------
1 | from azure.cosmos import ContainerProxy
2 | from fastapi.testclient import TestClient
3 | from app.utils import generate_uuid
4 |
5 |
6 | def test_correct_convo_is_returned(client: TestClient):
7 | container: ContainerProxy = client.app.state.cosmos_container
8 |
9 | convo = {
10 | "id": "does-not-matter",
11 | "userId": "does-not-matter",
12 | "title": "does-not-matter",
13 | "model": "does-not-matter",
14 | "timestamp": "does-not-matter",
15 | "isArchived": False,
16 | # omitting messages for convenience
17 | }
18 |
19 | container.create_item(convo)
20 |
21 | response = client.get(
22 | f"/convos/{convo['id']}", headers={"user-id": convo["userId"]}
23 | )
24 |
25 | assert response.status_code == 200
26 | assert response.json() == convo
27 |
28 |
29 | def test_error_is_thrown_when_no_convo_exists(client: TestClient):
30 | user_id = generate_uuid()
31 |
32 | response_get = client.get(
33 | "/convos/id-that-does-not-exist", headers={"user-id": user_id}
34 | )
35 |
36 | assert response_get.status_code == 404
37 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/tests/ExpandableInput.ts:
--------------------------------------------------------------------------------
1 | import { test, expect } from "@playwright/test";
2 |
3 | test("enter clears input", async ({ page }) => {
4 | await page.goto("/");
5 |
6 | const PromptInput = await page.getByTestId("prompt-input");
7 |
8 | await PromptInput.click();
9 | await PromptInput.fill("Hello, world");
10 | await PromptInput.press("Enter");
11 |
12 | await expect(PromptInput).toBeEmpty();
13 | });
14 |
15 | test("shift enter creates a new line", async ({ page }) => {
16 | await page.goto("/");
17 |
18 | const PromptInput = await page.getByTestId("prompt-input");
19 |
20 | await PromptInput.click();
21 | await PromptInput.fill("Hello, world");
22 | await PromptInput.press("Shift+Enter");
23 |
24 | await expect(PromptInput).toHaveText("Hello, world\n");
25 | });
26 |
27 | test("new line expands input", async ({ page }) => {
28 | await page.goto("/");
29 |
30 | const PromptInput = await page.getByTestId("prompt-input");
31 |
32 | await PromptInput.click();
33 | await PromptInput.fill("Hello, world");
34 | await PromptInput.press("Shift+Enter");
35 |
36 | await expect(PromptInput).toHaveJSProperty("rows", 2);
37 | });
38 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/tests/mocks/UserService.ts:
--------------------------------------------------------------------------------
1 | import { User } from "@/models";
2 | import { UserService } from "@/services/UserService";
3 |
4 | export class MockUserService implements UserService {
5 | getUser(): Promise {
6 | const user: User = {
7 | token: "abcdef",
8 | displayName: "xxx",
9 | email: "xxx@DFCI.HARVARD.EDU",
10 | };
11 |
12 | const msToSleep = 0;
13 | return new Promise((resolve) => setTimeout(resolve, msToSleep)).then(
14 | () => user
15 | );
16 | }
17 | }
18 |
19 | export class UserServiceWithDelay implements UserService {
20 | getUser(): Promise {
21 | const user: User = {
22 | token: "",
23 | displayName: "xxx",
24 | email: "xxx@DFCI.HARVARD.EDU",
25 | };
26 |
27 | const msToSleep = 1000;
28 | return new Promise((resolve) => setTimeout(resolve, msToSleep)).then(
29 | () => user
30 | );
31 | }
32 | }
33 |
34 | export class UserServiceWithError implements UserService {
35 | getUser(): Promise {
36 | return new Promise((_, reject) => reject("Error fetching user."));
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/services/UserService.ts:
--------------------------------------------------------------------------------
1 | import { User } from "@/models";
2 |
3 | export interface UserService {
4 | getUser(): Promise;
5 | }
6 |
7 | export class AADUserService implements UserService {
8 | async getUser(): Promise {
9 | const getUserData = (response: any) => {
10 | const data = response[0];
11 |
12 | let claims = data["user_claims"];
13 |
14 | // reformat
15 | claims = claims.reduce((result: any, claim: any) => {
16 | result[claim["typ"]] = claim["val"];
17 |
18 | return result;
19 | }, {});
20 |
21 | const user = {
22 | token: data["access_token"],
23 | displayName: claims["name"],
24 | email: claims["preferred_username"],
25 | };
26 |
27 | return user;
28 | };
29 | // https://learn.microsoft.com/en-us/azure/app-service/configure-authentication-user-identities#access-user-claims-using-the-api
30 | const response = fetch("/.auth/me")
31 | .then((response) => response.json())
32 | .then(getUserData);
33 |
34 | return response;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/tests/mocks/AssistantService.ts:
--------------------------------------------------------------------------------
1 | import {
2 | AssistantService,
3 | GetCompletionRequest,
4 | } from "@/services/AssistantService";
5 |
6 | export class MockAssistantService implements AssistantService {
7 | getCompletion(request: GetCompletionRequest) {
8 | if (request.messages.length <= 0) {
9 | throw Error("Request must include at least one message.");
10 | }
11 |
12 | const response = `This is a response to a chat with ${request.messages.length} messages.`;
13 | const msToSleep = 1000;
14 | return new Promise((resolve) => setTimeout(resolve, msToSleep)).then(
15 | () => response
16 | );
17 | }
18 | }
19 |
20 | export class MockAssistantServiceError implements AssistantService {
21 | getCompletion(request: GetCompletionRequest) {
22 | if (request.messages.length <= 0) {
23 | throw Error("Request must include at least one message.");
24 | }
25 |
26 | const msToSleep = 1000;
27 | return new Promise((resolve) => setTimeout(resolve, msToSleep)).then(
28 | () => {
29 | throw Error("This is a fake error.");
30 | }
31 | );
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/README.md:
--------------------------------------------------------------------------------
1 | # GPT4DFCI Front-end Code
2 |
3 | ## Stack
4 |
5 | - **Language:** [TypeScript](https://www.typescriptlang.org/)
6 | - **Package managment:** [Yarn](https://yarnpkg.com/)
7 | - **Build tool:** [Vite](https://vitejs.dev/)
8 | - **Frontend library:** [React](https://react.dev/)
9 | - **UI component library:** [Chakra UI](https://chakra-ui.com/)
10 | - **Icons:** [Lucide Icons](https://lucide.dev/)
11 | - **Linting and formatting:** [ESLint](https://eslint.org/), [Prettier](https://prettier.io/)
12 | - **Testing:** [Playwright](https://playwright.dev/)
13 |
14 | ## Development setup
15 |
16 | To install dependencies:
17 |
18 | ```
19 | yarn
20 | ```
21 |
22 | To run dev server:
23 |
24 | ```
25 | yarn dev
26 | ```
27 |
28 | ## Testing
29 |
30 | To run tests:
31 |
32 | ```
33 | yarn playwright test
34 | ```
35 |
36 | ## Type Checking
37 |
38 | To run type checks:
39 |
40 | ```
41 | yarn tsc
42 | ```
43 |
44 | ## Linting and Formatting
45 |
46 | To run linter:
47 |
48 | ```
49 | yarn lint
50 | ```
51 |
52 | To run formatter:
53 |
54 | ```
55 | yarn prettier --write .
56 | ```
57 |
58 |
59 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/ConvoDisplay/ConvoDisplay.tsx:
--------------------------------------------------------------------------------
1 | import useAutoScrollToBottom from "@/hooks/useAutoScrollToBottom";
2 | import { Conversation } from "@/models";
3 | import { Box, Flex } from "@chakra-ui/react";
4 | import MessageBubble from "@/components/MessageBubble";
5 | import { motion } from "framer-motion";
6 |
7 | interface ConvoDisplayProps {
8 | convo: Conversation;
9 | }
10 |
11 | const ConvoDisplay = ({ convo }: ConvoDisplayProps): JSX.Element => {
12 | // automatically scroll to bottom on new message
13 | const endOfMessages = useAutoScrollToBottom([convo.messages.length]);
14 | return (
15 |
16 | {convo.messages.map((message) => (
17 |
25 |
26 |
27 | ))}
28 |
29 |
30 | );
31 | };
32 |
33 | export default ConvoDisplay;
34 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI-Backend/tests/test_get_messages.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 | from azure.cosmos import ContainerProxy
3 | from fastapi.testclient import TestClient
4 | from app.models import Message
5 |
6 |
7 | def test_correct_messages_are_fetched(client: TestClient):
8 | container: ContainerProxy = client.app.state.cosmos_container
9 |
10 | convo = {
11 | "id": "does-not-matter",
12 | "userId": "does-not-matter",
13 | "title": "does-not-matter",
14 | "model": "does-not-matter",
15 | "timestamp": "does-not-matter",
16 | "isArchived": False,
17 | "messages": [
18 | {
19 | "id": "does-not-matter",
20 | "text": "first message",
21 | "sender": "user",
22 | "timestamp": "does-not-matter",
23 | "status": "success",
24 | "statusMessage": None,
25 | }
26 | ],
27 | }
28 |
29 | container.create_item(convo)
30 |
31 | response = client.get(
32 | f"/convos/{convo['id']}/messages",
33 | headers={"user-id": convo["userId"]},
34 | )
35 |
36 | assert response.status_code == 200
37 |
38 | messages: List[Message] = response.json()
39 |
40 | assert messages == convo["messages"]
41 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/services/AssistantService.ts:
--------------------------------------------------------------------------------
1 | import { Message } from "@/models";
2 | import { throwResponseError } from "@/utils";
3 |
4 | export interface GetCompletionRequest {
5 | messages: Message[];
6 | deployment_name: string;
7 | }
8 |
9 | export interface AssistantService {
10 | getCompletion(request: GetCompletionRequest): Promise;
11 | }
12 |
13 | export class OpenAIAssistantService implements AssistantService {
14 | async getCompletion(request: GetCompletionRequest): Promise {
15 | const endpoint = `${GPT4DFCI_API_ENDPOINT}?deployment_name=${request.deployment_name}`;
16 | const options = {
17 | method: "POST",
18 | headers: {
19 | "Content-Type": "application/json",
20 | "Ocp-Apim-Subscription-Key": ${OCP_APIM_SUBSCRIPTION_KEY},
21 | },
22 | body: JSON.stringify(request.messages),
23 | };
24 | return fetch(endpoint, options)
25 | .then(
26 | throwResponseError<{
27 | choices: { message: { content: string } }[];
28 | }>
29 | )
30 | .then((response) => {
31 | return response.choices[0].message.content;
32 | });
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/Layout/LayoutDrawer.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | Box,
3 | BoxProps,
4 | Drawer,
5 | DrawerCloseButton,
6 | DrawerContent,
7 | DrawerOverlay,
8 | IconButton,
9 | useDisclosure,
10 | } from "@chakra-ui/react";
11 | import { Menu } from "lucide-react";
12 | import { useRef } from "react";
13 |
14 | const LayoutDrawer = ({ children, ...props }: BoxProps): JSX.Element => {
15 | const { isOpen, onOpen, onClose } = useDisclosure();
16 | const buttonRef = useRef(null);
17 |
18 | return (
19 |
20 | }
24 | aria-label="menu-toggle"
25 | variant="ghost"
26 | />
27 |
33 |
34 |
35 |
36 | {children}
37 |
38 |
39 |
40 | );
41 | };
42 |
43 | export default LayoutDrawer;
44 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI-infra/README.md:
--------------------------------------------------------------------------------
1 | # GPT4DFCI Infrastructure
2 |
3 | This is alpha code provided as an example. What we ended up doing for v1.0 is to have 3 subscriptions; in the lowest one we would create manually Azure resources, configure them in detail, and export complete Azure ARM Template. These ARM files were then used to deploy in the other two subscriptions (one dedicated to testing and the other to production). The following code is based on the Pulumi-Azure interface and it aims at automating this process.
4 |
5 | ## Prerequisites
6 |
7 | ### Create a project folder
8 |
9 | ### Login into Azure
10 |
11 | `az login`
12 |
13 | ### Login into pulumi
14 |
15 | `pulumi login`
16 |
17 | ### Crete a new pulumi-azure project
18 |
19 | `pulumi new azure-python`
20 |
21 | ### Install required libraries
22 |
23 | `pip install pulumi pulumi_azure pulumi_azure_native`
24 |
25 | ## Run the deployment
26 |
27 | ### Replace `__main__.py` content with [`infra-pulumi-alpha.py`](./infra-pulumi-alpha.py) content
28 |
29 | ### Bring up the infra
30 |
31 | `pulumi up`
32 |
33 | ## Toubleshooting
34 |
35 | ### Check the infra status
36 |
37 | `pulumi stack`
38 |
39 | ### Take down the infra
40 |
41 | `pulumi destroy`
42 |
43 | 
44 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "dfci-GPT4DFCI",
3 | "private": true,
4 | "version": "0.0.0",
5 | "type": "module",
6 | "scripts": {
7 | "dev": "vite",
8 | "build": "tsc && vite build",
9 | "lint": "eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
10 | "preview": "vite preview"
11 | },
12 | "dependencies": {
13 | "@chakra-ui/react": "^2.7.0",
14 | "@emotion/react": "^11.11.1",
15 | "@emotion/styled": "^11.11.0",
16 | "@fontsource-variable/inter": "^5.0.3",
17 | "@fontsource/inter": "^5.0.3",
18 | "framer-motion": "^10.12.16",
19 | "lucide-react": "^0.244.0",
20 | "react": "^18.2.0",
21 | "react-dom": "^18.2.0"
22 | },
23 | "devDependencies": {
24 | "@playwright/test": "^1.35.1",
25 | "@types/node": "^20.2.5",
26 | "@types/react": "^18.0.37",
27 | "@types/react-dom": "^18.0.11",
28 | "@typescript-eslint/eslint-plugin": "^5.59.0",
29 | "@typescript-eslint/parser": "^5.59.0",
30 | "@vitejs/plugin-react": "^4.0.0",
31 | "eslint": "^8.38.0",
32 | "eslint-plugin-react-hooks": "^4.6.0",
33 | "eslint-plugin-react-refresh": "^0.3.4",
34 | "prettier": "^2.8.8",
35 | "typescript": "^5.0.2",
36 | "vite": "^4.3.9"
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI-Backend/tests/test_create_completion.py:
--------------------------------------------------------------------------------
1 | from fastapi.testclient import TestClient
2 |
3 |
4 | def test_create_completion_returns_dict_with_expected_keys(client: TestClient):
5 | response = client.post(
6 | "/completion",
7 | params={"deployment_name": "gpt-35-turbo-0613"},
8 | json=[
9 | {
10 | "id": "",
11 | "text": "Tell me a joke about ChatGPT.",
12 | "sender": "user",
13 | "timestamp": "",
14 | "status": "success",
15 | "statusMessage": "",
16 | }
17 | ],
18 | )
19 |
20 | assert response.status_code == 200
21 |
22 | result = response.json()
23 |
24 | assert list(result.keys()) == [
25 | "id",
26 | "object",
27 | "created",
28 | "model",
29 | "choices",
30 | "usage",
31 | ]
32 |
33 |
34 | def test_missing_deployment_name_throws_error(client: TestClient):
35 | response = client.post(
36 | "/completion",
37 | json=[
38 | {
39 | "id": "",
40 | "text": "Tell me a joke about ChatGPT.",
41 | "sender": "user",
42 | "timestamp": "",
43 | "status": "success",
44 | "statusMessage": "",
45 | }
46 | ],
47 | )
48 |
49 | assert response.status_code == 422
50 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI-Backend/tests/conftest.py:
--------------------------------------------------------------------------------
1 | import logging
2 |
3 | from azure.cosmos import CosmosClient, PartitionKey
4 | from dotenv import dotenv_values
5 | from fastapi.testclient import TestClient
6 | import pytest
7 | from app.main import app
8 |
9 | config = dotenv_values(".env.test")
10 |
11 | AZURE_COSMOSDB_ENDPOINT = config["AZURE_COSMOSDB_ENDPOINT"]
12 | AZURE_COSMOSDB_KEY = config["AZURE_COSMOSDB_KEY"]
13 | AZURE_COSMOSDB_DATABASE = config["AZURE_COSMOSDB_DATABASE"]
14 | AZURE_COSMOSDB_CONTAINER = config["AZURE_COSMOSDB_CONTAINER"]
15 |
16 | logging.info(
17 | f"""
18 | Using Cosmos config:
19 | Endpoint: {AZURE_COSMOSDB_ENDPOINT}
20 | Database: {AZURE_COSMOSDB_DATABASE}
21 | Container: {AZURE_COSMOSDB_CONTAINER}
22 | """,
23 | )
24 |
25 |
26 | @pytest.fixture
27 | def test_container():
28 | try:
29 | db = CosmosClient(
30 | url=AZURE_COSMOSDB_ENDPOINT,
31 | credential=AZURE_COSMOSDB_KEY,
32 | ).get_database_client(database=AZURE_COSMOSDB_DATABASE)
33 |
34 | partition_key = PartitionKey(path="/userId")
35 | container = db.create_container_if_not_exists(
36 | id=AZURE_COSMOSDB_CONTAINER,
37 | partition_key=partition_key,
38 | )
39 |
40 | yield container
41 |
42 | finally:
43 | db.delete_container(container)
44 |
45 |
46 | @pytest.fixture
47 | def client(test_container):
48 | app.state.cosmos_container = test_container
49 | return TestClient(app)
50 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/LandingDisplay/LandingDisplay.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | Box,
3 | Flex,
4 | Image,
5 | ListItem,
6 | Text,
7 | UnorderedList,
8 | } from "@chakra-ui/react";
9 | import Logo from "./dfci-logo.jpg";
10 |
11 | const LandingDisplay = (): JSX.Element => {
12 | return (
13 |
20 |
21 |
22 | GPT4DFCI
23 |
24 |
35 | Welcome to GPT4DFCI, the DFCI instance of GPT. You may use PHI
36 | and PII in here provided:
37 |
44 | Some condition
45 | Some condition
46 |
47 |
48 |
49 | );
50 | };
51 |
52 | export default LandingDisplay;
53 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI-Backend/tests/test_update_convo.py:
--------------------------------------------------------------------------------
1 | from azure.cosmos import ContainerProxy
2 | from fastapi.testclient import TestClient
3 |
4 |
5 | def test_title_can_be_updated(client: TestClient):
6 | container: ContainerProxy = client.app.state.cosmos_container
7 |
8 | convo = {
9 | "id": "does-not-matter",
10 | "userId": "does-not-matter",
11 | "title": "does-not-matter",
12 | "model": "does-not-matter",
13 | "timestamp": "does-not-matter",
14 | "isArchived": False,
15 | "messages": [],
16 | }
17 |
18 | container.create_item(convo)
19 |
20 | update = {
21 | "id": "does-not-matter",
22 | "userId": "does-not-matter",
23 | "title": "should-not-matter",
24 | "model": "does-not-matter",
25 | "timestamp": "does-not-matter",
26 | "isArchived": False,
27 | "messages": [],
28 | }
29 |
30 | response = client.patch(
31 | f"/convos/{convo['id']}", headers={"user-id": convo["userId"]}, json=update
32 | )
33 |
34 | assert response.status_code == 200
35 |
36 | # try and fetch updated convo
37 | query = "SELECT * FROM convos c where \
38 | c.id = @convoId and \
39 | c.userId = @userId"
40 |
41 | params: list[dict[str, object]] = [
42 | {"name": "@convoId", "value": convo["id"]},
43 | {"name": "@userId", "value": convo["userId"]},
44 | ]
45 |
46 | results = container.query_items(
47 | query=query,
48 | parameters=params,
49 | enable_cross_partition_query=False,
50 | )
51 |
52 | results = list(results)
53 |
54 | assert len(results) == 1
55 | assert results[0]["title"] == update["title"]
56 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/OptionsMenu/OptionsMenu.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | Icon,
3 | IconButton,
4 | Menu,
5 | MenuButton,
6 | MenuItem,
7 | MenuList,
8 | useDisclosure,
9 | } from "@chakra-ui/react";
10 | import { Download, Info, MoreVertical } from "lucide-react";
11 | import AboutModal from "./AboutModal";
12 |
13 | interface OptionsMenuProps {
14 | archive: {
15 | onSubmit: () => void;
16 | isDisabled: boolean;
17 | };
18 | export: {
19 | onSubmit: () => void;
20 | };
21 | }
22 |
23 | const OptionsMenu = (props: OptionsMenuProps): JSX.Element => {
24 | const aboutDisclosure = useDisclosure();
25 |
26 | return (
27 | <>
28 |
52 |
53 | >
54 | );
55 | };
56 |
57 | export default OptionsMenu;
58 |
--------------------------------------------------------------------------------
/CITATION.cff:
--------------------------------------------------------------------------------
1 | cff-version: 1.2.0
2 | message: "Citation for this repository"
3 | authors:
4 | - family-names: Umeton
5 | given-names: Renato
6 | - family-names: Kwok
7 | given-names: Anne
8 | - family-names: Maurya
9 | given-names: Rahul
10 | - family-names: Leco
11 | given-names: Domenic
12 | - family-names: Lenane
13 | given-names: Naomi
14 | - family-names: Willcox
15 | given-names: Jennifer
16 | - family-names: Abel
17 | given-names: Gregory
18 | - family-names: Tolikas
19 | given-names: Mary
20 | - family-names: Johnson
21 | given-names: Jason
22 | title: "GPT-4 in a Cancer Center: Institute-Wide Deployment Challenges and Lessons Learned"
23 | date-released: 2024-03-15
24 | doi: 10.1056/AIcs2300191
25 | url: https://github.com/Dana-Farber-AIOS/GPT4DFCI
26 | preferred-citation:
27 | type: article
28 | authors:
29 | - family-names: Umeton
30 | given-names: Renato
31 | - family-names: Kwok
32 | given-names: Anne
33 | - family-names: Maurya
34 | given-names: Rahul
35 | - family-names: Leco
36 | given-names: Domenic
37 | - family-names: Lenane
38 | given-names: Naomi
39 | - family-names: Willcox
40 | given-names: Jennifer
41 | - family-names: Abel
42 | given-names: Gregory
43 | - family-names: Tolikas
44 | given-names: Mary
45 | - family-names: Johnson
46 | given-names: Jason
47 | doi: 10.1056/AIcs2300191
48 | journal: "NEJM AI"
49 | publisher: Massachusetts Medical Society
50 | month: 3
51 | year: 2024
52 | issue: 4
53 | volume: 1
54 | start: 10
55 | title: "GPT-4 in a Cancer Center: Institute-Wide Deployment Challenges and Lessons Learned"
56 | url: https://ai.nejm.org/doi/full/10.1056/AIcs2300191
57 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/models/index.ts:
--------------------------------------------------------------------------------
1 | export interface User {
2 | token: string;
3 | displayName: string;
4 | email: string;
5 | }
6 |
7 | export interface Message {
8 | id: string;
9 | conversationId: string;
10 | sender: Sender;
11 | text: string;
12 | timestamp: Date;
13 | status: MessageStatus;
14 | statusMessage?: string;
15 | }
16 |
17 | export enum MessageStatus {
18 | Success = "success",
19 | Error = "error",
20 | }
21 |
22 | export interface Conversation {
23 | id: string;
24 | messages: Message[];
25 | title: string;
26 | timestamp: Date;
27 | isArchived: boolean;
28 | model: GPTModel;
29 | }
30 |
31 | export type ConversationMetadata = Omit;
32 |
33 | export enum Sender {
34 | User = "user",
35 | Assistant = "assistant",
36 | }
37 |
38 | export enum GPTModel {
39 | GPT35Turbo = "gpt-3.5-turbo",
40 | GPT4 = "gpt-4",
41 | GPT4turbo = "gpt-4-turbo",
42 | }
43 |
44 | export const DEFAULT_MODEL = GPTModel.GPT35Turbo;
45 |
46 | export const modelColorScheme = (model: GPTModel) => {
47 | switch (model) {
48 | case GPTModel.GPT35Turbo:
49 | return "green";
50 | case GPTModel.GPT4:
51 | return "blue";
52 | case GPTModel.GPT4turbo:
53 | return "blue";
54 | default:
55 | return "gray";
56 | }
57 | };
58 |
59 | export const modelDeployment = (model: GPTModel) => {
60 | switch (model) {
61 | case GPTModel.GPT35Turbo:
62 | return "gpt-35-turbo-0613";
63 | case GPTModel.GPT4:
64 | return "gpt-4model";
65 | case GPTModel.GPT4turbo:
66 | return "gpt-4tmodel";
67 |
68 | default:
69 | return "";
70 | }
71 | };
72 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI-Backend/tests/test_get_convos.py:
--------------------------------------------------------------------------------
1 | from azure.cosmos import ContainerProxy
2 | from fastapi.testclient import TestClient
3 | from app.utils import generate_uuid
4 |
5 |
6 | def test_multiple_convos_are_retrieved(client: TestClient):
7 | user_id = generate_uuid()
8 |
9 | container: ContainerProxy = client.app.state.cosmos_container
10 |
11 | convo_a = {
12 | "id": "convo_a",
13 | "userId": user_id,
14 | "title": "convo_a",
15 | "model": "does-not-matter",
16 | "timestamp": "does-not-matter",
17 | "isArchived": False,
18 | # omitting messages for convenience
19 | }
20 |
21 | convo_b = {
22 | "id": "convo_b",
23 | "userId": user_id,
24 | "title": "convo_b",
25 | "model": "does-not-matter",
26 | "timestamp": "does-not-matter",
27 | "isArchived": False,
28 | # omitting messages for convenience
29 | }
30 |
31 | container.create_item(convo_a)
32 | container.create_item(convo_b)
33 |
34 | response = client.get("/convos", headers={"user-id": user_id})
35 |
36 | assert response.status_code == 200
37 | assert response.json() == [
38 | convo_a,
39 | convo_b,
40 | ]
41 |
42 |
43 | def test_nonexistent_user_returns_empty_list(client: TestClient):
44 | user_id = generate_uuid()
45 |
46 | response = client.get("/convos", headers={"user-id": user_id})
47 |
48 | assert response.status_code == 200
49 | assert response.json() == []
50 |
51 |
52 | def test_empty_user_id_throws_error(client):
53 | response = client.get("/convos", headers={"user-id": ""})
54 |
55 | assert response.status_code == 400
56 |
57 |
58 | def test_missing_user_id_throws_error(client):
59 | response = client.get("/convos")
60 |
61 | assert response.status_code == 422
62 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/ConvoList/ConvoList.tsx:
--------------------------------------------------------------------------------
1 | import { ConversationMetadata } from "@/models";
2 | import ConvoListItem from "./ConvoListItem";
3 | import { Box, Flex } from "@chakra-ui/react";
4 | import { motion } from "framer-motion";
5 |
6 | interface ConvoListProps {
7 | convos: ConversationMetadata[];
8 | activeConvo: ConversationMetadata;
9 | onSelect: (convo: ConversationMetadata) => void;
10 | onEdit: (convo: ConversationMetadata, newTitle: string) => void;
11 | onArchive: (convo: ConversationMetadata) => void;
12 | }
13 |
14 | const ConvoList = ({
15 | convos,
16 | activeConvo,
17 | onSelect,
18 | onEdit,
19 | onArchive,
20 | }: ConvoListProps): JSX.Element => {
21 | const isActive = (convo: ConversationMetadata) =>
22 | activeConvo !== undefined && convo.id === activeConvo.id;
23 | return (
24 |
25 | {convos
26 | .sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime())
27 | .map((convo) => (
28 |
35 |
42 |
43 | ))}
44 |
45 | );
46 | };
47 |
48 | export default ConvoList;
49 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/ExpandableInput/ExpandableInput.tsx:
--------------------------------------------------------------------------------
1 | import React, { useState } from "react";
2 | import { Textarea, TextareaProps } from "@chakra-ui/react";
3 | import { numRows } from "./utils";
4 |
5 | interface ExpandableInputProps extends TextareaProps {
6 | maxRows: number;
7 | isSubmitting?: boolean;
8 | }
9 |
10 | const ExpandableInput = ({
11 | isSubmitting = false,
12 | maxRows,
13 | ...props
14 | }: ExpandableInputProps) => {
15 | const [height, setHeight] = useState(1);
16 | const [value, setValue] = useState("");
17 |
18 | const onChange = (event: React.ChangeEvent) => {
19 | setValue(event.target.value);
20 | setHeight(numRows(event.target.value, maxRows));
21 |
22 | if (props.onChange) {
23 | props.onChange(event);
24 | }
25 | };
26 |
27 | // Submit on Enter (or Numpad Enter), but allow linebreak on Shift + Enter
28 | const onKeyDown = (event: React.KeyboardEvent) => {
29 | if (
30 | !event.shiftKey &&
31 | (event.key === "Enter" || event.key === "Numpad Enter")
32 | ) {
33 | event.preventDefault();
34 | onSubmit(event);
35 | }
36 | };
37 |
38 | const onSubmit = (event: React.FormEvent) => {
39 | if (!isSubmitting && value.length > 0) {
40 | if (props.onSubmit) {
41 | props.onSubmit(event);
42 | }
43 | setValue("");
44 | setHeight(1);
45 | }
46 | };
47 |
48 | return (
49 |
58 | );
59 | };
60 |
61 | export default ExpandableInput;
62 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/Sidebar/Sidebar.tsx:
--------------------------------------------------------------------------------
1 | import { Box, Flex } from "@chakra-ui/react";
2 |
3 | interface SidebarProps {
4 | Header: React.ReactNode;
5 | Body: React.ReactNode;
6 | Footer: React.ReactNode;
7 | }
8 |
9 | const backgroundColor = "gray.100";
10 | const borderColor = "gray.300";
11 | const paddingX = "4";
12 | const paddingY = "4";
13 |
14 | const Sidebar = ({ Header, Body, Footer }: SidebarProps): JSX.Element => {
15 | return (
16 |
26 |
27 |
32 | {Header}
33 |
34 |
39 |
40 |
41 | {Body}
42 |
43 |
44 |
49 |
54 | {Footer}
55 |
56 |
57 |
58 | );
59 | };
60 |
61 | export default Sidebar;
62 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/MessageBubble/MessageBubble.tsx:
--------------------------------------------------------------------------------
1 | import { Message, MessageStatus, Sender } from "@/models";
2 | import { Flex, Icon, Text } from "@chakra-ui/react";
3 | import { AlertCircle } from "lucide-react";
4 |
5 | interface MessageBubbleProps {
6 | message: Message;
7 | }
8 |
9 | const MessageBubble = ({ message }: MessageBubbleProps): JSX.Element => {
10 | return (
11 |
12 |
13 |
14 | {message.sender}
15 |
16 |
17 | {message.timestamp.toLocaleString()}
18 |
19 |
20 |
34 |
35 | {message.text}
36 |
37 |
38 |
46 |
47 |
48 | {message.statusMessage}
49 |
50 |
51 |
52 | );
53 | };
54 |
55 | export default MessageBubble;
56 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/Layout/Layout.tsx:
--------------------------------------------------------------------------------
1 | import { Box, Flex } from "@chakra-ui/react";
2 |
3 | interface LayoutProps {
4 | Sidebar: React.ReactNode;
5 | Content: React.ReactNode;
6 | Footer: React.ReactNode;
7 | }
8 |
9 | const Layout = ({ Sidebar, Content, Footer }: LayoutProps): JSX.Element => {
10 | return (
11 |
12 |
17 | {Sidebar}
18 |
19 |
27 |
33 | {Content}
34 |
35 |
41 |
46 |
54 | {Footer}
55 |
56 |
57 |
58 |
59 | );
60 | };
61 |
62 | export default Layout;
63 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/ConfirmationDialog/ConfirmationDialog.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | AlertDialog,
3 | AlertDialogBody,
4 | AlertDialogContent,
5 | AlertDialogFooter,
6 | AlertDialogHeader,
7 | AlertDialogOverlay,
8 | Button,
9 | UseDisclosureReturn,
10 | } from "@chakra-ui/react";
11 | import { RefObject } from "react";
12 |
13 | interface ConfirmationDialogProps {
14 | disclosure: UseDisclosureReturn;
15 | cancelRef: RefObject;
16 | onSubmit: () => void;
17 | header: React.ReactNode;
18 | body: React.ReactNode;
19 | submitText: string;
20 | }
21 |
22 | const ConfirmationDialog = ({
23 | disclosure,
24 | cancelRef,
25 | onSubmit,
26 | header,
27 | body,
28 | submitText,
29 | }: ConfirmationDialogProps): JSX.Element => (
30 |
35 |
36 |
37 |
38 | {header}
39 |
40 |
41 | {body}
42 |
43 |
44 |
51 |
62 |
63 |
64 |
65 |
66 | );
67 |
68 | export default ConfirmationDialog;
69 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/tests/mocks/StorageService.ts:
--------------------------------------------------------------------------------
1 | import { Conversation, ConversationMetadata, Message, User } from "@/models";
2 | import { StorageService } from "@/services/StorageService";
3 |
4 | export class MockStorageService implements StorageService {
5 | user: User;
6 | storage: Conversation[];
7 |
8 | constructor(user: User) {
9 | this.user = user;
10 | this.storage = [];
11 | }
12 |
13 | async getConvos() {
14 | console.log(`getConvos`);
15 | console.log(this.storage);
16 | return this.storage;
17 | }
18 | async createConvo(convo: ConversationMetadata) {
19 | const withMessages = { messages: [], ...convo };
20 |
21 | this.storage.push(withMessages);
22 | console.log(`createConvo`);
23 | console.log(this.storage);
24 | return convo;
25 | }
26 | async updateConvo(convo: ConversationMetadata) {
27 | const index = this.storage.findIndex((item) => item.id === convo.id);
28 | const storedConvo = this.storage[index];
29 |
30 | const updatedConvo = { ...storedConvo, ...convo };
31 |
32 | this.storage[index] = updatedConvo;
33 |
34 | console.log(`updateConvo: ${convo.id}`);
35 | console.log(this.storage);
36 | }
37 | async archiveConvo(convoId: Conversation["id"]) {
38 | const index = this.storage.findIndex((item) => item.id === convoId);
39 |
40 | this.storage[index].isArchived = true;
41 |
42 | console.log(`archiveConvo: ${convoId}`);
43 | console.log(this.storage);
44 | }
45 | async getMessages(convoId: Conversation["id"]) {
46 | const index = this.storage.findIndex((item) => item.id === convoId);
47 |
48 | console.log(`getMessages: ${convoId}`);
49 | console.log(this.storage[index].messages);
50 |
51 | return this.storage[index].messages;
52 | }
53 | async addMessages(convoId: Conversation["id"], messages: Message[]) {
54 | const index = this.storage.findIndex((item) => item.id === convoId);
55 |
56 | console.log(`addMessages: ${convoId}`);
57 |
58 | this.storage[index].messages.concat(messages);
59 | console.log(this.storage[index].messages);
60 |
61 | return this.storage[index].messages;
62 | }
63 | async archiveAllConvos() {
64 | this.storage.forEach((item) => {
65 | item.isArchived = true;
66 | });
67 |
68 | console.log(`archiveAllConvos`);
69 | console.log(this.storage);
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/playwright.config.ts:
--------------------------------------------------------------------------------
1 | import { defineConfig, devices } from "@playwright/test";
2 |
3 | /**
4 | * Read environment variables from file.
5 | * https://github.com/motdotla/dotenv
6 | */
7 | // require('dotenv').config();
8 |
9 | /**
10 | * See https://playwright.dev/docs/test-configuration.
11 | */
12 | export default defineConfig({
13 | testDir: "./tests",
14 | /* Run tests in files in parallel */
15 | fullyParallel: true,
16 | /* Fail the build on CI if you accidentally left test.only in the source code. */
17 | forbidOnly: !!process.env.CI,
18 | /* Retry on CI only */
19 | retries: process.env.CI ? 2 : 0,
20 | /* Opt out of parallel tests on CI. */
21 | workers: process.env.CI ? 1 : undefined,
22 | /* Reporter to use. See https://playwright.dev/docs/test-reporters */
23 | reporter: "html",
24 | /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
25 | use: {
26 | /* Base URL to use in actions like `await page.goto('/')`. */
27 | baseURL: "http://localhost:5173",
28 |
29 | /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
30 | trace: "on-first-retry",
31 | },
32 |
33 | /* Configure projects for major browsers */
34 | projects: [
35 | {
36 | name: "chromium",
37 | use: { ...devices["Desktop Chrome"] },
38 | },
39 |
40 | {
41 | name: "firefox",
42 | use: { ...devices["Desktop Firefox"] },
43 | },
44 |
45 | {
46 | name: "webkit",
47 | use: { ...devices["Desktop Safari"] },
48 | },
49 |
50 | /* Test against mobile viewports. */
51 | // {
52 | // name: 'Mobile Chrome',
53 | // use: { ...devices['Pixel 5'] },
54 | // },
55 | // {
56 | // name: 'Mobile Safari',
57 | // use: { ...devices['iPhone 12'] },
58 | // },
59 |
60 | /* Test against branded browsers. */
61 | // {
62 | // name: 'Microsoft Edge',
63 | // use: { ...devices['Desktop Edge'], channel: 'msedge' },
64 | // },
65 | // {
66 | // name: 'Google Chrome',
67 | // use: { ..devices['Desktop Chrome'], channel: 'chrome' },
68 | // },
69 | ],
70 |
71 | /* Run your local dev server before starting the tests */
72 | webServer: {
73 | command: "yarn dev",
74 | url: "http://localhost:5173",
75 | reuseExistingServer: !process.env.CI,
76 | },
77 | });
78 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/assets/react.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # GPT4DFCI 🤖
2 |
3 | **Welcome to the code repository for GPT4DFCI, a private and secure generative AI tool, based on GPT-4 and deployed for non-clinical use at Dana-Farber Cancer Institute.**
4 |
5 | *ℹ️ Tool requirements, usage policy, and training material are overseen by the broader Dana-Farber AI Governance Committee. The development of this tool is led by the Dana-Farber Informatics & Analytics Department.*
6 |
7 | This repository is organized in the following sections:
8 |
9 | - Manuscript & policy details accompanying this tool
10 | - Training material for the users
11 |
12 | - Front-end code - this is the application where the users place their queries and read the output
13 | - Back-end code that handles all requests from the application and routes all requests to other components
14 | - Infrastructure that was used to deploy this
15 | - GPT4DFCI API client - to use GPT4DFCI programmatically, within your application
16 | - License
17 | - Contact
18 |
19 | # 📄 Manuscript & policy
20 |
21 | 👉 Manuscript PDF
and Supplementary appendix
22 |
23 | Further material about this tool adoption is available on [NEJM AI](https://ai.nejm.org/stoken/default+domain/MBGFT6KIUT9AYKQNJB5Q/full?redirectUri=/doi/full/10.1056/AIcs2300191).
24 |
25 | 📣 Continue reading on [Dana-Farber press release](https://www.dana-farber.org/newsroom/news-releases/2024/private-and-secure-generative-ai-tool-supports-operations-and-research-at-dana-farber).
26 |
27 | # 🧑🎓 Training
28 |
29 | 👉 Here you will find the [training material](./GPT4DFCI%20User%20Technical%20Training/) that accompanied this tool deployment.
30 |
31 | # 💻 GPT4DFCI Front-end Code
32 |
33 |
34 |
35 | 👉 Code & instructions are in the [DFCI-GPT4DFCI](./DFCI-GPT4DFCI) folder.
36 |
37 | # ⌨ GPT4DFCI Backend Code
38 |
39 |
40 |
41 | 👉 Code & instructions are in the [DFCI-GPT4DFCI-Backend](./DFCI-GPT4DFCI-Backend) folder.
42 |
43 | # 🏗️ GPT4DFCI Infrastructure
44 |
45 | 
46 |
47 | 👉 Code & instructions are in the [DFCI-GPT4DFCI-infra](./DFCI-GPT4DFCI-infra) folder.
48 |
49 | # 🔌 API Usage
50 |
51 | 
52 |
53 | 👉 Code & instructions are in the [GPT4DFCI API](https://github.com/Dana-Farber-AIOS/GPT4DFCI-API) code repository.
54 |
55 | # 🎫 License
56 |
57 | The GNU GPL v2 version of GPT4DFCI is made available via Open Source licensing. The user is free to use, modify, and distribute under the terms of the GNU General Public License version 2.
58 |
59 | Commercial license options are available also, and include these additional features:
60 | - Accurate per-user monthly billing, based on actual Azure OpenAI token consumption
61 | - Log analytics to monitor application status and application adoption by the user base
62 | - Log analytics to detect and monitor power users and possibly malicious behavior (e.g., jailbreaking attempts)
63 | - Load balancing and retry logic to mitigate Azure OpenAI quota limits and ensure a smooth user experience
64 |
65 | # 📧 Contact
66 |
67 | Questions? Comments? Suggestions? Get in touch!
68 |
69 | innovation@dfci.harvard.edu
70 |
71 |
Dana-Farber personnel: please contact us through the [dedicated ticketing system](https://dfciservicerequest.dfci.harvard.edu/?RelayState=GPT4DFCI).
72 |
73 |
74 |
75 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/services/StorageService.ts:
--------------------------------------------------------------------------------
1 | import { Conversation, ConversationMetadata, Message, User } from "@/models";
2 |
3 | export interface StorageService {
4 | user: User;
5 |
6 | /** Fetch conversations for given user, without messages. */
7 | getConvos: () => Promise;
8 |
9 | /** Create a conversation in the database from the given object.
10 | *
11 | * The created conversation is returned in order to supply the ID
12 | * generated by the backend.
13 | */
14 | createConvo: (convo: ConversationMetadata) => Promise;
15 |
16 | /** Update the conversation with the given ID with the supplied values. */
17 | updateConvo: (convo: ConversationMetadata) => Promise;
18 |
19 | /** Mark the conversation with the given ID as "archived". */
20 | archiveConvo: (convoId: Conversation["id"]) => Promise;
21 |
22 | /** Mark all the user's conversations as "archived". */
23 | archiveAllConvos: () => Promise;
24 |
25 | /** Fetch messages for the conversation with the given ID. */
26 | getMessages: (convoId: Conversation["id"]) => Promise;
27 |
28 | /** Add message */
29 | addMessages: (
30 | convoId: Conversation["id"],
31 | messages: Message[]
32 | ) => Promise;
33 | }
34 |
35 | export class HTTPStorageService implements StorageService {
36 | user: User;
37 | endpoint: string;
38 |
39 | constructor(user: User, endpoint: string = `${HTTP_STORAGE_SERVICE_HOST}:${HTTP_STORAGE_SERVICE_PORT}`) {
40 | this.user = user;
41 | this.endpoint = endpoint;
42 | }
43 |
44 | async getConvos() {
45 | const options = {
46 | method: "GET",
47 | headers: {
48 | "Content-Type": "application/json",
49 | Authorization: `Bearer ${this.user.token}`,
50 | },
51 | };
52 |
53 | return fetch(`${this.endpoint}/convos`, options)
54 | .then((result) => result.json())
55 | .then((data) => data as ConversationMetadata[]);
56 | }
57 |
58 | async createConvo(convo: ConversationMetadata) {
59 | const options = {
60 | method: "POST",
61 | headers: {
62 | "Content-Type": "application/json",
63 | Authorization: `Bearer ${this.user.token}`,
64 | },
65 | body: JSON.stringify(convo),
66 | };
67 |
68 | return fetch(`${this.endpoint}/convos`, options)
69 | .then((result) => result.json())
70 | .then((data) => data as ConversationMetadata);
71 | }
72 |
73 | async updateConvo(convo: ConversationMetadata) {
74 | const options = {
75 | method: "PATCH",
76 | headers: {
77 | "Content-Type": "application/json",
78 | Authorization: `Bearer ${this.user.token}`,
79 | },
80 | body: JSON.stringify(convo),
81 | };
82 |
83 | await fetch(`${this.endpoint}/convos/${convo.id}`, options);
84 | }
85 |
86 | async archiveConvo(convoId: Conversation["id"]) {
87 | const options = {
88 | method: "PATCH",
89 | headers: {
90 | "Content-Type": "application/json",
91 | Authorization: `Bearer ${this.user.token}`,
92 | },
93 | body: JSON.stringify({
94 | id: convoId,
95 | isArchived: true,
96 | }),
97 | };
98 |
99 | await fetch(`${this.endpoint}/convos/${convoId}`, options);
100 | }
101 |
102 | async archiveAllConvos() {}
103 |
104 | async getMessages(convoId: Conversation["id"]) {
105 | const options = {
106 | method: "GET",
107 | headers: {
108 | "Content-Type": "application/json",
109 | Authorization: `Bearer ${this.user.token}`,
110 | },
111 | };
112 |
113 | return fetch(`${this.endpoint}/convos/${convoId}/messages`, options)
114 | .then((result) => result.json())
115 | .then((data) => data as Message[]);
116 | }
117 |
118 | async addMessages(convoId: Conversation["id"], messages: Message[]) {
119 | const options = {
120 | method: "POST",
121 | headers: {
122 | "Content-Type": "application/json",
123 | Authorization: `Bearer ${this.user.token}`,
124 | },
125 | body: JSON.stringify(messages),
126 | };
127 |
128 | return fetch(`${this.endpoint}/convos/${convoId}/messages`, options)
129 | .then((result) => result.json())
130 | .then((data) => data as Message[]);
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI-Backend/tests/test_create_convo.py:
--------------------------------------------------------------------------------
1 | from azure.cosmos import ContainerProxy
2 | from fastapi.testclient import TestClient
3 | from app.utils import generate_uuid, is_valid_uuid
4 |
5 |
6 | def test_item_is_created(client: TestClient):
7 | user_id = generate_uuid()
8 | response = client.post(
9 | "/convos",
10 | headers={"user-id": user_id},
11 | json={
12 | "id": "does-not-matter",
13 | "userId": user_id,
14 | "title": "does-not-matter",
15 | "model": "does-not-matter",
16 | "timestamp": "does-not-matter",
17 | "isArchived": False,
18 | },
19 | )
20 |
21 | convo = response.json()
22 |
23 | # try to fetch created convo
24 | container: ContainerProxy = client.app.state.cosmos_container
25 |
26 | query = "SELECT * FROM convos c where \
27 | c.id = @convoId and \
28 | c.userId = @userId"
29 |
30 | params: list[dict[str, object]] = [
31 | {"name": "@convoId", "value": convo["id"]},
32 | {"name": "@userId", "value": user_id},
33 | ]
34 |
35 | results = container.query_items(
36 | query=query,
37 | parameters=params,
38 | enable_cross_partition_query=False,
39 | )
40 |
41 | results = list(results)
42 |
43 | assert len(results) == 1
44 | assert results[0]["id"] == convo["id"]
45 |
46 |
47 | def test_valid_uuid_is_generated_for_id(client: TestClient):
48 | user_id = generate_uuid()
49 | response = client.post(
50 | "/convos",
51 | headers={"user-id": user_id},
52 | json={
53 | "id": "does-not-matter",
54 | "userId": user_id,
55 | "title": "does-not-matter",
56 | "model": "does-not-matter",
57 | "timestamp": "does-not-matter",
58 | "isArchived": False,
59 | },
60 | )
61 |
62 | convo = response.json()
63 |
64 | assert response.status_code == 200
65 | assert is_valid_uuid(convo["id"])
66 |
67 |
68 | def test_empty_message_list_is_created(client: TestClient):
69 | user_id = generate_uuid()
70 | response = client.post(
71 | "/convos",
72 | headers={"user-id": user_id},
73 | json={
74 | "id": "does-not-matter",
75 | "userId": user_id,
76 | "title": "does-not-matter",
77 | "model": "does-not-matter",
78 | "timestamp": "does-not-matter",
79 | "isArchived": False,
80 | },
81 | )
82 |
83 | convo = response.json()
84 |
85 | # try to fetch created messages
86 | container: ContainerProxy = client.app.state.cosmos_container
87 |
88 | query = "SELECT c.messages FROM convos c where \
89 | c.id = @convoId and \
90 | c.userId = @userId"
91 |
92 | params: list[dict[str, object]] = [
93 | {"name": "@convoId", "value": convo["id"]},
94 | {"name": "@userId", "value": user_id},
95 | ]
96 |
97 | results = container.query_items(
98 | query=query,
99 | parameters=params,
100 | enable_cross_partition_query=False,
101 | )
102 |
103 | results = list(results)
104 |
105 | assert len(results) == 1
106 | assert results[0]["messages"] == []
107 |
108 |
109 | def test_messages_in_body_are_ignored(client: TestClient):
110 | user_id = generate_uuid()
111 | response_post = client.post(
112 | "/convos",
113 | headers={"user-id": user_id},
114 | json={
115 | "id": "does-not-matter",
116 | "userId": user_id,
117 | "title": "does-not-matter",
118 | "messages": [
119 | {
120 | "id": generate_uuid(),
121 | "text": "does-not-matter",
122 | "sender": "user",
123 | "timestamp": "does-not-matter",
124 | "status": "success",
125 | "statusMessage": None,
126 | }
127 | ],
128 | "model": "does-not-matter",
129 | "timestamp": "does-not-matter",
130 | "isArchived": False,
131 | },
132 | )
133 |
134 | convo = response_post.json()
135 |
136 | # try to fetch created messages
137 | container: ContainerProxy = client.app.state.cosmos_container
138 |
139 | query = "SELECT c.messages FROM convos c where \
140 | c.id = @convoId and \
141 | c.userId = @userId"
142 |
143 | params: list[dict[str, object]] = [
144 | {"name": "@convoId", "value": convo["id"]},
145 | {"name": "@userId", "value": user_id},
146 | ]
147 |
148 | results = container.query_items(
149 | query=query,
150 | parameters=params,
151 | enable_cross_partition_query=False,
152 | )
153 |
154 | results = list(results)
155 |
156 | assert len(results) == 1
157 | assert results[0]["messages"] == []
158 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI-infra/infra-pulumi-alpha.py:
--------------------------------------------------------------------------------
1 | ##
2 | ## This is alpha code, generated with GPT4DFCI (a private and secure generative AI tool based on GPT4)
3 | ##
4 |
5 | import pulumi
6 | from pulumi_azure import core, appservice, containerregistry, storage
7 | from pulumi_azure_native import resources, cosmosdb, cognitive_services
8 |
9 | # Configuration
10 | config = pulumi.Config()
11 | location = config.require('location') # e.g., "WestUS2"
12 |
13 | # Create an Azure Resource Group
14 | resource_group = resources.ResourceGroup('resourceGroup',
15 | resource_group_name='my-resource-group',
16 | location=location)
17 |
18 | # Azure API Management (APIM)
19 | apim = cognitive_services.Account('apimService',
20 | account_name='myapimaccount',
21 | kind='api',
22 | sku=cognitive_services.SkuArgs(name='Consumption'),
23 | resource_group_name=resource_group.name,
24 | location=location)
25 |
26 | # Azure App Service
27 | app_service_plan = appservice.Plan('appServicePlan',
28 | resource_group_name=resource_group.name,
29 | kind='App',
30 | sku={'tier': 'Basic', 'size': 'B1'})
31 |
32 | app_service = appservice.AppService('appService',
33 | resource_group_name=resource_group.name,
34 | app_service_plan_id=app_service_plan.id)
35 |
36 | # Azure Container Registry
37 | acr = containerregistry.Registry('acr',
38 | resource_group_name=resource_group.name,
39 | sku='Basic',
40 | admin_enabled=True)
41 |
42 | # Azure Cosmos DB
43 | cosmosdb_account = cosmosdb.Account('cosmosdbAccount',
44 | resource_group_name=resource_group.name,
45 | kind='GlobalDocumentDB',
46 | database_account_offer_type='Standard',
47 | locations=[{
48 | 'locationName': resource_group.location,
49 | 'failoverPriority': 0,
50 | 'isZoneRedundant': False,
51 | }])
52 |
53 | # Azure Storage Account
54 | storage_account = storage.Account('storageAccount',
55 | resource_group_name=resource_group.name,
56 | account_tier='Standard',
57 | account_replication_type='LRS')
58 |
59 | # Create an Azure Cognitive Services Account for OpenAI
60 | # This needs to be updated with the latest model IDs from Azure page and associated model versions (eg, 0613)
61 | # https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models
62 | # Content-filter needs to be setup manually for each deployment
63 | openai_account = cognitive_services.Account('openaiAccount',
64 | account_name='myopenaiaccount',
65 | kind='OpenAI',
66 | sku=cognitive_services.SkuArgs(name='S0'),
67 | resource_group_name=resource_group.name,
68 | location=location,
69 | properties=cognitive_services.AccountPropertiesArgs(
70 | public_network_access='Enabled',
71 | ))
72 | # Function to deploy models
73 | def deploy_model(model_name, deployment_name):
74 | return cognitive_services.Deployment(f'{deployment_name}Deployment',
75 | deployment_name=deployment_name,
76 | account_name=openai_account.name,
77 | resource_group_name=resource_group.name,
78 | properties=cognitive_services.DeploymentPropertiesArgs(
79 | model=cognitive_services.DeploymentModelArgs(
80 | format="OpenAI",
81 | name=model_name,
82 | ),
83 | ))
84 | # Deploy models
85 | models = {
86 | 'gpt-3.5-turbo-16k': 'modelGpt35Turbo-api-16k', #API users
87 | 'gpt-3.5-turbo': 'modelGpt35Turbo-4k',
88 | 'gpt-4': 'modelGpt4-8k',
89 | 'gpt-4-32k': 'modelGpt4-api-32k', #API users
90 | 'gpt-4-1106-preview': 'modelGpt4Turbo-128k',
91 | 'gpt-4-1106-preview': 'modelGpt4Turbo-api-128k', #API users
92 | }
93 | for model_name, deployment_name in models.items():
94 | deployed_model = deploy_model(model_name, deployment_name)
95 | pulumi.export(f'deployed_{deployment_name}_name', deployed_model.name)
96 |
97 |
98 | ## !pulumi up
99 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/App.tsx:
--------------------------------------------------------------------------------
1 | import { motion } from "framer-motion";
2 | import { Button, Flex } from "@chakra-ui/react";
3 | import ConvoList from "@/components/ConvoList";
4 | import ConvoDisplay from "@/components/ConvoDisplay";
5 | import ExpandableInput from "@/components/ExpandableInput";
6 | import LandingDisplay from "@/components/LandingDisplay";
7 | import Layout from "@/components/Layout";
8 | import ModelSelect from "@/components/ModelSelect";
9 | import OptionsMenu from "@/components/OptionsMenu";
10 | import Sidebar from "@/components/Sidebar";
11 | import UserProfile from "@/components/UserProfile";
12 | import useAPI from "@/hooks/useAPI";
13 | import { GPTModel } from "@/models";
14 | import { Newable } from "@/utils";
15 | import { AADUserService, UserService } from "@/services/UserService";
16 | import { MockUserService } from "../tests/mocks/UserService";
17 | import { MockStorageService } from "../tests/mocks/StorageService";
18 | import {
19 | AssistantService,
20 | OpenAIAssistantService,
21 | } from "@/services/AssistantService";
22 |
23 | function App() {
24 | let UserService: Newable;
25 | let AssistantService: Newable;
26 |
27 | if (import.meta.env.DEV) {
28 | UserService = MockUserService;
29 | AssistantService = OpenAIAssistantService;
30 | } else {
31 | UserService = AADUserService;
32 | AssistantService = OpenAIAssistantService;
33 | }
34 |
35 | const StorageService = MockStorageService;
36 |
37 | const {
38 | convos,
39 | activeConvo,
40 | selectConvo,
41 | createConvo,
42 | archiveConvo,
43 | archiveAllConvos,
44 | editConvo,
45 | onSubmit,
46 | isSubmitting,
47 | isLoading,
48 | user,
49 | model,
50 | selectModel,
51 | } = useAPI(UserService, AssistantService, StorageService);
52 |
53 | return (
54 |
65 | New Conversation
66 |
67 | }
68 | Body={
69 |
76 | }
77 | Footer={
78 |
79 |
80 | {
87 | return;
88 | },
89 | }}
90 | />
91 |
92 | }
93 | />
94 | }
95 | Content={
96 | activeConvo.messages.length > 0 ? (
97 |
98 | ) : (
99 |
105 |
114 |
115 |
121 |
122 |
123 | )
124 | }
125 | Footer={
126 | onSubmit(event.currentTarget.value)}
135 | width="full"
136 | paddingX="3"
137 | paddingY="2.5"
138 | rounded="lg"
139 | boxShadow="sm"
140 | fontSize="sm"
141 | isDisabled={isLoading || isSubmitting}
142 | data-testid="prompt-input"
143 | />
144 | }
145 | />
146 | );
147 | }
148 |
149 | export default App;
150 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/components/ConvoList/ConvoListItem.tsx:
--------------------------------------------------------------------------------
1 | import { ConversationMetadata } from "@/models";
2 | import {
3 | Badge,
4 | ButtonGroup,
5 | Editable,
6 | EditableInput,
7 | EditablePreview,
8 | Flex,
9 | IconButton,
10 | Input,
11 | Text,
12 | useDisclosure,
13 | useEditableControls,
14 | } from "@chakra-ui/react";
15 | import { Archive, Check, Edit3, X } from "lucide-react";
16 | import { useRef } from "react";
17 | import ConfirmationDialog from "@/components/ConfirmationDialog";
18 | import { modelColorScheme } from "@/models";
19 |
20 | interface ConvoListItemProps {
21 | convo: ConversationMetadata;
22 | isActive: boolean;
23 | onSelect: (conversation: ConversationMetadata) => void;
24 | onEdit: (conversation: ConversationMetadata, title: string) => void;
25 | onArchive: (conversation: ConversationMetadata) => void;
26 | }
27 |
28 | const backgroundColor = "gray.200";
29 | const iconSize = "16";
30 | const iconStrokeWidth = "2";
31 |
32 | const ConvoListItem = ({
33 | convo,
34 | isActive,
35 | onSelect,
36 | onEdit,
37 | onArchive,
38 | }: ConvoListItemProps): JSX.Element => {
39 | const archiveDisclosure = useDisclosure();
40 | const archiveDisclosureRef = useRef(null);
41 |
42 | const EditableControls = (): JSX.Element => {
43 | const {
44 | isEditing,
45 | getSubmitButtonProps,
46 | getCancelButtonProps,
47 | getEditButtonProps,
48 | } = useEditableControls();
49 |
50 | const Buttons = isEditing ? (
51 | <>
52 |
55 | }
56 | color="gray"
57 | aria-label="submit-edit"
58 | {...getSubmitButtonProps()}
59 | />
60 | }
62 | color="gray"
63 | aria-label="cancel-edit"
64 | {...getCancelButtonProps()}
65 | />
66 | >
67 | ) : (
68 | <>
69 |
72 | }
73 | color="gray"
74 | aria-label="edit-title"
75 | {...getEditButtonProps()}
76 | />
77 |
83 | }
84 | color="gray"
85 | onClick={archiveDisclosure.onOpen}
86 | aria-label="archive-convo"
87 | />
88 | >
89 | );
90 |
91 | return (
92 |
93 | {Buttons}
94 |
95 | );
96 | };
97 | return (
98 | <>
99 | onSelect(convo)}
103 | tabIndex={0}
104 | width="full"
105 | display="flex"
106 | justifyContent="space-between"
107 | alignItems="center"
108 | gap="2"
109 | paddingX="3.5"
110 | paddingY="2"
111 | rounded="md"
112 | cursor="pointer"
113 | backgroundColor={isActive ? backgroundColor : ""}
114 | _hover={{
115 | backgroundColor: backgroundColor,
116 | }}
117 | onSubmit={(title) => onEdit(convo, title)}
118 | role="listitem"
119 | >
120 |
121 |
122 |
129 |
135 | {convo.timestamp.toDateString()}
136 |
137 |
143 | {convo.model}
144 |
145 |
146 |
147 |
148 | onArchive(convo)}
152 | header={<>Archive Conversation>}
153 | body={
154 | <>
155 | Are you sure you want to archive{" "}
156 |
157 | "{convo.title}"
158 |
159 | ? This action cannot be undone.
160 | >
161 | }
162 | submitText="Archive"
163 | />
164 | >
165 | );
166 | };
167 |
168 | export default ConvoListItem;
169 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI/src/hooks/useAPI.ts:
--------------------------------------------------------------------------------
1 | import {
2 | Conversation,
3 | ConversationMetadata,
4 | DEFAULT_MODEL,
5 | GPTModel,
6 | MessageStatus,
7 | Sender,
8 | User,
9 | modelDeployment,
10 | } from "@/models";
11 | import { useEffect, useState } from "react";
12 | import { AssistantService } from "@/services/AssistantService";
13 | import { StorageService } from "@/services/StorageService";
14 | import { UserService } from "@/services/UserService";
15 | import { Newable } from "@/utils";
16 | import useConvos from "./useConvos";
17 |
18 | const defaultConvo = (model: GPTModel = DEFAULT_MODEL) => {
19 | return {
20 | /** id and timestamp are placeholders,
21 | * backend will generate these */
22 | id: crypto.randomUUID(),
23 | title: "",
24 | timestamp: new Date(),
25 | model: model,
26 | messages: [],
27 | isArchived: false,
28 | };
29 | };
30 |
31 | const useAPI = (
32 | UserService: Newable,
33 | AssistantService: Newable,
34 | StorageService: Newable
35 | ) => {
36 | const assistantService = new AssistantService();
37 |
38 | const [user, setUser] = useState();
39 | const [storageService, setStorageService] = useState();
40 |
41 | const { convos, ...convoState } = useConvos();
42 | const [activeConvo, setActiveConvo] = useState(
43 | defaultConvo()
44 | );
45 | const [isSubmitting, setIsSubmitting] = useState(false);
46 | const [isLoading, setIsLoading] = useState(true);
47 |
48 | const [model, setModel] = useState(DEFAULT_MODEL);
49 |
50 | /** Load conversations from storage */
51 | useEffect(() => {
52 | const userService = new UserService();
53 | const loadConversations = async () => {
54 | setIsLoading(true);
55 | await userService
56 | .getUser()
57 | .then((user) => {
58 | setUser(user);
59 |
60 | const storageService = new StorageService(user);
61 |
62 | setStorageService(storageService);
63 | return storageService;
64 | })
65 | .then((storageService) => storageService.getConvos())
66 | .then(convoState.setConvos);
67 | setIsLoading(false);
68 | };
69 |
70 | loadConversations();
71 | }, [UserService, StorageService]);
72 |
73 | /** Make sure convos state is updated
74 | * so new title appears in the sidebar list.
75 | */
76 | useEffect(() => {
77 | const updatedConvos = convos.map((convo) =>
78 | convo.id === activeConvo.id ? activeConvo : convo
79 | );
80 | convoState.setConvos(updatedConvos);
81 | }, [activeConvo.title]);
82 |
83 | const selectModel = (model: GPTModel) => {
84 | activeConvo.model = model;
85 | setActiveConvo(activeConvo);
86 | setModel(model);
87 | };
88 |
89 | const selectConvo = (convo: ConversationMetadata) => {
90 | storageService?.getMessages(convo.id).then((messages) => {
91 | const newActiveConvo = { messages: messages, ...convo };
92 | setActiveConvo(newActiveConvo);
93 | });
94 | };
95 |
96 | /** Create empty conversation, without adding to list. */
97 | const createConvo = () => {
98 | setModel(model);
99 | setActiveConvo(defaultConvo(model));
100 | };
101 |
102 | /** Edit conversation title. */
103 | const editConvo = (
104 | convo: ConversationMetadata,
105 | title: Conversation["title"]
106 | ) => {
107 | storageService?.updateConvo(convo);
108 | convoState.editTitle(convo, title);
109 | };
110 |
111 | /** Archive single conversation. */
112 | const archiveConvo = (convo: ConversationMetadata) => {
113 | storageService?.archiveConvo(convo.id);
114 | convoState.archiveConvo(convo);
115 | createConvo();
116 | };
117 |
118 | /** Archive all conversations. */
119 | const archiveAllConvos = () => {
120 | storageService?.archiveAllConvos();
121 | convoState.archiveAllConvos();
122 | createConvo();
123 | };
124 |
125 | /** On submit for prompt input. */
126 | const onSubmit = async (text: string) => {
127 | /** Check if user is defined */
128 | if (!user) {
129 | throw Error("User is not defined.");
130 | }
131 |
132 | if (!storageService) {
133 | throw Error("Storage service not defined.");
134 | }
135 |
136 | /** If conversation is new, add to list. */
137 | if (!convos.some((convo) => convo.id === activeConvo.id)) {
138 | /** Use first message for default title.
139 | * Original ChatGPT behavior is to generate a title -
140 | * may want to update to this in the future.
141 | */
142 | const truncate = (text: string) => {
143 | const MAX_LENGTH = 20;
144 |
145 | if (text.length > MAX_LENGTH) {
146 | return text.substring(0, MAX_LENGTH) + "...";
147 | } else {
148 | return text;
149 | }
150 | };
151 | activeConvo.title = truncate(text);
152 |
153 | convoState.createConvo(activeConvo);
154 | const createdConvo = await storageService.createConvo(activeConvo);
155 |
156 | activeConvo.id = createdConvo.id;
157 |
158 | setActiveConvo({ ...activeConvo });
159 | }
160 |
161 | if (!isSubmitting) {
162 | setIsSubmitting(true);
163 |
164 | const userMessage = {
165 | id: crypto.randomUUID(),
166 | conversationId: activeConvo.id,
167 | text: text,
168 | sender: Sender.User,
169 | timestamp: new Date(),
170 | status: MessageStatus.Success,
171 | };
172 |
173 | storageService?.addMessages(activeConvo.id, [userMessage]);
174 | activeConvo.messages.push(userMessage);
175 |
176 | const completion = await assistantService
177 | .getCompletion({
178 | messages: activeConvo.messages,
179 | deployment_name: modelDeployment(model),
180 | })
181 | .catch((error) => {
182 | const latestMessage = activeConvo.messages.at(-1);
183 | if (latestMessage) {
184 | latestMessage.status = MessageStatus.Error;
185 | latestMessage.statusMessage = error.message;
186 | }
187 | });
188 |
189 | if (completion) {
190 | const assistantMessage = {
191 | id: crypto.randomUUID(),
192 | conversationId: activeConvo.id,
193 | text: completion,
194 | sender: Sender.Assistant,
195 | timestamp: new Date(),
196 | status: MessageStatus.Success,
197 | };
198 |
199 | activeConvo.messages.push(assistantMessage);
200 | storageService?.addMessages(activeConvo.id, [assistantMessage]);
201 | }
202 |
203 | setIsSubmitting(false);
204 | }
205 | };
206 |
207 | return {
208 | convos,
209 | activeConvo,
210 | selectConvo,
211 | createConvo,
212 | archiveConvo,
213 | archiveAllConvos,
214 | editConvo,
215 | onSubmit,
216 | isSubmitting,
217 | isLoading,
218 | user,
219 | model,
220 | selectModel,
221 | };
222 | };
223 |
224 | export default useAPI;
225 |
--------------------------------------------------------------------------------
/DFCI-GPT4DFCI-Backend/app/main.py:
--------------------------------------------------------------------------------
1 | from contextlib import asynccontextmanager
2 | from typing import Annotated, List
3 |
4 | from azure.cosmos import CosmosClient, ContainerProxy, PartitionKey
5 | from dotenv import dotenv_values
6 | from fastapi import Depends, FastAPI, Header, HTTPException, Request
7 | import openai
8 |
9 | from app.models import Convo, Message, ChatCompletion
10 | from app.utils import generate_uuid, generate_timestamp
11 |
12 | config = dotenv_values()
13 |
14 | AZURE_COSMOSDB_ENDPOINT = config["AZURE_COSMOSDB_ENDPOINT"]
15 | AZURE_COSMOSDB_KEY = config["AZURE_COSMOSDB_KEY"]
16 | AZURE_COSMOSDB_DATABASE = config["AZURE_COSMOSDB_DATABASE"]
17 | AZURE_COSMOSDB_CONTAINER = config["AZURE_COSMOSDB_CONTAINER"]
18 |
19 | openai.api_type = config["AZURE_OPENAI_API_TYPE"]
20 | openai.api_base = config["AZURE_OPENAI_ENDPOINT"]
21 | openai.api_version = config["AZURE_OPENAI_API_VERSION"]
22 | openai.api_key = config["AZURE_OPENAI_KEY"]
23 |
24 |
25 | @asynccontextmanager
26 | async def lifespan(app: FastAPI):
27 | partition_key = PartitionKey(
28 | path="/userId"
29 | )
30 | app.state.cosmos_container = (
31 | CosmosClient(
32 | url=AZURE_COSMOSDB_ENDPOINT,
33 | credential=AZURE_COSMOSDB_KEY,
34 | )
35 | .get_database_client(database=AZURE_COSMOSDB_DATABASE)
36 | .create_container_if_not_exists(
37 | id=AZURE_COSMOSDB_CONTAINER,
38 | partition_key=partition_key,
39 | )
40 | )
41 | yield
42 |
43 |
44 | def get_container(request: Request):
45 | return request.app.state.cosmos_container
46 |
47 |
48 | def verify_user_id(user_id: Annotated[str, Header()]):
49 | if len(user_id) == 0:
50 | raise HTTPException(status_code=400, detail="User ID invalid.")
51 |
52 | return user_id
53 |
54 |
55 | app = FastAPI(
56 | title="GPT4DFCI - Backend",
57 | lifespan=lifespan,
58 | )
59 |
60 |
61 | @app.post("/completion")
62 | def create_completion(
63 | deployment_name: str,
64 | messages: List[Message],
65 | ) -> ChatCompletion:
66 | # reformat to fit OpenAI API request schema
67 | reformatted_messages = [
68 | {"role": message.sender, "content": message.text} for message in messages
69 | ]
70 | response = openai.ChatCompletion.create(
71 | engine=deployment_name,
72 | messages=reformatted_messages,
73 | temperature=0.1,
74 | max_tokens=800,
75 | top_p=0.95,
76 | frequency_penalty=0,
77 | presence_penalty=0,
78 | stop=None,
79 | )
80 | return response
81 |
82 |
83 | @app.get("/convos")
84 | def get_convos(
85 | user_id: Annotated[str, Depends(verify_user_id)],
86 | container: Annotated[ContainerProxy, Depends(get_container)],
87 | ) -> List[Convo]:
88 | """Get all conversations for the given user, excluding messages."""
89 | query = "SELECT * FROM convos c where c.userId = @userId"
90 | params: list[dict[str, object]] = [{"name": "@userId", "value": user_id}]
91 |
92 | items = container.query_items(
93 | query=query, parameters=params, enable_cross_partition_query=False
94 | )
95 |
96 | # exclude messages
97 | results = []
98 |
99 | for result in items:
100 | result.pop("messages", None)
101 | results.append(Convo(**result))
102 |
103 | return results
104 |
105 |
106 | @app.post("/convos")
107 | def create_convo(
108 | convo: Convo,
109 | user_id: Annotated[str, Depends(verify_user_id)],
110 | container: Annotated[ContainerProxy, Depends(get_container)],
111 | timestamp: Annotated[str, Depends(generate_timestamp)],
112 | ) -> Convo:
113 | """Create a new conversation.
114 |
115 | Returns the created conversation.
116 | """
117 | convo_json = convo.model_dump(mode="json")
118 |
119 | # generate ID and timestamp
120 | convo_json["id"] = generate_uuid()
121 | convo_json["userId"] = user_id
122 | convo_json["timestamp"] = timestamp
123 | convo_json["messages"] = []
124 |
125 | item = container.create_item(convo_json)
126 |
127 | created_convo = Convo(**item)
128 | return created_convo
129 |
130 |
131 | @app.get("/convos/{convo_id}")
132 | def get_convo(
133 | convo_id: str,
134 | user_id: Annotated[str, Depends(verify_user_id)],
135 | container: Annotated[ContainerProxy, Depends(get_container)],
136 | ) -> Convo:
137 | """Get a conversation by ID."""
138 |
139 | # exclude messages
140 | query = "SELECT \
141 | c.id, \
142 | c.userId,\
143 | c.title, \
144 | c.model, \
145 | c.timestamp, \
146 | c.isArchived \
147 | FROM convos c where \
148 | c.id = @convoId and \
149 | c.userId = @userId"
150 |
151 | params: list[dict[str, object]] = [
152 | {"name": "@convoId", "value": convo_id},
153 | {"name": "@userId", "value": user_id},
154 | ]
155 |
156 | results = container.query_items(
157 | query=query, parameters=params, enable_cross_partition_query=False
158 | )
159 |
160 | results = list(results)
161 |
162 | if len(results) == 0:
163 | raise HTTPException(
164 | status_code=404,
165 | detail="Conversation not found.",
166 | )
167 |
168 | elif len(results) == 1:
169 | returned_convo = results[0]
170 |
171 | return Convo(**returned_convo)
172 |
173 | else:
174 | raise HTTPException(
175 | status_code=500,
176 | detail="Multiple conversations with given ID found.",
177 | )
178 |
179 |
180 | @app.patch("/convos/{convo_id}")
181 | def update_convo(
182 | convo_id: str,
183 | convo: Convo,
184 | user_id: Annotated[str, Depends(verify_user_id)],
185 | container: Annotated[ContainerProxy, Depends(get_container)],
186 | ) -> Convo:
187 | """Update a conversation with the given values.
188 |
189 | If successful, returns the updated convo.
190 | """
191 | if convo.id != convo_id:
192 | raise HTTPException(
193 | status_code=400,
194 | detail="Conversation ID in body must match ID provided in path.",
195 | )
196 |
197 | if convo.userId != user_id:
198 | raise HTTPException(
199 | status_code=400, detail="User ID in body must match ID provided in header."
200 | )
201 |
202 | stored_convo = get_convo(convo_id=convo_id, user_id=user_id, container=container)
203 | stored_messages = get_messages(
204 | convo_id=convo_id, user_id=user_id, container=container
205 | )
206 |
207 | data_to_update = convo.model_dump(mode="json", exclude_unset=True)
208 |
209 | updated_convo = stored_convo.model_copy(
210 | update=data_to_update, deep=True
211 | ).model_dump(mode="json")
212 |
213 | updated_convo["messages"] = stored_messages
214 |
215 | item = container.upsert_item(updated_convo)
216 |
217 | returned_convo = Convo(**item)
218 | return returned_convo
219 |
220 |
221 | @app.get("/convos/{convo_id}/messages")
222 | def get_messages(
223 | convo_id: str,
224 | user_id: Annotated[str, Depends(verify_user_id)],
225 | container: Annotated[ContainerProxy, Depends(get_container)],
226 | ) -> List[Message]:
227 | """Get the messages for a given convo."""
228 |
229 | # fetch messages
230 | query = "SELECT c.messages FROM convos c where \
231 | c.id = @convoId and \
232 | c.userId = @userId"
233 |
234 | params: list[dict[str, object]] = [
235 | {"name": "@convoId", "value": convo_id},
236 | {"name": "@userId", "value": user_id},
237 | ]
238 |
239 | results = container.query_items(
240 | query=query, parameters=params, enable_cross_partition_query=False
241 | )
242 |
243 | results = list(results)
244 |
245 | # spot checks
246 | if len(results) == 0 or "messages" not in results[0].keys():
247 | raise HTTPException(status_code=404, detail="Messages not found.")
248 |
249 | elif len(results) == 1:
250 | return results[0]["messages"]
251 |
252 | else:
253 | raise HTTPException(status_code=400, detail="Multiple sets of messages found.")
254 |
255 |
256 | @app.post("/convos/{convo_id}/messages")
257 | def add_messages(
258 | convo_id: str,
259 | messages: List[Message],
260 | user_id: Annotated[str, Depends(verify_user_id)],
261 | container: Annotated[ContainerProxy, Depends(get_container)],
262 | timestamp: Annotated[str, Depends(generate_timestamp)],
263 | ) -> List[Message]:
264 | """Append one or more messages to the list of messages for a given convo.
265 |
266 | If successful, returns the updated list of messages.
267 | """
268 | # fetch convo
269 | convo = get_convo(
270 | convo_id=convo_id, user_id=user_id, container=container
271 | ).model_dump(mode="json")
272 |
273 | # fetch messages
274 | stored_messages = get_messages(
275 | convo_id=convo_id, user_id=user_id, container=container
276 | )
277 |
278 | # add timestamp
279 | new_messages = []
280 |
281 | for message in messages:
282 | new_message = message.model_dump(mode="json")
283 |
284 | new_message["id"] = generate_uuid()
285 | new_message["timestamp"] = timestamp
286 |
287 | new_messages.append(new_message)
288 |
289 | # append to existing messages
290 | convo["messages"] = stored_messages + new_messages
291 |
292 | updated_convo = container.upsert_item(convo)
293 |
294 | # return created messages
295 | return updated_convo["messages"]
296 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 |
294 | Copyright (C)
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | , 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------