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 lines626364656566676861 unmodified lines
RUN pip install --no-cache-dir --upgrade -r requirements.txtRUN pip install --no-cache-dir -r requirements.txt
12345678910111213141516171819202122232425262728293031323334353637383940414243444546471249345653789101112571314151617186119202122652324252627692829303132333435367778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121373839401254142434412945464748491335051525354137555657585960141616263646566145676869701497172737415375767778157798081828316184858687881658990919216993949596173979899100101102177103104105106107181108109110111185112113114115116189117118119120121122123124125126127128197129130131132133134201135136137138139140205141142143144209145146147148149150213151152153154217155156157221158159160161162163164165166167168229169170171172173174233175176177178237179180181182241183184185186187188189190191192193194195196249197198199200253201202203204205206257207208209210261211212213265import chainlit as cl
from typing import Optional
import time
# Store conversation history
conversation_memory = []
@cl.on_chat_start
async def start():
"""Initializes the chat session"""
# Send an initial message
await cl.Message(
import os
content="👋 Hello! I'm your AI assistant. How can I help you today?",from typing import List
author="Assistant"from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.vectorstores import Chroma
).send()from langchain.chains import (
ConversationalRetrievalChain,
)
from langchain.chat_models import ChatOpenAI
# Set some session variablesfrom langchain.docstore.document import Document
from langchain.memory import ChatMessageHistory, ConversationBufferMemory
cl.user_session.set("conversation_started", True)
import chainlit as cl
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
@cl.on_message
async def main(message: cl.Message):
"""Main message handler"""
# Simulate some processing time
with cl.Step("Processing...") as step:
time.sleep(1) # Simulated delay
step.output = "Processed message"
# Store message in conversation history
conversation_memory.append({
"role": "user",text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
"content": message.content
@cl.on_chat_start
})async def on_chat_start():
files = None
# Wait for the user to upload a file
while files == None:
# Create a response files = await cl.AskFileMessage(
content="Please upload a text file to begin!",
accept=["text/plain"],
response = f"I received your message: '{message.content}'. This is a demo response." max_size_mb=20,
timeout=180,
).send()
file = files[0]
# Store response in conversation history
msg = cl.Message(content=f"Processing `{file.name}`...")
conversation_memory.append({ await msg.send()
"role": "assistant", with open(file.path, "r", encoding="utf-8") as f:
text = f.read()
"content": response
# Split the text into chunks
texts = text_splitter.split_text(text)
})
# Create a metadata for each chunk
metadatas = [{"source": f"{i}-pl"} for i in range(len(texts))]
# Send response with typing effect # Create a Chroma vector store
embeddings = OpenAIEmbeddings()
docsearch = await cl.make_async(Chroma.from_texts)(
await cl.Message( texts, embeddings, metadatas=metadatas
)
content=response,
message_history = ChatMessageHistory()
author="Assistant"
memory = ConversationBufferMemory(
memory_key="chat_history",
).send() output_key="answer",
chat_memory=message_history,
return_messages=True,
)
# Create a chain that uses the Chroma vector store
@cl.password_auth_callback chain = ConversationalRetrievalChain.from_llm(
ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0, streaming=True),
chain_type="stuff",
def auth_callback(username: str, password: str) -> Optional[cl.User]: retriever=docsearch.as_retriever(),
memory=memory,
return_source_documents=True,
"""Basic authentication handler""" )
# This is a simple example - in production, use proper authentication # Let the user know that the system is ready
msg.content = f"Processing `{file.name}` done. You can now ask questions!"
await msg.update()
if username == "demo" and password == "password":
cl.user_session.set("chain", chain)
return cl.User(identifier="demo", metadata={"role": "user"})
return None
@cl.on_message
async def main(message: cl.Message):
chain = cl.user_session.get("chain") # type: ConversationalRetrievalChain
cb = cl.AsyncLangchainCallbackHandler()
@cl.on_chat_end res = await chain.acall(message.content, callbacks=[cb])
answer = res["answer"]
source_documents = res["source_documents"] # type: List[Document]
async def end():
text_elements = [] # type: List[cl.Text]
"""Cleanup when chat ends"""
if source_documents:
await cl.Message(content="👋 Thank you for chatting! Goodbye!").send() for source_idx, source_doc in enumerate(source_documents):
source_name = f"source_{source_idx}"
# Create the text element referenced in the message
text_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]
# Custom action handler example
if source_names:
@cl.action_callback("feedback") answer += f"\nSources: {', '.join(source_names)}"
else:
answer += "\nNo sources found"
async def on_action(action):
await cl.Message(content=answer, elements=text_elements).send()
"""Handles custom feedback action"""
await cl.Message(content=f"Received feedback: {action.value}").send()11234565789108911fastapichainlit==1.3.0
langchain
langchain-community
uvicorn[standard]pydantic==2.7.3
pydantic-settings==2.6.1
chainlitpydantic_core==2.18.4Dockerfile+1-1
app.py+79-131
requirements.txt+6-4