Spaces:
Runtime error
Runtime error
daniel Foley commited on
Commit ·
91b7015
1
Parent(s): 74eb75e
Sample Chainlit app placeholder
Browse filesCo-authored-by: Dan dfoley3838@gmail.com
Co-authored-by: Brandon bmv2021@bu.edu
Co-authored-by: Enrico enricoll@bu.edu
Files changed (3)
- Dockerfile+1-1
- app.py+79-131
- requirements.txt+6-4
61 unmodified lines6263646566676861 unmodified linesRUN pip install --no-cache-dir --upgrade -r requirements.txt61 unmodified lines6263646566676861 unmodified linesRUN pip install --no-cache-dir -r requirements.txt
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265import chainlit as clfrom typing import Optionalimport time# Store conversation historyconversation_memory = []@cl.on_chat_startasync def start():"""Initializes the chat session"""# Send an initial messageawait cl.Message(content="👋 Hello! I'm your AI assistant. How can I help you today?",author="Assistant").send()# Set some session variablescl.user_session.set("conversation_started", True)@cl.on_messageasync def main(message: cl.Message):"""Main message handler"""# Simulate some processing timewith cl.Step("Processing...") as step:time.sleep(1) # Simulated delaystep.output = "Processed message"# Store message in conversation historyconversation_memory.append({"role": "user","content": message.content})# Create a responseresponse = f"I received your message: '{message.content}'. This is a demo response."# Store response in conversation historyconversation_memory.append({"role": "assistant","content": response})# Send response with typing effectawait cl.Message(content=response,author="Assistant").send()@cl.password_auth_callbackdef auth_callback(username: str, password: str) -> Optional[cl.User]:"""Basic authentication handler"""# This is a simple example - in production, use proper authenticationif username == "demo" and password == "password":return cl.User(identifier="demo", metadata={"role": "user"})return None@cl.on_chat_endasync def end():"""Cleanup when chat ends"""await cl.Message(content="👋 Thank you for chatting! Goodbye!").send()# Custom action handler example@cl.action_callback("feedback")async def on_action(action):"""Handles custom feedback action"""await cl.Message(content=f"Received feedback: {action.value}").send()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213import osfrom typing import Listfrom langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain.vectorstores import Chromafrom langchain.chains import (ConversationalRetrievalChain,)from langchain.chat_models import ChatOpenAIfrom langchain.docstore.document import Documentfrom langchain.memory import ChatMessageHistory, ConversationBufferMemoryimport chainlit as clos.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)@cl.on_chat_startasync def on_chat_start():files = None# Wait for the user to upload a filewhile files == None:files = await cl.AskFileMessage(content="Please upload a text file to begin!",accept=["text/plain"],max_size_mb=20,timeout=180,).send()file = files[0]msg = cl.Message(content=f"Processing `{file.name}`...")await msg.send()with open(file.path, "r", encoding="utf-8") as f:text = f.read()# Split the text into chunkstexts = text_splitter.split_text(text)# Create a metadata for each chunkmetadatas = [{"source": f"{i}-pl"} for i in range(len(texts))]# Create a Chroma vector storeembeddings = OpenAIEmbeddings()docsearch = await cl.make_async(Chroma.from_texts)(texts, embeddings, metadatas=metadatas)message_history = ChatMessageHistory()memory = ConversationBufferMemory(memory_key="chat_history",output_key="answer",chat_memory=message_history,return_messages=True,)# Create a chain that uses the Chroma vector storechain = ConversationalRetrievalChain.from_llm(ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0, streaming=True),chain_type="stuff",retriever=docsearch.as_retriever(),memory=memory,return_source_documents=True,)# Let the user know that the system is readymsg.content = f"Processing `{file.name}` done. You can now ask questions!"await msg.update()cl.user_session.set("chain", chain)@cl.on_messageasync def main(message: cl.Message):chain = cl.user_session.get("chain") # type: ConversationalRetrievalChaincb = cl.AsyncLangchainCallbackHandler()res = await chain.acall(message.content, callbacks=[cb])answer = res["answer"]source_documents = res["source_documents"] # type: List[Document]text_elements = [] # type: List[cl.Text]if source_documents:for source_idx, source_doc in enumerate(source_documents):source_name = f"source_{source_idx}"# Create the text element referenced in the messagetext_elements.append(cl.Text(content=source_doc.page_content, name=source_name, display="side"))source_names = [text_el.name for text_el in text_elements]if source_names:answer += f"\nSources: {', '.join(source_names)}"else:answer += "\nNo sources found"await cl.Message(content=answer, elements=text_elements).send()
123456789fastapiuvicorn[standard]chainlit1234567891011chainlit==1.3.0langchainlangchain-communitypydantic==2.7.3pydantic-settings==2.6.1pydantic_core==2.18.4
Dockerfile+1-1
app.py+79-131
requirements.txt+6-4