File size: 9,605 Bytes
a1bb249
80c4f7e
a1bb249
80c4f7e
 
a1bb249
 
80c4f7e
552b1b4
80c4f7e
a1bb249
 
 
 
 
 
 
 
 
6b6ba40
 
 
8d3cdc2
a1bb249
 
6b6ba40
 
a1bb249
 
 
 
80c4f7e
a1bb249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80c4f7e
a1bb249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d3cdc2
a1bb249
8d3cdc2
a1bb249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80c4f7e
a1bb249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80c4f7e
a1bb249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80c4f7e
a1bb249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80c4f7e
a1bb249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6f89d2
 
a1bb249
a6f89d2
33e75e2
a6f89d2
 
a1bb249
 
33e75e2
a6f89d2
33e75e2
 
 
 
 
 
 
 
a6f89d2
a1bb249
33e75e2
 
a1bb249
33e75e2
a6f89d2
33e75e2
a1bb249
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# app.py
# Advanced AI R&D Assistant for Hugging Face Spaces
#
# This app leverages LangGraph, DeepSeek-R1 via text-based function calling, and Agentic RAG.
# API keys are securely loaded via environment variables.
#
# To deploy:
# 1. Add your API key to Hugging Face Space secrets with the key DEEP_SEEK_API.
# 2. Ensure your requirements.txt includes langchain-community.
# 3. Run the app with Streamlit.

import os
import re
import logging
import streamlit as st
import requests
from typing import Sequence
from typing_extensions import TypedDict, Annotated

# Updated imports for LangChain
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import Chroma
from langchain.schema import HumanMessage, AIMessage
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.tools.retriever import create_retriever_tool

# Imports for LangGraph remain the same
from langgraph.graph import END, StateGraph, START
from langgraph.prebuilt import ToolNode
from langgraph.graph.message import add_messages

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# --- Dummy Data Setup ---
research_texts = [
    "Research Report: Results of a New AI Model Improving Image Recognition Accuracy to 98%",
    "Academic Paper Summary: Why Transformers Became the Mainstream Architecture in Natural Language Processing",
    "Latest Trends in Machine Learning Methods Using Quantum Computing"
]

development_texts = [
    "Project A: UI Design Completed, API Integration in Progress",
    "Project B: Testing New Feature X, Bug Fixes Needed",
    "Product Y: In the Performance Optimization Stage Before Release"
]

# --- Preprocessing & Embeddings ---
splitter = RecursiveCharacterTextSplitter(chunk_size=100, chunk_overlap=10)
research_docs = splitter.create_documents(research_texts)
development_docs = splitter.create_documents(development_texts)

embeddings = OpenAIEmbeddings(model="text-embedding-3-large")

research_vectorstore = Chroma.from_documents(
    documents=research_docs,
    embedding=embeddings,
    collection_name="research_collection"
)
development_vectorstore = Chroma.from_documents(
    documents=development_docs,
    embedding=embeddings,
    collection_name="development_collection"
)

research_retriever = research_vectorstore.as_retriever()
development_retriever = development_vectorstore.as_retriever()

research_tool = create_retriever_tool(
    research_retriever,
    "research_db_tool",
    "Search information from the research database."
)
development_tool = create_retriever_tool(
    development_retriever,
    "development_db_tool",
    "Search information from the development database."
)
tools = [research_tool, development_tool]

# --- Agent and Workflow Functions ---
# Note: We are using only AIMessage and HumanMessage for our message types.
class AgentState(TypedDict):
    messages: Annotated[Sequence[AIMessage | HumanMessage], add_messages]

def agent(state: AgentState):
    logger.info("Agent invoked")
    messages = state["messages"]
    user_message = messages[0][1] if isinstance(messages[0], tuple) else messages[0].content

    prompt = f"""Given this user question: "{user_message}"
If it's about research or academic topics, respond EXACTLY in this format:
SEARCH_RESEARCH: <search terms>

If it's about development status, respond EXACTLY in this format:
SEARCH_DEV: <search terms>

Otherwise, just answer directly.
"""
    headers = {
        "Accept": "application/json",
        "Authorization": f"Bearer {os.environ.get('DEEP_SEEK_API')}",
        "Content-Type": "application/json"
    }
    data = {
        "model": "deepseek-chat",
        "messages": [{"role": "user", "content": prompt}],
        "temperature": 0.7,
        "max_tokens": 1024
    }
    response = requests.post(
        "https://api.deepseek.com/v1/chat/completions",
        headers=headers,
        json=data,
        verify=False
    )
    if response.status_code == 200:
        response_text = response.json()['choices'][0]['message']['content']
        logger.info(f"DeepSeek response: {response_text}")
        if "SEARCH_RESEARCH:" in response_text:
            query = response_text.split("SEARCH_RESEARCH:")[1].strip()
            results = research_retriever.invoke(query)
            return {"messages": [AIMessage(content=f'Action: research_db_tool\n{{"query": "{query}"}}\n\nResults: {str(results)}')]}
        elif "SEARCH_DEV:" in response_text:
            query = response_text.split("SEARCH_DEV:")[1].strip()
            results = development_retriever.invoke(query)
            return {"messages": [AIMessage(content=f'Action: development_db_tool\n{{"query": "{query}"}}\n\nResults: {str(results)}')]}
        else:
            return {"messages": [AIMessage(content=response_text)]}
    else:
        error_msg = f"DeepSeek API call failed: {response.text}"
        logger.error(error_msg)
        raise Exception(error_msg)

def simple_grade_documents(state: AgentState):
    last_message = state["messages"][-1]
    logger.info(f"Grading message: {last_message.content}")
    if "Results: [Document" in last_message.content:
        return "generate"
    else:
        return "rewrite"

def generate(state: AgentState):
    logger.info("Generating final answer")
    messages = state["messages"]
    question = messages[0].content if not isinstance(messages[0], tuple) else messages[0][1]
    last_message = messages[-1]
    docs = ""
    if "Results: [" in last_message.content:
        docs = last_message.content[last_message.content.find("Results: ["):]
    headers = {
        "Accept": "application/json",
        "Authorization": f"Bearer {os.environ.get('DEEP_SEEK_API')}",
        "Content-Type": "application/json"
    }
    prompt = f"""Based on these research documents, summarize the latest advancements in AI:
Question: {question}
Documents: {docs}
Focus on extracting and synthesizing the key findings from the research papers.
"""
    data = {
        "model": "deepseek-chat",
        "messages": [{"role": "user", "content": prompt}],
        "temperature": 0.7,
        "max_tokens": 1024
    }
    response = requests.post(
        "https://api.deepseek.com/v1/chat/completions",
        headers=headers,
        json=data,
        verify=False
    )
    if response.status_code == 200:
        response_text = response.json()['choices'][0]['message']['content']
        return {"messages": [AIMessage(content=response_text)]}
    else:
        error_msg = f"DeepSeek API generate call failed: {response.text}"
        logger.error(error_msg)
        raise Exception(error_msg)

def rewrite(state: AgentState):
    logger.info("Rewriting question")
    original_question = state["messages"][0].content if state["messages"] else "N/A"
    headers = {
        "Accept": "application/json",
        "Authorization": f"Bearer {os.environ.get('DEEP_SEEK_API')}",
        "Content-Type": "application/json"
    }
    data = {
        "model": "deepseek-chat",
        "messages": [{"role": "user", "content": f"Rewrite this question to be more specific and clearer: {original_question}"}],
        "temperature": 0.7,
        "max_tokens": 1024
    }
    response = requests.post(
        "https://api.deepseek.com/v1/chat/completions",
        headers=headers,
        json=data,
        verify=False
    )
    if response.status_code == 200:
        response_text = response.json()['choices'][0]['message']['content']
        return {"messages": [AIMessage(content=response_text)]}
    else:
        error_msg = f"DeepSeek API rewrite call failed: {response.text}"
        logger.error(error_msg)
        raise Exception(error_msg)

tools_pattern = re.compile(r"Action: .*")
def custom_tools_condition(state: AgentState):
    last_message = state["messages"][-1]
    if tools_pattern.match(last_message.content):
        return "tools"
    return END

# Build the workflow with LangGraph's StateGraph
workflow = StateGraph(AgentState)
workflow.add_node("agent", agent)
retrieve_node = ToolNode(tools)
workflow.add_node("retrieve", retrieve_node)
workflow.add_node("rewrite", rewrite)
workflow.add_node("generate", generate)
workflow.add_edge(START, "agent")
workflow.add_conditional_edges("agent", custom_tools_condition, {"tools": "retrieve", END: END})
workflow.add_conditional_edges("retrieve", simple_grade_documents)
workflow.add_edge("generate", END)
workflow.add_edge("rewrite", "agent")
app_workflow = workflow.compile()

def process_question(user_question, app, config):
    events = []
    for event in app.stream({"messages": [("user", user_question)]}, config):
        events.append(event)
    return events

# --- Streamlit UI ---
import streamlit as st

def main():
    st.set_page_config(
        page_title="High Contrast Chatbot",
        layout="wide",
        initial_sidebar_state="expanded"
    )

    # Force all text to be black (#000) and backgrounds to be white (#fff)
    st.markdown("""
    <style>
    /* Apply to the entire app */
    html, body, [class*="css"]  {
        color: #000000 !important;          /* Black text */
        background-color: #ffffff !important; /* White background */
        text-shadow: none !important;       /* Remove any faint shadows */
    }
    </style>
    """, unsafe_allow_html=True)

    st.title("High Contrast Chatbot")
    st.markdown("Enter your question below. All text should now be clearly visible.")

    user_query = st.text_area("Ask me something:")
    if st.button("Submit"):
        st.write("You asked:", user_query)

if __name__ == "__main__":
    main()