vsj0702 commited on
Commit
a1f96e4
·
verified ·
1 Parent(s): 3d3e74a

Fixing error

Browse files
Files changed (1) hide show
  1. chatbot.py +39 -104
chatbot.py CHANGED
@@ -3,38 +3,27 @@ from groq import Groq
3
  from langchain_groq import ChatGroq
4
  from langchain_core.prompts import ChatPromptTemplate
5
  from langchain_core.output_parsers import StrOutputParser
 
6
  import edge_tts
7
  import asyncio
8
  import os
9
- from html import escape
10
 
11
  GROQ_API_KEY = os.getenv('GROQ_API_KEY')
12
 
13
-
14
  class CodeAssistantBot:
15
  def __init__(self):
16
  self.client = Groq(api_key=GROQ_API_KEY)
17
  self.model = ChatGroq(model="llama-3.3-70b-versatile", temperature=0.6)
18
-
19
- # Initialize prompts
20
  self.analysis_prompt = ChatPromptTemplate.from_messages([
21
- ("system",
22
- """You are an expert code assistant. Analyze the code and context provided,
23
- then give clear, helpful responses. Keep responses concise and focused on the code."""),
24
- ("user", """Code: {code}
25
- Output: {output}
26
- Error: {error}
27
- Question: {question}""")
28
  ])
29
-
30
  self.summary_prompt = ChatPromptTemplate.from_messages([
31
- ("system",
32
- """Summarize the conversation focusing on key technical points and insights.
33
- Keep it brief and clear."""),
34
  ("user", "Conversation: {conversation}")
35
  ])
36
 
37
- def analyze_code(self, code: str, output: str, error: str, question: str) -> str:
38
  try:
39
  parser = StrOutputParser()
40
  chain = self.analysis_prompt | self.model | parser
@@ -45,115 +34,61 @@ class CodeAssistantBot:
45
  'question': question
46
  })
47
  except Exception as e:
48
- return f"Sorry, I encountered an error: {str(e)}"
49
-
50
- def summarize_conversation(self, conversation: list) -> str:
51
- try:
52
- parser = StrOutputParser()
53
- chain = self.summary_prompt | self.model | parser
54
- formatted_conv = "\n".join([f"Q: {q}\nA: {a}" for q, a in conversation])
55
- return chain.invoke({'conversation': formatted_conv})
56
- except Exception as e:
57
- return f"Could not generate summary: {str(e)}"
58
 
59
-
60
- async def text_to_speech(text: str, filename: str):
61
  voice = "fr-FR-VivienneMultilingualNeural"
62
- communicate = edge_tts.Communicate(text, voice)
63
- await communicate.save(filename)
64
 
65
 
66
- def render_chatbot(code: str, output: str, error: str):
67
- """Render the chatbot UI in a polished, scrollable panel with support for code blocks."""
68
- # --- session state ---
69
  st.session_state.setdefault('conversation', [])
70
  st.session_state.setdefault('audio_count', 0)
71
 
72
- # --- CSS styling ---
73
- st.markdown("""
74
- <style>
75
- .chat-container {
76
- display: flex;
77
- flex-direction: column;
78
- gap: 0.75rem;
79
- max-height: 480px;
80
- overflow-y: auto;
81
- padding: 1rem;
82
- border-radius: 8px;
83
- background-color: inherit;
84
- border: 1px solid;
85
- animation: fadeIn 0.5s ease;
86
- }
87
- .chat-message {
88
- max-width: 90%;
89
- padding: 0.75rem 1rem;
90
- border-radius: 12px;
91
- position: relative;
92
- animation: popIn 0.3s ease;
93
- }
94
- .user-message {
95
- background: rgba(100, 149, 237, 0.2);
96
- align-self: flex-end;
97
- }
98
- .bot-message {
99
- background: rgba(200, 200, 200, 0.2);
100
- align-self: flex-start;
101
- }
102
- .chat-message pre {
103
- background: rgba(0,0,0,0.1);
104
- padding: 0.5rem;
105
- border-radius: 4px;
106
- overflow-x: auto;
107
- }
108
- @keyframes fadeIn {
109
- from { opacity: 0; } to { opacity: 1; }
110
- }
111
- @keyframes popIn {
112
- from { transform: scale(0.95); opacity: 0; }
113
- to { transform: scale(1); opacity: 1; }
114
- }
115
- </style>
116
- """, unsafe_allow_html=True)
117
-
118
- # --- input area ---
119
- cols = st.columns([4, 1], gap='small')
120
- with cols[0]:
121
  question = st.text_input("Ask your question…", key="chat_input")
122
- with cols[1]:
123
  send = st.button("🚀")
124
 
125
- # --- handle send ---
126
  if send and question:
127
  bot = CodeAssistantBot()
128
- answer = bot.analyze_code(code, output, error, question)
129
- st.session_state.conversation.append((question, answer))
130
- # summary & tts can go here
131
 
132
- # --- render chat ---
133
  st.markdown('<div class="chat-container">', unsafe_allow_html=True)
134
  for q, a in st.session_state.conversation:
135
- # user bubble
136
- html_q = f'<div class="chat-message user-message">{escape(q)}</div>'
137
- st.markdown(html_q, unsafe_allow_html=True)
138
- # bot bubble: convert code fences to <pre>
139
- def render_bot(text):
140
  parts = text.split('```')
141
- html = ''
142
  for i, part in enumerate(parts):
143
- if i % 2 == 0:
144
- html += escape(part)
 
 
 
 
 
145
  else:
146
- code_block = escape(part)
147
- html += f'<pre><code>{code_block}</code></pre>'
148
- return html
149
- html_a = f'<div class="chat-message bot-message">{render_bot(a)}</div>'
150
- st.markdown(html_a, unsafe_allow_html=True)
151
  st.markdown('</div>', unsafe_allow_html=True)
152
 
153
- # --- auto-scroll ---
154
  st.markdown("""
155
  <script>
156
  const c = window.parent.document.querySelector('.chat-container');
157
- if(c) { c.scrollTop = c.scrollHeight; }
158
  </script>
159
- """, unsafe_allow_html=True)
 
3
  from langchain_groq import ChatGroq
4
  from langchain_core.prompts import ChatPromptTemplate
5
  from langchain_core.output_parsers import StrOutputParser
6
+ from html import escape
7
  import edge_tts
8
  import asyncio
9
  import os
 
10
 
11
  GROQ_API_KEY = os.getenv('GROQ_API_KEY')
12
 
 
13
  class CodeAssistantBot:
14
  def __init__(self):
15
  self.client = Groq(api_key=GROQ_API_KEY)
16
  self.model = ChatGroq(model="llama-3.3-70b-versatile", temperature=0.6)
 
 
17
  self.analysis_prompt = ChatPromptTemplate.from_messages([
18
+ ("system", "You are an expert code assistant. Keep responses concise."),
19
+ ("user", "Code: {code}\nOutput: {output}\nError: {error}\nQuestion: {question}")
 
 
 
 
 
20
  ])
 
21
  self.summary_prompt = ChatPromptTemplate.from_messages([
22
+ ("system", "Summarize key technical points."),
 
 
23
  ("user", "Conversation: {conversation}")
24
  ])
25
 
26
+ def analyze_code(self, code, output, error, question):
27
  try:
28
  parser = StrOutputParser()
29
  chain = self.analysis_prompt | self.model | parser
 
34
  'question': question
35
  })
36
  except Exception as e:
37
+ return f"Error: {e}"
 
 
 
 
 
 
 
 
 
38
 
39
+ async def text_to_speech(text, filename):
 
40
  voice = "fr-FR-VivienneMultilingualNeural"
41
+ await edge_tts.Communicate(text, voice).save(filename)
 
42
 
43
 
44
+ def render_chatbot(code, output, error):
45
+ """Render the chatbot UI with code-block support and no deprecated APIs."""
 
46
  st.session_state.setdefault('conversation', [])
47
  st.session_state.setdefault('audio_count', 0)
48
 
49
+ # Input row
50
+ c1, c2 = st.columns([4,1], gap='small')
51
+ with c1:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  question = st.text_input("Ask your question…", key="chat_input")
53
+ with c2:
54
  send = st.button("🚀")
55
 
56
+ # Handle send
57
  if send and question:
58
  bot = CodeAssistantBot()
59
+ response = bot.analyze_code(code, output, error, question)
60
+ st.session_state.conversation.append((question, response))
 
61
 
62
+ # Chat container
63
  st.markdown('<div class="chat-container">', unsafe_allow_html=True)
64
  for q, a in st.session_state.conversation:
65
+ # User message
66
+ st.markdown(f'<div class="chat-message user-message">{escape(q)}</div>', unsafe_allow_html=True)
67
+
68
+ # Bot message with code formatting
69
+ def format_response(text):
70
  parts = text.split('```')
71
+ result = ''
72
  for i, part in enumerate(parts):
73
+ if i % 2 == 1:
74
+ # Remove optional language tag
75
+ lines = part.splitlines()
76
+ if lines and lines[0].isalpha():
77
+ lines = lines[1:]
78
+ code_html = escape("\n".join(lines))
79
+ result += f'<pre><code>{code_html}</code></pre>'
80
  else:
81
+ result += escape(part)
82
+ return result
83
+
84
+ formatted = format_response(a)
85
+ st.markdown(f'<div class="chat-message bot-message">{formatted}</div>', unsafe_allow_html=True)
86
  st.markdown('</div>', unsafe_allow_html=True)
87
 
88
+ # Auto-scroll
89
  st.markdown("""
90
  <script>
91
  const c = window.parent.document.querySelector('.chat-container');
92
+ if (c) c.scrollTop = c.scrollHeight;
93
  </script>
94
+ """, unsafe_allow_html=True)