Spaces:
Build error
Build error
Update components/chat_interface.py
Browse files- components/chat_interface.py +44 -10
components/chat_interface.py
CHANGED
|
@@ -1,21 +1,41 @@
|
|
| 1 |
-
# components/chat_interface.py
|
| 2 |
import streamlit as st
|
| 3 |
from typing import List, Dict
|
| 4 |
import anthropic
|
|
|
|
| 5 |
|
| 6 |
class ChatInterface:
|
| 7 |
def __init__(self, vector_store):
|
| 8 |
self.vector_store = vector_store
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
if "messages" not in st.session_state:
|
| 13 |
st.session_state.messages = []
|
|
|
|
|
|
|
| 14 |
|
| 15 |
def render(self):
|
| 16 |
-
"""Render chat interface"""
|
| 17 |
st.subheader("Chat with Documents")
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
# Display chat history
|
| 20 |
for message in st.session_state.messages:
|
| 21 |
with st.chat_message(message["role"]):
|
|
@@ -33,16 +53,17 @@ class ChatInterface:
|
|
| 33 |
results = self.vector_store.similarity_search(prompt, k=3)
|
| 34 |
context = "\n\n".join([r["metadata"]["text"] for r in results])
|
| 35 |
|
| 36 |
-
# Generate response
|
| 37 |
with st.chat_message("assistant"):
|
| 38 |
with st.spinner("Thinking..."):
|
| 39 |
-
response = self.generate_response(prompt, context)
|
| 40 |
st.markdown(response)
|
| 41 |
st.session_state.messages.append({"role": "assistant", "content": response})
|
| 42 |
|
| 43 |
-
def generate_response(self, prompt: str, context: str) -> str:
|
| 44 |
-
"""Generate response using Claude"""
|
| 45 |
try:
|
|
|
|
| 46 |
message = self.client.messages.create(
|
| 47 |
model="claude-3-sonnet-20240229",
|
| 48 |
max_tokens=2000,
|
|
@@ -59,7 +80,20 @@ class ChatInterface:
|
|
| 59 |
Please provide a detailed response with references to specific parts of the documents when relevant."""
|
| 60 |
}]
|
| 61 |
)
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
except Exception as e:
|
| 64 |
st.error(f"Error generating response: {str(e)}")
|
| 65 |
return "I apologize, but I encountered an error generating the response."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
from typing import List, Dict
|
| 3 |
import anthropic
|
| 4 |
+
import os
|
| 5 |
|
| 6 |
class ChatInterface:
|
| 7 |
def __init__(self, vector_store):
|
| 8 |
self.vector_store = vector_store
|
| 9 |
+
|
| 10 |
+
# Initialize Anthropic client using environment variable
|
| 11 |
+
try:
|
| 12 |
+
api_key = os.getenv("ANTHROPIC_API_KEY")
|
| 13 |
+
if not api_key:
|
| 14 |
+
st.error("Please set the ANTHROPIC_API_KEY in your environment variables.")
|
| 15 |
+
st.stop()
|
| 16 |
+
self.client = anthropic.Anthropic(api_key=api_key)
|
| 17 |
+
except Exception as e:
|
| 18 |
+
st.error(f"Error initializing Anthropic client: {str(e)}")
|
| 19 |
+
st.stop()
|
| 20 |
+
|
| 21 |
+
# Initialize chat history and analyzed documents
|
| 22 |
if "messages" not in st.session_state:
|
| 23 |
st.session_state.messages = []
|
| 24 |
+
if "analyzed_documents" not in st.session_state:
|
| 25 |
+
st.session_state.analyzed_documents = []
|
| 26 |
|
| 27 |
def render(self):
|
| 28 |
+
"""Render chat interface with analyzed documents and history."""
|
| 29 |
st.subheader("Chat with Documents")
|
| 30 |
|
| 31 |
+
# Display analyzed documents
|
| 32 |
+
with st.expander("Analyzed Documents", expanded=True):
|
| 33 |
+
if st.session_state.analyzed_documents:
|
| 34 |
+
for doc in st.session_state.analyzed_documents:
|
| 35 |
+
st.markdown(f"- **{doc['name']}**")
|
| 36 |
+
else:
|
| 37 |
+
st.info("No documents analyzed yet.")
|
| 38 |
+
|
| 39 |
# Display chat history
|
| 40 |
for message in st.session_state.messages:
|
| 41 |
with st.chat_message(message["role"]):
|
|
|
|
| 53 |
results = self.vector_store.similarity_search(prompt, k=3)
|
| 54 |
context = "\n\n".join([r["metadata"]["text"] for r in results])
|
| 55 |
|
| 56 |
+
# Generate response with references
|
| 57 |
with st.chat_message("assistant"):
|
| 58 |
with st.spinner("Thinking..."):
|
| 59 |
+
response = self.generate_response(prompt, context, results)
|
| 60 |
st.markdown(response)
|
| 61 |
st.session_state.messages.append({"role": "assistant", "content": response})
|
| 62 |
|
| 63 |
+
def generate_response(self, prompt: str, context: str, results: List[Dict]) -> str:
|
| 64 |
+
"""Generate response using Claude with document references."""
|
| 65 |
try:
|
| 66 |
+
# Call the Claude API for response generation
|
| 67 |
message = self.client.messages.create(
|
| 68 |
model="claude-3-sonnet-20240229",
|
| 69 |
max_tokens=2000,
|
|
|
|
| 80 |
Please provide a detailed response with references to specific parts of the documents when relevant."""
|
| 81 |
}]
|
| 82 |
)
|
| 83 |
+
response_content = message.content[0].text
|
| 84 |
+
|
| 85 |
+
# Append document references to the response
|
| 86 |
+
references = [
|
| 87 |
+
f"{idx + 1}. {res['metadata']['text'][:200]}... (Reference: {res['metadata'].get('reference', 'N/A')})"
|
| 88 |
+
for idx, res in enumerate(results)
|
| 89 |
+
]
|
| 90 |
+
references_text = "\n\nReferences:\n" + "\n".join(references)
|
| 91 |
+
return response_content + references_text
|
| 92 |
except Exception as e:
|
| 93 |
st.error(f"Error generating response: {str(e)}")
|
| 94 |
return "I apologize, but I encountered an error generating the response."
|
| 95 |
+
|
| 96 |
+
def add_analyzed_document(self, doc: Dict):
|
| 97 |
+
"""Add a document to the list of analyzed documents."""
|
| 98 |
+
if doc not in st.session_state.analyzed_documents:
|
| 99 |
+
st.session_state.analyzed_documents.append(doc)
|