Add support for tgi multimodal models (#531)
Browse files* wip: add support for tgi multimodal models
* wip work on passing images to prompt
* working idefics config!
* rm allowed conv feature
* lint
* Add image resizing
* fix ssr
* add upload button
* add delete button
* misc formatting
* lint
* server file size check
* optimistic update of images
* retry with images
* fix websearch button
* lint
* better error handling & max one image at a time
* replace test image by blank one
* disable loading on page change
* Fix sharing of images
* fix comments
* Update filedropzone (#544)
* Update src/lib/buildPrompt.ts
Co-authored-by: Mishig <mishig.davaadorj@coloradocollege.edu>
* small tweaks
* Fix merge conflicts
* lint
* wildcard image mime type
* fix lint and comment
* added comments
* added comment about file size
* Readme update
---------
Co-authored-by: Mishig <mishig.davaadorj@coloradocollege.edu>
Co-authored-by: Victor Mustar <victor.mustar@gmail.com>
Files changed (29)
- .env.template+1-1
- PROMPTS.md+6
- README.md+85-110
- package-lock.json+29
- package.json+2
- src/lib/buildPrompt.ts+38-6
- src/lib/components/UploadBtn.svelteAdded+23
- src/lib/components/chat/ChatInput.svelte-1
- src/lib/components/chat/ChatMessage.svelte+53-30
- src/lib/components/chat/ChatWindow.svelte+139-75
- src/lib/components/chat/FileDropzone.svelteAdded+110
- src/lib/server/database.ts+3-1
- src/lib/server/endpoints/endpoints.ts+1
- src/lib/server/endpoints/tgi/endpointTgi.ts+1
- src/lib/server/files/downloadFile.tsAdded+36
- src/lib/server/files/uploadFile.tsAdded+21
- src/lib/server/models.ts+2-1
- src/lib/stores/pendingMessage.ts+7-1
- src/lib/types/Message.ts+1
- src/lib/types/MessageUpdate.ts+8-1
- src/lib/types/Model.ts+1
- src/lib/utils/file2base64.tsAdded+14
- src/lib/utils/models.ts+1-1
- src/routes/+layout.server.ts+1
- src/routes/+page.svelte+6-1
- src/routes/conversation/[id]/+page.svelte+41-6
- src/routes/conversation/[id]/+server.ts+46-1
- src/routes/conversation/[id]/output/[sha256]/+server.tsAdded+49
- src/routes/conversation/[id]/share/+server.ts+17
110 unmodified lines111112113114115116117110 unmodified lines},"promptExamples": [{"title": "Write an email from bullet list","prompt": "As a restaurant owner, write a professional email to the supplier to get these products every week: \n\n- Wine (x10)\n- Eggs (x24)\n- Bread (x12)"}, {"title": "Code a snake game",110 unmodified lines111112113114115116117110 unmodified lines},"promptExamples": [{"title": "Write an email from bullet list","prompt": "As a restaurant owner, write a professional email to the supplier to get these products every week: \n\n- Wine (x10)\n- Eggs (x24)\n- Bread (x12)"}, {"title": "Code a snake game",
30 unmodified lines31323330 unmodified lines```env<|system|>\n{{preprompt}}</s>\n{{#each messages}}{{#ifUser}}<|user|>\n{{content}}</s>\n<|assistant|>\n{{/ifUser}}{{#ifAssistant}}{{content}}</s>\n{{/ifAssistant}}{{/each}}```30 unmodified lines31323334353637383930 unmodified lines```env<|system|>\n{{preprompt}}</s>\n{{#each messages}}{{#ifUser}}<|user|>\n{{content}}</s>\n<|assistant|>\n{{/ifUser}}{{#ifAssistant}}{{content}}</s>\n{{/ifAssistant}}{{/each}}```## IDEFICS```env{{#each messages}}{{#ifUser}}User: {{content}}{{/ifUser}}<end_of_utterance>\nAssistant: {{#ifAssistant}}{{content}}\n{{/ifAssistant}}{{/each}}```
167 unmodified lines16816917017117217317442 unmodified lines21721821922022122222329 unmodified lines25325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132220 unmodified lines34334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639710 unmodified lines408409410411412413414415416167 unmodified linesYou can change things like the parameters, or customize the preprompt to better suit your needs. You can also add more models by adding more objects to the array, with different preprompts for example.#### OpenAI API compatible modelsChat UI can be used with any API server that supports OpenAI API compatibility, for example [text-generation-webui](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/openai), [LocalAI](https://github.com/go-skynet/LocalAI), [FastChat](https://github.com/lm-sys/FastChat/blob/main/docs/openai_api.md), [llama-cpp-python](https://github.com/abetlen/llama-cpp-python), and [ialacol](https://github.com/chenhunghan/ialacol).42 unmodified lines}]````#### Llama.cpp API serverchat-ui also supports the llama.cpp API server directly without the need for an adapter. You can do this using the `llamacpp` endpoint type.29 unmodified linesStart chat-ui with `npm run dev` and you should be able to chat with Zephyr locally.#### Custom prompt templatesBy default, the prompt is constructed using `userMessageToken`, `assistantMessageToken`, `userMessageEndToken`, `assistantMessageEndToken`, `preprompt` parameters and a series of default templates.However, these templates can be modified by setting the `chatPromptTemplate` and `webSearchQueryPromptTemplate` parameters. Note that if WebSearch is not enabled, only `chatPromptTemplate` needs to be set. The template language is <https://handlebarsjs.com>. The templates have access to the model's prompt parameters (`preprompt`, etc.). However, if the templates are specified it is recommended to inline the prompt parameters, as using the references (`{{preprompt}}`) is deprecated.For example:```prompt<System>You are an AI, called ChatAI.</System>{{#each messages}}{{#ifUser}}<User>{{content}}</User>{{/ifUser}}{{#ifAssistant}}<Assistant>{{content}}</Assistant>{{/ifAssistant}}{{/each}}<Assistant>```##### chatPromptTemplateWhen querying the model for a chat response, the `chatPromptTemplate` template is used. `messages` is an array of chat messages, it has the format `[{ content: string }, ...]`. To identify if a message is a user message or an assistant message the `ifUser` and `ifAssistant` block helpers can be used.The following is the default `chatPromptTemplate`, although newlines and indentiation have been added for readability. You can find the prompts used in production for HuggingChat [here](https://github.com/huggingface/chat-ui/blob/main/PROMPTS.md).```prompt{{preprompt}}{{#each messages}}{{#ifUser}}{{@root.userMessageToken}}{{content}}{{@root.userMessageEndToken}}{{/ifUser}}{{#ifAssistant}}{{@root.assistantMessageToken}}{{content}}{{@root.assistantMessageEndToken}}{{/ifAssistant}}{{/each}}{{assistantMessageToken}}```##### webSearchQueryPromptTemplateWhen performing a websearch, the search query is constructed using the `webSearchQueryPromptTemplate` template. It is recommended that the prompt instructs the chat model to only return a few keywords.The following is the default `webSearchQueryPromptTemplate`.```prompt{{userMessageToken}}My question is: {{message.content}}.Based on the conversation history (my previous questions are: {{previousMessages}}), give me an appropriate query to answer my question for web search. You should not say more than query. You should not say any words except the query. For the context, today is {{currentDate}}{{userMessageEndToken}}{{assistantMessageToken}}```#### Running your own models using a custom endpointIf you want to, instead of hitting models on the Hugging Face Inference API, you can run your own models locally.A good option is to hit a [text-generation-inference](https://github.com/huggingface/text-generation-inference) endpoint. This is what is done in the official [Chat UI Spaces Docker template](https://huggingface.co/new-space?template=huggingchat/chat-ui-template) for instance: both this app and a text-generation-inference server run inside the same container.To do this, you can add your own endpoints to the `MODELS` variable in `.env.local`, by adding an `"endpoints"` key for each model in `MODELS`.```env{// rest of the model config here"endpoints": [{"url": "https://HOST:PORT"}]}```If `endpoints` are left unspecified, ChatUI will look for the model on the hosted Hugging Face inference API using the model name.### Custom endpoint authorization20 unmodified lines]```### Amazon#### SageMakerYou can also specify your Amazon SageMaker instance as an endpoint for chat-ui. The config goes like this:```env"endpoints": [{"type" : "aws","service" : "sagemaker""url": "","accessKey": "","secretKey" : "","sessionToken": "","weight": 1}]```#### LambdaYou can also specify your Amazon Lambda instance as an endpoint for chat-ui. The config goes like this:```env"endpoints" : [{"type": "aws","service": "lambda","url": "","accessKey": "","secretKey": "","sessionToken": "","region": "","weight": 1}]```You can get the `accessKey` and `secretKey` from your AWS user, under programmatic access.#### Client Certificate Authentication (mTLS)Custom endpoints may require client certificate authentication, depending on how you configure them. To enable mTLS between Chat UI and your custom endpoint, you will need to set the `USE_CLIENT_CERTIFICATE` to `true`, and add the `CERT_PATH` and `KEY_PATH` parameters to your `.env.local`. These parameters should point to the location of the certificate and key files on your local machine. The certificate and key files should be in PEM format. The key file can be encrypted with a passphrase, in which case you will also need to add the `CLIENT_KEY_PASSWORD` parameter to your `.env.local`.If you're using a certificate signed by a private CA, you will also need to add the `CA_PATH` parameter to your `.env.local`. This parameter should point to the location of the CA certificate file on your local machine.If you're using a self-signed certificate, e.g. for testing or development purposes, you can set the `REJECT_UNAUTHORIZED` parameter to `false` in your `.env.local`. This will disable certificate validation, and allow Chat UI to connect to your custom endpoint.#### Models hosted on multiple custom endpointsIf the model being hosted will be available on multiple servers/instances add the `weight` parameter to your `.env.local`. The `weight` will be used to determine the probability of requesting a particular endpoint.10 unmodified lines}...]```## Deploying to a HF SpaceCreate a `DOTENV_LOCAL` secret to your HF space with the content of your .env.local, and they will be picked up automatically when you run.167 unmodified lines16816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123242 unmodified lines27527627727827928028129 unmodified lines31131231331431531631731831932032132232332432532632732832933033133233333433533633733833920 unmodified lines36036136236336436510 unmodified lines376377378379380381382383384385386387388389390391167 unmodified linesYou can change things like the parameters, or customize the preprompt to better suit your needs. You can also add more models by adding more objects to the array, with different preprompts for example.#### chatPromptTemplateWhen querying the model for a chat response, the `chatPromptTemplate` template is used. `messages` is an array of chat messages, it has the format `[{ content: string }, ...]`. To identify if a message is a user message or an assistant message the `ifUser` and `ifAssistant` block helpers can be used.The following is the default `chatPromptTemplate`, although newlines and indentiation have been added for readability. You can find the prompts used in production for HuggingChat [here](https://github.com/huggingface/chat-ui/blob/main/PROMPTS.md).```prompt{{preprompt}}{{#each messages}}{{#ifUser}}{{@root.userMessageToken}}{{content}}{{@root.userMessageEndToken}}{{/ifUser}}{{#ifAssistant}}{{@root.assistantMessageToken}}{{content}}{{@root.assistantMessageEndToken}}{{/ifAssistant}}{{/each}}{{assistantMessageToken}}```#### Multi modal modelWe currently only support IDEFICS as a multimodal model, hosted on TGI. You can enable it by using the followin config (if you have a PRO HF Api token):```env{"name": "HuggingFaceM4/idefics-80b-instruct","multimodal" : true,"description": "IDEFICS is the new multimodal model by Hugging Face.","preprompt": "","chatPromptTemplate" : "{{#each messages}}{{#ifUser}}User: {{content}}{{/ifUser}}<end_of_utterance>\nAssistant: {{#ifAssistant}}{{content}}\n{{/ifAssistant}}{{/each}}","parameters": {"temperature": 0.1,"top_p": 0.95,"repetition_penalty": 1.2,"top_k": 12,"truncate": 1000,"max_new_tokens": 1024,"stop": ["<end_of_utterance>", "User:", "\nUser:"]}}```#### Running your own models using a custom endpointIf you want to, instead of hitting models on the Hugging Face Inference API, you can run your own models locally.A good option is to hit a [text-generation-inference](https://github.com/huggingface/text-generation-inference) endpoint. This is what is done in the official [Chat UI Spaces Docker template](https://huggingface.co/new-space?template=huggingchat/chat-ui-template) for instance: both this app and a text-generation-inference server run inside the same container.To do this, you can add your own endpoints to the `MODELS` variable in `.env.local`, by adding an `"endpoints"` key for each model in `MODELS`.```env{// rest of the model config here"endpoints": [{"type" : "tgi","url": "https://HOST:PORT",}]}```If `endpoints` are left unspecified, ChatUI will look for the model on the hosted Hugging Face inference API using the model name.##### OpenAI API compatible modelsChat UI can be used with any API server that supports OpenAI API compatibility, for example [text-generation-webui](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/openai), [LocalAI](https://github.com/go-skynet/LocalAI), [FastChat](https://github.com/lm-sys/FastChat/blob/main/docs/openai_api.md), [llama-cpp-python](https://github.com/abetlen/llama-cpp-python), and [ialacol](https://github.com/chenhunghan/ialacol).42 unmodified lines}]````##### Llama.cpp API serverchat-ui also supports the llama.cpp API server directly without the need for an adapter. You can do this using the `llamacpp` endpoint type.29 unmodified linesStart chat-ui with `npm run dev` and you should be able to chat with Zephyr locally.#### AmazonYou can also specify your Amazon SageMaker instance as an endpoint for chat-ui. The config goes like this:```env"endpoints": [{"type" : "aws","service" : "sagemaker""url": "","accessKey": "","secretKey" : "","sessionToken": "","region": "","weight": 1}]```You can also set `"service" : "lambda"` to use a lambda instance.You can get the `accessKey` and `secretKey` from your AWS user, under programmatic access.### Custom endpoint authorization20 unmodified lines]```#### Models hosted on multiple custom endpointsIf the model being hosted will be available on multiple servers/instances add the `weight` parameter to your `.env.local`. The `weight` will be used to determine the probability of requesting a particular endpoint.10 unmodified lines}...]```#### Client Certificate Authentication (mTLS)Custom endpoints may require client certificate authentication, depending on how you configure them. To enable mTLS between Chat UI and your custom endpoint, you will need to set the `USE_CLIENT_CERTIFICATE` to `true`, and add the `CERT_PATH` and `KEY_PATH` parameters to your `.env.local`. These parameters should point to the location of the certificate and key files on your local machine. The certificate and key files should be in PEM format. The key file can be encrypted with a passphrase, in which case you will also need to add the `CLIENT_KEY_PASSWORD` parameter to your `.env.local`.If you're using a certificate signed by a private CA, you will also need to add the `CA_PATH` parameter to your `.env.local`. This parameter should point to the location of the CA certificate file on your local machine.If you're using a self-signed certificate, e.g. for testing or development purposes, you can set the `REJECT_UNAUTHORIZED` parameter to `false` in your `.env.local`. This will disable certificate validation, and allow Chat UI to connect to your custom endpoint.## Deploying to a HF SpaceCreate a `DOTENV_LOCAL` secret to your HF space with the content of your .env.local, and they will be picked up automatically when you run.
11 unmodified lines121314151617181920211774 unmodified lines1796179717981799180018011464 unmodified lines3266326732683269327032711714 unmodified lines49864987498849894990499111 unmodified lines"@huggingface/inference": "^2.6.3","@xenova/transformers": "^2.6.0","autoprefixer": "^10.4.14","date-fns": "^2.29.3","dotenv": "^16.0.3","handlebars": "^4.7.8","highlight.js": "^11.7.0","jsdom": "^22.0.0","marked": "^4.3.0","mongodb": "^5.8.0",1774 unmodified lines"base64-js": "^1.1.2"}},"node_modules/browserslist": {"version": "4.21.5","resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.21.5.tgz",1464 unmodified lines"node": ">= 4"}},"node_modules/import-fresh": {"version": "3.3.0","resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz",1714 unmodified lines"resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz","integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ=="},"node_modules/queue-microtask": {"version": "1.2.3","resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",11 unmodified lines1213141516171819202122231774 unmodified lines179817991800180118021803180418051806180718081464 unmodified lines327332743275327632773278327932803281328232833284328532863287328832893290329132921714 unmodified lines5007500850095010501150125013501450155016501750185019502011 unmodified lines"@huggingface/inference": "^2.6.3","@xenova/transformers": "^2.6.0","autoprefixer": "^10.4.14","browser-image-resizer": "^2.4.1","date-fns": "^2.29.3","dotenv": "^16.0.3","handlebars": "^4.7.8","highlight.js": "^11.7.0","image-size": "^1.0.2","jsdom": "^22.0.0","marked": "^4.3.0","mongodb": "^5.8.0",1774 unmodified lines"base64-js": "^1.1.2"}},"node_modules/browser-image-resizer": {"version": "2.4.1","resolved": "https://registry.npmjs.org/browser-image-resizer/-/browser-image-resizer-2.4.1.tgz","integrity": "sha512-gqrmr7+NTI9FgZVVyw/GIqwJE3MhNWaBn1R5ptu75r+/M5ncyntSMQYuYhOPonm44qQNnkGN9cnghlpd9h1Hug=="},"node_modules/browserslist": {"version": "4.21.5","resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.21.5.tgz",1464 unmodified lines"node": ">= 4"}},"node_modules/image-size": {"version": "1.0.2","resolved": "https://registry.npmjs.org/image-size/-/image-size-1.0.2.tgz","integrity": "sha512-xfOoWjceHntRb3qFCrh5ZFORYH8XCdYpASltMhZ/Q0KZiOwjdE/Yl2QCiWdwD+lygV5bMCvauzgu5PxBX/Yerg==","dependencies": {"queue": "6.0.2"},"bin": {"image-size": "bin/image-size.js"},"engines": {"node": ">=14.0.0"}},"node_modules/import-fresh": {"version": "3.3.0","resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz",1714 unmodified lines"resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz","integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ=="},"node_modules/queue": {"version": "6.0.2","resolved": "https://registry.npmjs.org/queue/-/queue-6.0.2.tgz","integrity": "sha512-iHZWu+q3IdFZFX36ro/lKBkSvfkztY5Y7HMiPlOUjhupPcG2JMfst2KKEpu5XndviX/3UhFbRngUPNKtgvtZiA==","dependencies": {"inherits": "~2.0.3"}},"node_modules/queue-microtask": {"version": "1.2.3","resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
47 unmodified lines4849505152535455565747 unmodified lines"@huggingface/inference": "^2.6.3","@xenova/transformers": "^2.6.0","autoprefixer": "^10.4.14","date-fns": "^2.29.3","dotenv": "^16.0.3","handlebars": "^4.7.8","highlight.js": "^11.7.0","jsdom": "^22.0.0","marked": "^4.3.0","mongodb": "^5.8.0",47 unmodified lines48495051525354555657585947 unmodified lines"@huggingface/inference": "^2.6.3","@xenova/transformers": "^2.6.0","autoprefixer": "^10.4.14","browser-image-resizer": "^2.4.1","date-fns": "^2.29.3","dotenv": "^16.0.3","handlebars": "^4.7.8","highlight.js": "^11.7.0","image-size": "^1.0.2","jsdom": "^22.0.0","marked": "^4.3.0","mongodb": "^5.8.0",
1 unmodified line23456789101112131415161718191 unmodified line21222324252622 unmodified lines4950515253541 unmodified lineimport type { Message } from "./types/Message";import { format } from "date-fns";import type { WebSearch } from "./types/WebSearch";/*** Convert [{user: "assistant", content: "hi"}, {user: "user", content: "hello"}] to:** <|assistant|>hi<|endoftext|><|prompter|>hello<|endoftext|><|assistant|>*/interface buildPromptOptions {messages: Pick<Message, "from" | "content">[];model: BackendModel;locals?: App.Locals;webSearch?: WebSearch;preprompt?: string;}export async function buildPrompt({1 unmodified linemodel,webSearch,preprompt,}: buildPromptOptions): Promise<string> {if (webSearch && webSearch.context) {const lastMsg = messages.slice(-1)[0];22 unmodified lines];}return (model.chatPromptRender({ messages, preprompt })1 unmodified line234567891011121314151617181 unmodified line2021222324252622 unmodified lines49505152535455565758596061626364656667686970717273747576777879808182838485861 unmodified lineimport type { Message } from "./types/Message";import { format } from "date-fns";import type { WebSearch } from "./types/WebSearch";import { downloadFile } from "./server/files/downloadFile";import type { Conversation } from "./types/Conversation";interface buildPromptOptions {messages: Pick<Message, "from" | "content" | "files">[];id?: Conversation["_id"];model: BackendModel;locals?: App.Locals;webSearch?: WebSearch;preprompt?: string;files?: File[];}export async function buildPrompt({1 unmodified linemodel,webSearch,preprompt,id,}: buildPromptOptions): Promise<string> {if (webSearch && webSearch.context) {const lastMsg = messages.slice(-1)[0];22 unmodified lines];}// section to handle potential files inputif (model.multimodal) {messages = await Promise.all(messages.map(async (el) => {let content = el.content;if (el.from === "user") {if (el?.files && el.files.length > 0 && id) {const markdowns = await Promise.all(el.files.map(async (hash) => {try {const { content: image, mime } = await downloadFile(hash, id);const b64 = image.toString("base64");return `})`;} catch (e) {console.error(e);}}));content += markdowns.join("\n ");} else {// if no image, append an empty white imagecontent +="\n";}}return { ...el, content };}));}return (model.chatPromptRender({ messages, preprompt })
1234567891011121314151617181920212223<script lang="ts"> import CarbonUpload from "~icons/carbon/upload";
export let classNames = ""; export let files: File[]; let filelist: FileList;
$: if (filelist) { files = Array.from(filelist); }</script>
<button class="btn relative h-8 rounded-lg border bg-white px-3 py-1 text-sm text-gray-500 shadow-sm transition-all hover:bg-gray-100 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600 {classNames}"> <input bind:files={filelist} class="absolute w-full cursor-pointer opacity-0" type="file" accept="image/*" /> <CarbonUpload class="mr-2 text-xs " /> Upload image</button>5 unmodified lines67891011125 unmodified linesexport let maxRows: null | number = null;export let placeholder = "";export let disabled = false;// Approximate width from which we disable autofocusconst TABLET_VIEWPORT_WIDTH = 768;5 unmodified lines678910115 unmodified linesexport let maxRows: null | number = null;export let placeholder = "";export let disabled = false;// Approximate width from which we disable autofocusconst TABLET_VIEWPORT_WIDTH = 768;
233 unmodified lines234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269233 unmodified lines{/if}{#if message.from === "user"}<div class="group relative flex items-start justify-start gap-4 max-sm:text-sm"><div class="mt-5 h-3 w-3 flex-none rounded-full" /><divclass="max-w-full whitespace-break-spaces break-words rounded-2xl px-5 py-3.5 text-gray-500 dark:text-gray-400">{message.content.trim()}</div>{#if !loading}<div class="absolute right-0 top-3.5 flex gap-2 lg:-right-2">{#if downloadLink}<aclass="rounded-lg border border-gray-100 p-1 text-xs text-gray-400 group-hover:block hover:text-gray-500 dark:border-gray-800 dark:text-gray-400 dark:hover:text-gray-300 md:hidden"title="Download prompt and parameters"type="button"target="_blank"href={downloadLink}><CarbonDownload /></a>{/if}{#if !readOnly}<buttonclass="cursor-pointer rounded-lg border border-gray-100 p-1 text-xs text-gray-400 group-hover:block hover:text-gray-500 dark:border-gray-800 dark:text-gray-400 dark:hover:text-gray-300 md:hidden lg:-right-2"title="Retry"type="button"on:click={() => dispatch("retry", { content: message.content, id: message.id })}><CarbonRotate360 /></button>{/if}</div>{/if}</div>{/if}233 unmodified lines234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292233 unmodified lines{/if}{#if message.from === "user"}<div class="group relative flex items-start justify-start gap-4 max-sm:text-sm"><div class="flex flex-col">{#if message.files && message.files.length > 0}<div class="mx-auto grid w-fit grid-cols-2 gap-5 px-5">{#each message.files as file}<!-- handle the case where this is a hash that points to an image in the db, hash is always 64 char long -->{#if file.length === 64}<imgsrc={$page.url.pathname + "/output/" + file}alt="input from user"class="my-2 aspect-auto max-h-48 rounded-lg shadow-lg"/>{:else}<!-- handle the case where this is a base64 encoded image --><imgsrc={"data:image/*;base64," + file}alt="input from user"class="my-2 aspect-auto max-h-48 rounded-lg shadow-lg"/>{/if}{/each}</div>{/if}<divclass="max-w-full whitespace-break-spaces break-words rounded-2xl px-5 py-3.5 text-gray-500 dark:text-gray-400">{message.content.trim()}</div>{#if !loading}<div class="absolute right-0 top-3.5 flex gap-2 lg:-right-2">{#if downloadLink}<aclass="rounded-lg border border-gray-100 p-1 text-xs text-gray-400 group-hover:block hover:text-gray-500 dark:border-gray-800 dark:text-gray-400 dark:hover:text-gray-300 md:hidden"title="Download prompt and parameters"type="button"target="_blank"href={downloadLink}><CarbonDownload /></a>{/if}{#if !readOnly}<buttonclass="cursor-pointer rounded-lg border border-gray-100 p-1 text-xs text-gray-400 group-hover:block hover:text-gray-500 dark:border-gray-800 dark:text-gray-400 dark:hover:text-gray-300 md:hidden lg:-right-2"title="Retry"type="button"on:click={() => dispatch("retry", { content: message.content, id: message.id })}><CarbonRotate360 /></button>{/if}</div>{/if}</div></div>{/if}
4 unmodified lines56789106 unmodified lines171819202122234 unmodified lines28293031323313 unmodified lines4748495051525330 unmodified lines848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761774 unmodified linesimport CarbonSendAltFilled from "~icons/carbon/send-alt-filled";import CarbonExport from "~icons/carbon/export";import CarbonStopFilledAlt from "~icons/carbon/stop-filled-alt";import EosIconsLoading from "~icons/eos-icons/loading";import ChatMessages from "./ChatMessages.svelte";6 unmodified linesimport type { WebSearchUpdate } from "$lib/types/MessageUpdate";import { page } from "$app/stores";import DisclaimerModal from "../DisclaimerModal.svelte";import RetryBtn from "../RetryBtn.svelte";export let messages: Message[] = [];export let loading = false;4 unmodified linesexport let settings: LayoutData["settings"];export let webSearchMessages: WebSearchUpdate[] = [];export let preprompt: string | undefined = undefined;$: isReadOnly = !models.some((model) => model.id === currentModel.id);13 unmodified linesmessage = "";};$: lastIsError = messages[messages.length - 1]?.from === "user" && !loading;</script><div class="relative min-h-0 min-w-0">30 unmodified linesif (!loading) dispatch("retry", ev.detail);}}/><divclass="dark:via-gray-80 pointer-events-none absolute inset-x-0 bottom-0 z-0 mx-auto flex w-full max-w-3xl flex-col items-center justify-center bg-gradient-to-t from-white via-white/80 to-white/0 px-3.5 py-4 dark:border-gray-800 dark:from-gray-900 dark:to-gray-900/0 max-md:border-t max-md:bg-white max-md:dark:bg-gray-900 sm:px-5 md:py-8 xl:max-w-4xl [&>*]:pointer-events-auto"><div class="flex w-full pb-3">{#if settings?.searchEnabled}<WebSearchToggle />{/if}{#if loading}<StopGeneratingBtn classNames="ml-auto" on:click={() => dispatch("stop")} />{/if}{#if lastIsError}<RetryBtnclassNames="ml-auto"on:click={() =>dispatch("retry", {id: messages[messages.length - 1].id,content: messages[messages.length - 1].content,})}/>{/if}</div><formon:submit|preventDefault={handleSubmit}class="relative flex w-full max-w-4xl flex-1 items-center rounded-xl border bg-gray-100 focus-within:border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:focus-within:border-gray-500{isReadOnly ? 'opacity-30' : ''}"><div class="flex w-full flex-1 border-none bg-transparent">{#if lastIsError}<ChatInput value="Sorry, something went wrong. Please try again." disabled={true} />{:else}<ChatInputplaceholder="Ask anything"bind:value={message}on:submit={handleSubmit}on:keypress={(ev) => {if ($page.data.loginRequired) {ev.preventDefault();loginModalOpen = true;}}}maxRows={4}disabled={isReadOnly || lastIsError}/>{/if}{#if loading}<buttonclass="btn mx-1 my-1 inline-block h-[2.4rem] self-end rounded-lg bg-transparent p-1 px-[0.7rem] text-gray-400 disabled:opacity-60 enabled:hover:text-gray-700 dark:disabled:opacity-40 enabled:dark:hover:text-gray-100 md:hidden"on:click={() => dispatch("stop")}><CarbonStopFilledAlt /></button><divclass="mx-1 my-1 hidden h-[2.4rem] items-center p-1 px-[0.7rem] text-gray-400 disabled:opacity-60 enabled:hover:text-gray-700 dark:disabled:opacity-40 enabled:dark:hover:text-gray-100 md:flex"><EosIconsLoading /></div>{:else}<buttonclass="btn mx-1 my-1 h-[2.4rem] self-end rounded-lg bg-transparent p-1 px-[0.7rem] text-gray-400 disabled:opacity-60 enabled:hover:text-gray-700 dark:disabled:opacity-40 enabled:dark:hover:text-gray-100"disabled={!message || isReadOnly}type="submit"><CarbonSendAltFilled /></button>{/if}</div></form><div class="mt-2 flex justify-between self-stretch px-1 text-xs text-gray-400/90 max-sm:gap-2"><p>Model: <ahref={currentModel.modelUrl || "https://huggingface.co/" + currentModel.name}target="_blank"rel="noreferrer"class="hover:underline">{currentModel.displayName}</a> <span class="max-sm:hidden">·</span><br class="sm:hidden" /> Generated content may be inaccurateor false.</p>{#if messages.length}<buttonclass="flex flex-none items-center hover:text-gray-400 hover:underline max-sm:rounded-lg max-sm:bg-gray-50 max-sm:px-2.5 dark:max-sm:bg-gray-800"type="button"on:click={() => dispatch("share")}><CarbonExport class="text-[.6rem] sm:mr-1.5 sm:text-primary-500" /><div class="max-sm:hidden">Share this conversation</div></button>{/if}</div></div></div>4 unmodified lines567891011126 unmodified lines192021222324252627284 unmodified lines3334353637383913 unmodified lines5354555657585960616263646566676869707172737475767730 unmodified lines1081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402414 unmodified linesimport CarbonSendAltFilled from "~icons/carbon/send-alt-filled";import CarbonExport from "~icons/carbon/export";import CarbonStopFilledAlt from "~icons/carbon/stop-filled-alt";import CarbonClose from "~icons/carbon/close";import EosIconsLoading from "~icons/eos-icons/loading";import ChatMessages from "./ChatMessages.svelte";6 unmodified linesimport type { WebSearchUpdate } from "$lib/types/MessageUpdate";import { page } from "$app/stores";import DisclaimerModal from "../DisclaimerModal.svelte";import FileDropzone from "./FileDropzone.svelte";import RetryBtn from "../RetryBtn.svelte";import UploadBtn from "../UploadBtn.svelte";import file2base64 from "$lib/utils/file2base64";export let messages: Message[] = [];export let loading = false;4 unmodified linesexport let settings: LayoutData["settings"];export let webSearchMessages: WebSearchUpdate[] = [];export let preprompt: string | undefined = undefined;export let files: File[] = [];$: isReadOnly = !models.some((model) => model.id === currentModel.id);13 unmodified linesmessage = "";};let lastTarget: EventTarget | null = null;let onDrag = false;const onDragEnter = (e: DragEvent) => {lastTarget = e.target;onDrag = true;};const onDragLeave = (e: DragEvent) => {if (e.target === lastTarget) {onDrag = false;}};const onDragOver = (e: DragEvent) => {e.preventDefault();};$: lastIsError = messages[messages.length - 1]?.from === "user" && !loading;$: sources = files.map((file) => file2base64(file));</script><div class="relative min-h-0 min-w-0">30 unmodified linesif (!loading) dispatch("retry", ev.detail);}}/><divclass="pointer-events-none absolute inset-x-0 bottom-0 z-0 mx-auto flex w-full max-w-3xl flex-col items-center justify-center md:px-5 md:py-8 xl:max-w-4xl [&>*]:pointer-events-auto"><div class="flex flex-row flex-wrap justify-center gap-2.5 max-md:pb-3">{#each sources as source, index}{#await source then src}<div class="relative h-24 w-24 overflow-hidden rounded-lg shadow-lg"><imgsrc={`data:image/*;base64,${src}`}alt="input content"class="h-full w-full rounded-lg bg-gray-400 object-cover dark:bg-gray-900"/><!-- add a button on top that deletes this image from sources --><buttonclass="absolute left-1 top-1"on:click={() => {files = files.filter((_, i) => i !== index);}}><CarbonClose class="text-md font-black text-gray-300 hover:text-gray-100" /></button></div>{/await}{/each}</div><divclass="dark:via-gray-80 w-full bg-gradient-to-t from-white via-white/80 to-white/0 dark:border-gray-800 dark:from-gray-900 dark:to-gray-900/0 max-md:border-t max-md:bg-white max-md:px-4 max-md:dark:bg-gray-900"><div class="flex w-full pb-3 max-md:pt-3">{#if settings?.searchEnabled}<WebSearchToggle />{/if}{#if loading}<StopGeneratingBtn classNames="ml-auto" on:click={() => dispatch("stop")} />{:else if lastIsError}<RetryBtnclassNames="ml-auto"on:click={() =>dispatch("retry", {id: messages[messages.length - 1].id,content: messages[messages.length - 1].content,})}/>{:else if currentModel.multimodal}<UploadBtn bind:files classNames="ml-auto" />{/if}</div><formon:dragover={onDragOver}on:dragenter={onDragEnter}on:dragleave={onDragLeave}tabindex="-1"aria-label="file dropzone"on:submit|preventDefault={handleSubmit}class="relative flex w-full max-w-4xl flex-1 items-center rounded-xl border bg-gray-100 focus-within:border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:focus-within:border-gray-500{isReadOnly ? 'opacity-30' : ''}">{#if onDrag && currentModel.multimodal}<FileDropzone bind:files bind:onDrag />{:else}<div class="flex w-full flex-1 border-none bg-transparent">{#if lastIsError}<ChatInput value="Sorry, something went wrong. Please try again." disabled={true} />{:else}<ChatInputplaceholder="Ask anything"bind:value={message}on:submit={handleSubmit}on:keypress={(ev) => {if ($page.data.loginRequired) {ev.preventDefault();loginModalOpen = true;}}}maxRows={4}disabled={isReadOnly || lastIsError}/>{/if}{#if loading}<buttonclass="btn mx-1 my-1 inline-block h-[2.4rem] self-end rounded-lg bg-transparent p-1 px-[0.7rem] text-gray-400 disabled:opacity-60 enabled:hover:text-gray-700 dark:disabled:opacity-40 enabled:dark:hover:text-gray-100 md:hidden"on:click={() => dispatch("stop")}><CarbonStopFilledAlt /></button><divclass="mx-1 my-1 hidden h-[2.4rem] items-center p-1 px-[0.7rem] text-gray-400 disabled:opacity-60 enabled:hover:text-gray-700 dark:disabled:opacity-40 enabled:dark:hover:text-gray-100 md:flex"><EosIconsLoading /></div>{:else}<buttonclass="btn mx-1 my-1 h-[2.4rem] self-end rounded-lg bg-transparent p-1 px-[0.7rem] text-gray-400 disabled:opacity-60 enabled:hover:text-gray-700 dark:disabled:opacity-40 enabled:dark:hover:text-gray-100"disabled={!message || isReadOnly}type="submit"><CarbonSendAltFilled /></button>{/if}</div>{/if}</form><divclass="mt-2 flex justify-between self-stretch px-1 text-xs text-gray-400/90 max-md:mb-2 max-sm:gap-2"><p>Model: <ahref={currentModel.modelUrl || "https://huggingface.co/" + currentModel.name}target="_blank"rel="noreferrer"class="hover:underline">{currentModel.displayName}</a> <span class="max-sm:hidden">·</span><br class="sm:hidden" /> Generated content may be inaccurateor false.</p>{#if messages.length}<buttonclass="flex flex-none items-center hover:text-gray-400 hover:underline max-sm:rounded-lg max-sm:bg-gray-50 max-sm:px-2.5 dark:max-sm:bg-gray-800"type="button"on:click={() => dispatch("share")}><CarbonExport class="text-[.6rem] sm:mr-1.5 sm:text-primary-500" /><div class="max-sm:hidden">Share this conversation</div></button>{/if}</div></div></div></div>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110<script lang="ts"> import { onDestroy } from "svelte"; import CarbonImage from "~icons/carbon/image"; // import EosIconsLoading from "~icons/eos-icons/loading";
export let files: File[];
let file_error_message = ""; let errorTimeout: ReturnType<typeof setTimeout>;
export let onDrag = false;
async function dropHandle(event: DragEvent) { event.preventDefault(); if (event.dataTransfer && event.dataTransfer.items) { // Use DataTransferItemList interface to access the file(s) if (files.length > 0) { files = []; } // get only the first file // optionally: we need to handle multiple files, if we want to support document upload for example // for multimodal we only support one image at a time but we could support multiple PDFs if (event.dataTransfer.items[0].kind === "file") { const file = event.dataTransfer.items[0].getAsFile(); if (file) { if (!event.dataTransfer.items[0].type.startsWith("image")) { setErrorMsg("Only images are supported"); files = []; return; } // if image is bigger than 2MB abort if (file.size > 2 * 1024 * 1024) { setErrorMsg("Image is too big. (2MB max)"); files = []; return; } files = [file]; onDrag = false; } } } }
function setErrorMsg(errorMsg: string) { if (errorTimeout) { clearTimeout(errorTimeout); } file_error_message = errorMsg; errorTimeout = setTimeout(() => { file_error_message = ""; onDrag = false; }, 2000); }
onDestroy(() => { if (errorTimeout) { clearTimeout(errorTimeout); } });</script>
<div id="dropzone" role="form" on:drop={dropHandle} class="relative flex w-full max-w-4xl flex-col items-center rounded-xl border bg-gray-100 focus-within:border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:focus-within:border-gray-500"> <div class="object-center"> {#if file_error_message} <div class="absolute bottom-0 left-0 right-0 top-0 flex flex-col items-center justify-center gap-2 rounded-xl bg-gray-100 bg-opacity-50 dark:bg-gray-700 dark:bg-opacity-50" > <p class="text-red-500 dark:text-red-400">{file_error_message}</p> <div class="h-2.5 w-1/2 rounded-full bg-gray-200 dark:bg-gray-700"> <div class="animate-progress-bar h-2.5 rounded-full bg-red-500 dark:text-red-400 " /> </div> </div> {/if} <div class="mt-3 flex justify-center" class:opacity-0={file_error_message}> <CarbonImage class="text-5xl text-gray-500 dark:text-gray-400" /> </div> <p class="mb-3 mt-3 text-sm text-gray-500 dark:text-gray-400" class:opacity-0={file_error_message} > Drag and drop <span class="font-semibold">one image</span> here </p> </div></div>
<style> @keyframes slideInFromLeft { 0% { width: 0; } 100% { width: 100%; } }
.animate-progress-bar { /* This section calls the slideInFromLeft animation we defined above */ animation: 2s linear 0s 1 slideInFromLeft; }</style>1234523 unmodified lines2930313233344 unmodified lines394041424344import { MONGODB_URL, MONGODB_DB_NAME, MONGODB_DIRECT_CONNECTION } from "$env/static/private";import { MongoClient } from "mongodb";import type { Conversation } from "$lib/types/Conversation";import type { SharedConversation } from "$lib/types/SharedConversation";import type { WebSearch } from "$lib/types/WebSearch";23 unmodified linesconst users = db.collection<User>("users");const webSearches = db.collection<WebSearch>("webSearches");const messageEvents = db.collection<MessageEvent>("messageEvents");export { client, db };export const collections = {4 unmodified linesusers,webSearches,messageEvents,};client.on("open", () => {1234523 unmodified lines293031323334354 unmodified lines40414243444546import { MONGODB_URL, MONGODB_DB_NAME, MONGODB_DIRECT_CONNECTION } from "$env/static/private";import { GridFSBucket, MongoClient } from "mongodb";import type { Conversation } from "$lib/types/Conversation";import type { SharedConversation } from "$lib/types/SharedConversation";import type { WebSearch } from "$lib/types/WebSearch";23 unmodified linesconst users = db.collection<User>("users");const webSearches = db.collection<WebSearch>("webSearches");const messageEvents = db.collection<MessageEvent>("messageEvents");const bucket = new GridFSBucket(db, { bucketName: "files" });export { client, db };export const collections = {4 unmodified linesusers,webSearches,messageEvents,bucket,};client.on("open", () => {
10 unmodified lines11121314151610 unmodified linesconversation: {messages: Omit<Conversation["messages"][0], "id">[];preprompt?: Conversation["preprompt"];};}10 unmodified lines1112131415161710 unmodified linesconversation: {messages: Omit<Conversation["messages"][0], "id">[];preprompt?: Conversation["preprompt"];_id?: Conversation["_id"];};}
22 unmodified lines23242526272822 unmodified lineswebSearch: conversation.messages[conversation.messages.length - 1].webSearch,preprompt: conversation.preprompt,model,});return textGenerationStream({22 unmodified lines2324252627282922 unmodified lineswebSearch: conversation.messages[conversation.messages.length - 1].webSearch,preprompt: conversation.preprompt,model,id: conversation._id,});return textGenerationStream({
123456789101112131415161718192021222324252627282930313233343536import { error } from "@sveltejs/kit";import { collections } from "../database";import type { Conversation } from "$lib/types/Conversation";import type { SharedConversation } from "$lib/types/SharedConversation";
export async function downloadFile( sha256: string, convId: Conversation["_id"] | SharedConversation["_id"]) { const fileId = collections.bucket.find({ filename: `${convId.toString()}-${sha256}` }); let mime = "";
const content = await fileId.next().then(async (file) => { if (!file) { throw error(404, "File not found"); } if (file.metadata?.conversation !== convId.toString()) { throw error(403, "You don't have access to this file."); }
mime = file.metadata?.mime;
const fileStream = collections.bucket.openDownloadStream(file._id);
const fileBuffer = await new Promise<Buffer>((resolve, reject) => { const chunks: Uint8Array[] = []; fileStream.on("data", (chunk) => chunks.push(chunk)); fileStream.on("error", reject); fileStream.on("end", () => resolve(Buffer.concat(chunks))); });
return fileBuffer; });
return { content, mime };}123456789101112131415161718192021import type { Conversation } from "$lib/types/Conversation";import { sha256 } from "$lib/utils/sha256";import { collections } from "../database";
export async function uploadFile(file: Blob, conv: Conversation): Promise<string> { const sha = await sha256(await file.text());
const upload = collections.bucket.openUploadStream(`${conv._id}-${sha}`, { metadata: { conversation: conv._id.toString(), mime: "image/jpeg" }, });
upload.write((await file.arrayBuffer()) as unknown as Buffer); upload.end();
// only return the filename when upload throws a finish event or a 10s time out occurs return new Promise((resolve, reject) => { upload.once("finish", () => resolve(sha)); upload.once("error", reject); setTimeout(() => reject(new Error("Upload timed out")), 10000); });}56 unmodified lines57585960616281 unmodified lines14414514614756 unmodified lines}).passthrough().optional(),});const modelsRaw = z.array(modelConfig).parse(JSON.parse(MODELS));81 unmodified linesdefaultModel: defaultModel;export type BackendModel = Optional<typeof defaultModel, "preprompt" | "parameters">;56 unmodified lines5758596061626381 unmodified lines14514614714856 unmodified lines}).passthrough().optional(),multimodal: z.boolean().default(false),});const modelsRaw = z.array(modelConfig).parse(JSON.parse(MODELS));81 unmodified linesdefaultModel: defaultModel;export type BackendModel = Optional<typeof defaultModel, "preprompt" | "parameters" | "multimodal">;
123import { writable } from "svelte/store";export const pendingMessage = writable<string>("");123456789import { writable } from "svelte/store";export const pendingMessage = writable<| {content: string;files: File[];}| undefined>();
9 unmodified lines101112139 unmodified lineswebSearchId?: WebSearch["_id"]; // legacy versionwebSearch?: WebSearch;score?: -1 | 0 | 1;};9 unmodified lines10111213149 unmodified lineswebSearchId?: WebSearch["_id"]; // legacy versionwebSearch?: WebSearch;score?: -1 | 0 | 1;files?: string[]; // can contain either the hash of the file or the b64 encoded image data on the client side when uploading};
30 unmodified lines31323334353637383930 unmodified linesmessage?: string;};export type MessageUpdate =| FinalAnswer| TextStreamUpdate| AgentUpdate| WebSearchUpdate| StatusUpdate;30 unmodified lines3132333435363738394041424344454630 unmodified linesmessage?: string;};export type ErrorUpdate = {type: "error";message: string;name: string;};export type MessageUpdate =| FinalAnswer| TextStreamUpdate| AgentUpdate| WebSearchUpdate| StatusUpdate| ErrorUpdate;
12 unmodified lines1314151612 unmodified lines| "modelUrl"| "datasetUrl"| "preprompt">;12 unmodified lines131415161712 unmodified lines| "modelUrl"| "datasetUrl"| "preprompt"| "multimodal">;
1234567891011121314const file2base64 = (file: File): Promise<string> => { return new Promise<string>((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => { const dataUrl = reader.result as string; const base64 = dataUrl.split(",")[1]; resolve(base64); }; reader.onerror = (error) => reject(error); });};
export default file2base64;1234import type { Model } from "$lib/types/Model";export const findCurrentModel = (models: Model[], id?: string) =>models.find((m) => m.id === id) ?? models[0];1234import type { Model } from "$lib/types/Model";export const findCurrentModel = (models: Model[], id?: string): Model =>models.find((m) => m.id === id) ?? models[0];
101 unmodified lines102103104105106107101 unmodified linespromptExamples: model.promptExamples,parameters: model.parameters,preprompt: model.preprompt,})),oldModels,user: locals.user && {101 unmodified lines102103104105106107108101 unmodified linespromptExamples: model.promptExamples,parameters: model.parameters,preprompt: model.preprompt,multimodal: model.multimodal,})),oldModels,user: locals.user && {
8 unmodified lines9101112131418 unmodified lines3334353637383916 unmodified lines565758598 unmodified linesexport let data;let loading = false;async function createConversation(message: string) {try {18 unmodified linesconst { conversationId } = await res.json();// Ugly hack to use a store as temp storage, feel free to improve ^^pendingMessage.set(message);// invalidateAll to update list of conversationsawait goto(`${base}/conversation/${conversationId}`, { invalidateAll: true });16 unmodified linescurrentModel={findCurrentModel([...data.models, ...data.oldModels], data.settings.activeModel)}models={data.models}settings={data.settings}/>8 unmodified lines910111213141518 unmodified lines3435363738394041424316 unmodified lines60616263648 unmodified linesexport let data;let loading = false;let files: File[] = [];async function createConversation(message: string) {try {18 unmodified linesconst { conversationId } = await res.json();// Ugly hack to use a store as temp storage, feel free to improve ^^pendingMessage.set({content: message,files,});// invalidateAll to update list of conversationsawait goto(`${base}/conversation/${conversationId}`, { invalidateAll: true });16 unmodified linescurrentModel={findCurrentModel([...data.models, ...data.oldModels], data.settings.activeModel)}models={data.models}settings={data.settings}bind:files/>
13 unmodified lines1415161718192011 unmodified lines32333435363741 unmodified lines79808182838485868788899091923 unmodified lines969798991001011021031042 unmodified lines10710810911011111230 unmodified lines14314414514614714825 unmodified lines17417517617717817953 unmodified lines23323423523623723823924023 unmodified lines26426526626726826927014 unmodified lines28528628728828929013 unmodified linesimport type { Message } from "$lib/types/Message";import type { MessageUpdate, WebSearchUpdate } from "$lib/types/MessageUpdate";import titleUpdate from "$lib/stores/titleUpdate";export let data;let messages = data.messages;11 unmodified lineslet loading = false;let pending = false;async function convFromShared() {try {loading = true;41 unmodified linesretryMessageIndex = messages.length;}// slice up to the point of the retrymessages = [...messages.slice(0, retryMessageIndex),{ from: "user", content: message, id: messageId },];const responseId = randomUUID();const response = await fetch(`${base}/conversation/${$page.params.id}`, {method: "POST",headers: { "Content-Type": "application/json" },3 unmodified linesresponse_id: responseId,is_retry: isRetry,web_search: $webSearchParameters.useSearch,}),});if (!response.body) {throw new Error("Body not defined");}2 unmodified lineserror.set((await response.json())?.message);return;}// eslint-disable-next-line no-undefconst encoder = new TextDecoderStream();const reader = response?.body?.pipeThrough(encoder).getReader();30 unmodified linesif (update.type === "finalAnswer") {finalAnswer = update.text;reader.cancel();invalidate(UrlDependency.Conversation);} else if (update.type === "stream") {pending = false;25 unmodified lines} else if (update.status === "error") {$error = update.message ?? "An error has occurred";}}} catch (parseError) {// in case of parsing error we wait for the next message53 unmodified linesonMount(async () => {// only used in case of creating new conversations (from the parent POST endpoint)if ($pendingMessage) {await writeMessage($pendingMessage);$pendingMessage = "";}});23 unmodified lines}}$: $page.params.id, (isAborted = true);$: title = data.conversations.find((conv) => conv.id === $page.params.id)?.title ?? data.title;</script>14 unmodified linesshared={data.shared}preprompt={data.preprompt}bind:webSearchMessageson:message={onMessage}on:retry={onRetry}on:vote={(event) => voteMessage(event.detail.score, event.detail.id)}13 unmodified lines1415161718192011 unmodified lines323334353637383941 unmodified lines818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161173 unmodified lines1211221231241251261271281291301312 unmodified lines13413513613713813914030 unmodified lines17117217317417517617717825 unmodified lines20420520620720820921021121253 unmodified lines26626726826927027127227327423 unmodified lines29829930030130230330414 unmodified lines31932032132232332432513 unmodified linesimport type { Message } from "$lib/types/Message";import type { MessageUpdate, WebSearchUpdate } from "$lib/types/MessageUpdate";import titleUpdate from "$lib/stores/titleUpdate";import file2base64 from "$lib/utils/file2base64.js";export let data;let messages = data.messages;11 unmodified lineslet loading = false;let pending = false;let files: File[] = [];async function convFromShared() {try {loading = true;41 unmodified linesretryMessageIndex = messages.length;}const module = await import("browser-image-resizer");// currently, only IDEFICS is supported by TGI// the size of images is hardcoded to 224x224 in TGI// this will need to be configurable when support for more models is addedconst resizedImages = await Promise.all(files.map(async (file) => {return await module.readAndCompressImage(file, {maxHeight: 224,maxWidth: 224,quality: 1,}).then(async (el) => await file2base64(el as File));}));// slice up to the point of the retrymessages = [...messages.slice(0, retryMessageIndex),{from: "user",content: message,id: messageId,files: isRetry ? messages[retryMessageIndex].files : resizedImages,},];files = [];const responseId = randomUUID();const response = await fetch(`${base}/conversation/${$page.params.id}`, {method: "POST",headers: { "Content-Type": "application/json" },3 unmodified linesresponse_id: responseId,is_retry: isRetry,web_search: $webSearchParameters.useSearch,files: isRetry ? undefined : resizedImages,}),});files = [];if (!response.body) {throw new Error("Body not defined");}2 unmodified lineserror.set((await response.json())?.message);return;}// eslint-disable-next-line no-undefconst encoder = new TextDecoderStream();const reader = response?.body?.pipeThrough(encoder).getReader();30 unmodified linesif (update.type === "finalAnswer") {finalAnswer = update.text;reader.cancel();loading = false;pending = false;invalidate(UrlDependency.Conversation);} else if (update.type === "stream") {pending = false;25 unmodified lines} else if (update.status === "error") {$error = update.message ?? "An error has occurred";}} else if (update.type === "error") {error.set(update.message);reader.cancel();}} catch (parseError) {// in case of parsing error we wait for the next message53 unmodified linesonMount(async () => {// only used in case of creating new conversations (from the parent POST endpoint)if ($pendingMessage) {files = $pendingMessage.files;await writeMessage($pendingMessage.content);$pendingMessage = undefined;}});23 unmodified lines}}$: $page.params.id, ((isAborted = true), (loading = false));$: title = data.conversations.find((conv) => conv.id === $page.params.id)?.title ?? data.title;</script>14 unmodified linesshared={data.shared}preprompt={data.preprompt}bind:webSearchMessagesbind:fileson:message={onMessage}on:retry={onRetry}on:vote={(event) => voteMessage(event.detail.score, event.detail.id)}
11 unmodified lines12131415161774 unmodified lines9293949596971 unmodified line991001011021031041051061075 unmodified lines1131141151161171181195 unmodified lines125126127128129130137 unmodified lines26826927027127227311 unmodified linesimport type { WebSearch } from "$lib/types/WebSearch";import { abortedGenerations } from "$lib/server/abortedGenerations";import { summarize } from "$lib/server/summarize";export async function POST({ request, locals, params, getClientAddress }) {const id = z.string().parse(params.id);74 unmodified linesid: messageId,is_retry,web_search: webSearch,} = z.object({inputs: z.string().trim().min(1),1 unmodified lineresponse_id: z.optional(z.string().uuid()),is_retry: z.optional(z.boolean()),web_search: z.optional(z.boolean()),}).parse(json);// get the list of messages// while checking for retrieslet messages = (() => {5 unmodified lines}return [...conv.messages.slice(0, retryMessageIdx),{ content: newPrompt, from: "user", id: messageId as Message["id"], updatedAt: new Date() },];} // else append the message at the bottom5 unmodified linesid: (messageId as Message["id"]) || crypto.randomUUID(),createdAt: new Date(),updatedAt: new Date(),},];})() satisfies Message[];137 unmodified linestype: "finalAnswer",text: messages[messages.length - 1].content,});},async cancel() {await collections.conversations.updateOne(11 unmodified lines121314151617181974 unmodified lines9495969798991001 unmodified line1021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421435 unmodified lines1491501511521531541551561571581591601615 unmodified lines167168169170171172173137 unmodified lines31131231331431531631731811 unmodified linesimport type { WebSearch } from "$lib/types/WebSearch";import { abortedGenerations } from "$lib/server/abortedGenerations";import { summarize } from "$lib/server/summarize";import { uploadFile } from "$lib/server/files/uploadFile.js";import sizeof from "image-size";export async function POST({ request, locals, params, getClientAddress }) {const id = z.string().parse(params.id);74 unmodified linesid: messageId,is_retry,web_search: webSearch,files: b64files,} = z.object({inputs: z.string().trim().min(1),1 unmodified lineresponse_id: z.optional(z.string().uuid()),is_retry: z.optional(z.boolean()),web_search: z.optional(z.boolean()),files: z.optional(z.array(z.string())),}).parse(json);// files is an array of base64 strings encoding Blob objects// we need to convert this array to an array of File objectsconst files = b64files?.map((file) => {const blob = Buffer.from(file, "base64");return new File([blob], "image.png");});// check sizesif (files) {const filechecks = await Promise.all(files.map(async (file) => {const dimensions = sizeof(Buffer.from(await file.arrayBuffer()));return (file.size > 2 * 1024 * 1024 ||(dimensions.width ?? 0) > 224 ||(dimensions.height ?? 0) > 224);}));if (filechecks.some((check) => check)) {throw error(413, "File too large, should be <2MB and 224x224 max.");}}let hashes: undefined | string[];if (files) {hashes = await Promise.all(files.map(async (file) => await uploadFile(file, conv)));}// get the list of messages// while checking for retrieslet messages = (() => {5 unmodified lines}return [...conv.messages.slice(0, retryMessageIdx),{content: newPrompt,from: "user",id: messageId as Message["id"],updatedAt: new Date(),files: conv.messages[retryMessageIdx]?.files,},];} // else append the message at the bottom5 unmodified linesid: (messageId as Message["id"]) || crypto.randomUUID(),createdAt: new Date(),updatedAt: new Date(),files: hashes,},];})() satisfies Message[];137 unmodified linestype: "finalAnswer",text: messages[messages.length - 1].content,});return;},async cancel() {await collections.conversations.updateOne(
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import { authCondition } from "$lib/server/auth";import { collections } from "$lib/server/database";import { error } from "@sveltejs/kit";import { ObjectId } from "mongodb";import { z } from "zod";import type { RequestHandler } from "./$types";import { downloadFile } from "$lib/server/files/downloadFile";
export const GET: RequestHandler = async ({ locals, params }) => { const sha256 = z.string().parse(params.sha256);
const userId = locals.user?._id ?? locals.sessionId;
// check user if (!userId) { throw error(401, "Unauthorized"); }
if (params.id.length !== 7) { const convId = new ObjectId(z.string().parse(params.id));
// check if the user has access to the conversation const conv = await collections.conversations.findOne({ _id: convId, ...authCondition(locals), });
if (!conv) { throw error(404, "Conversation not found"); } } else { // check if the user has access to the conversation const conv = await collections.sharedConversations.findOne({ _id: params.id, });
if (!conv) { throw error(404, "Conversation not found"); } }
const { content, mime } = await downloadFile(sha256, params.id);
return new Response(content, { headers: { "Content-Type": mime ?? "application/octet-stream", }, });};42 unmodified lines43444546474842 unmodified linesawait collections.sharedConversations.insertOne(shared);return new Response(JSON.stringify({url: getShareUrl(url, shared._id),42 unmodified lines434445464748495051525354555657585960616263646542 unmodified linesawait collections.sharedConversations.insertOne(shared);// copy files from `${conversation._id}-` to `${shared._id}-`const files = await collections.bucket.find({ filename: { $regex: `${conversation._id}-` } }).toArray();await Promise.all(files.map(async (file) => {const newFilename = file.filename.replace(`${conversation._id}-`, `${shared._id}-`);// copy files from `${conversation._id}-` to `${shared._id}-` by downloading and reuploaidngconst downloadStream = collections.bucket.openDownloadStream(file._id);const uploadStream = collections.bucket.openUploadStream(newFilename, {metadata: { ...file.metadata, conversation: shared._id.toString() },});downloadStream.pipe(uploadStream);}));return new Response(JSON.stringify({url: getShareUrl(url, shared._id),