iarfmoose3 commited on
Commit
a8703fa
·
verified ·
1 Parent(s): 4721c37

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -50
app.py CHANGED
@@ -14,7 +14,6 @@ SYSTEM_PROMPT_BASE = (
14
  # ----------------------------------------------------------------------------
15
  # Together Client Initialization with API Key
16
  # ----------------------------------------------------------------------------
17
- # Expecting TOGETHER_API_KEY set in environment (e.g., Gradio Secrets)
18
  api_key = os.environ.get("TOGETHER_API_KEY")
19
  if not api_key:
20
  raise ValueError("Missing TOGETHER_API_KEY environment variable")
@@ -23,94 +22,82 @@ together_client = Together(api_key=api_key)
23
  # ----------------------------------------------------------------------------
24
  # In-Memory Context Tracking
25
  # ----------------------------------------------------------------------------
26
- conversation_history = [] # List of {'role': str, 'content': str}
27
- context_summary = "" # Running summary of the conversation
28
 
29
  # ----------------------------------------------------------------------------
30
  # Helper: Update Context Summary
31
  # ----------------------------------------------------------------------------
32
  def update_summary(history):
33
- """
34
- Call the model to generate a concise summary of the conversation history.
35
- """
36
- # Build summarization prompt
37
  messages = [
38
  {"role": "system", "content": SYSTEM_PROMPT_BASE},
39
  {"role": "user", "content": (
40
  "Summarize the following cybersecurity conversation in 3-5 bullet points, "
41
  "focusing on key decisions and context:\n" +
42
- "\n".join([f"{msg['role']}: {msg['content']}" for msg in history])
43
  )}
44
  ]
45
-
46
- response = together_client.chat.completions.create(
47
  model=MODEL_NAME,
48
  messages=messages,
49
  stream=False
50
  )
51
- # Extract full summary text
52
- summary_text = response.choices[0].message.content
53
- return summary_text.strip()
54
 
55
  # ----------------------------------------------------------------------------
56
- # Core Chat Functionality
57
  # ----------------------------------------------------------------------------
58
- def append_and_stream(user_input: str):
59
- global context_summary
60
-
61
- # Frame as cybersecurity expert if not already
 
62
  if not user_input.lower().startswith("as a cybersecurity expert"):
63
  user_input = f"(As a cybersecurity expert) {user_input}"
 
 
 
64
 
65
- # Append user message
66
- conversation_history.append({'role': 'user', 'content': user_input})
67
-
68
- # Build system prompt including updated context summary
69
- system_prompt = SYSTEM_PROMPT_BASE
 
70
  if context_summary:
71
- system_prompt += "\n\nPrevious context summary:\n" + context_summary
72
-
73
- # Assemble messages for streaming
74
- messages = ([{'role': 'system', 'content': system_prompt}] +
75
- conversation_history)
76
- # Add placeholder for assistant
77
- conversation_history.append({'role': 'assistant', 'content': ''})
78
-
79
- # Stream tokens from the model
80
  stream = together_client.chat.completions.create(
81
  model=MODEL_NAME,
82
- messages=messages,
83
  stream=True
84
  )
85
-
86
- # Incrementally build assistant reply
87
  for token in stream:
88
  if hasattr(token, 'choices'):
89
  delta = token.choices[0].delta.content
90
- conversation_history[-1]['content'] += delta
91
- yield [(msg['role'], msg['content']) for msg in conversation_history if msg['role'] != 'system']
92
-
93
- # After full reply, update the context summary
94
- context_summary = update_summary(conversation_history)
95
 
96
  # ----------------------------------------------------------------------------
97
- # Gradio Interface Definition
98
  # ----------------------------------------------------------------------------
99
  def launch_interface():
100
  with gr.Blocks() as demo:
101
  gr.Markdown("## CyberGuard – Autonomous Cybersecurity Chat")
102
  chatbot = gr.Chatbot()
103
- state = gr.State([]) # placeholder to trigger streaming
104
-
105
  txt = gr.Textbox(show_label=False, placeholder="Enter your security query...")
106
 
107
- # On submit: trigger streaming
108
- def on_submit(user_msg, _state):
109
- return [[('user', user_msg)]], None # just triggers state change
110
-
111
- txt.submit(lambda *_: None, None, txt)
112
- txt.submit(on_submit, [txt, state], [state, chatbot], queue=False)
113
- state.change(fn=lambda s: append_and_stream(txt.value), inputs=state, outputs=chatbot)
114
 
115
  demo.launch(share=True, server_name='0.0.0.0', server_port=7860)
116
 
 
14
  # ----------------------------------------------------------------------------
15
  # Together Client Initialization with API Key
16
  # ----------------------------------------------------------------------------
 
17
  api_key = os.environ.get("TOGETHER_API_KEY")
18
  if not api_key:
19
  raise ValueError("Missing TOGETHER_API_KEY environment variable")
 
22
  # ----------------------------------------------------------------------------
23
  # In-Memory Context Tracking
24
  # ----------------------------------------------------------------------------
25
+ conversation_history = [] # List of (user_msg, assistant_msg)
26
+ context_summary = "" # Running summary of conversation
27
 
28
  # ----------------------------------------------------------------------------
29
  # Helper: Update Context Summary
30
  # ----------------------------------------------------------------------------
31
  def update_summary(history):
 
 
 
 
32
  messages = [
33
  {"role": "system", "content": SYSTEM_PROMPT_BASE},
34
  {"role": "user", "content": (
35
  "Summarize the following cybersecurity conversation in 3-5 bullet points, "
36
  "focusing on key decisions and context:\n" +
37
+ "\n".join([f"user: {u}\nassistant: {a}" for u, a in history])
38
  )}
39
  ]
40
+ resp = together_client.chat.completions.create(
 
41
  model=MODEL_NAME,
42
  messages=messages,
43
  stream=False
44
  )
45
+ return resp.choices[0].message.content.strip()
 
 
46
 
47
  # ----------------------------------------------------------------------------
48
+ # Core Chat Functions for Gradio
49
  # ----------------------------------------------------------------------------
50
+ def user_submit(user_input, history):
51
+ history = history or []
52
+ if not user_input:
53
+ return "", history
54
+ # Frame as cybersecurity expert
55
  if not user_input.lower().startswith("as a cybersecurity expert"):
56
  user_input = f"(As a cybersecurity expert) {user_input}"
57
+ # Append placeholder for assistant
58
+ history.append((user_input, ""))
59
+ return "", history
60
 
61
+ def assistant_stream(history):
62
+ global context_summary
63
+ if not history:
64
+ return history
65
+ # Build messages for model
66
+ model_msgs = [{"role": "system", "content": SYSTEM_PROMPT_BASE}]
67
  if context_summary:
68
+ model_msgs[0]["content"] += f"\n\nPrevious summary:\n{context_summary}"
69
+ for user_msg, assistant_msg in history[:-1]:
70
+ model_msgs.append({"role": "user", "content": user_msg})
71
+ model_msgs.append({"role": "assistant", "content": assistant_msg})
72
+ # Current user turn
73
+ user_msg, _ = history[-1]
74
+ model_msgs.append({"role": "user", "content": user_msg})
75
+ # Stream from together
 
76
  stream = together_client.chat.completions.create(
77
  model=MODEL_NAME,
78
+ messages=model_msgs,
79
  stream=True
80
  )
 
 
81
  for token in stream:
82
  if hasattr(token, 'choices'):
83
  delta = token.choices[0].delta.content
84
+ history[-1] = (history[-1][0], history[-1][1] + delta)
85
+ yield history
86
+ # After full response, update summary
87
+ context_summary = update_summary(history)
 
88
 
89
  # ----------------------------------------------------------------------------
90
+ # Launch Gradio Interface
91
  # ----------------------------------------------------------------------------
92
  def launch_interface():
93
  with gr.Blocks() as demo:
94
  gr.Markdown("## CyberGuard – Autonomous Cybersecurity Chat")
95
  chatbot = gr.Chatbot()
 
 
96
  txt = gr.Textbox(show_label=False, placeholder="Enter your security query...")
97
 
98
+ txt.submit(user_submit, [txt, chatbot], [txt, chatbot], queue=False)
99
+ txt.submit(lambda: None, None, txt) # clear input
100
+ chatbot.stream(assistant_stream, chatbot)
 
 
 
 
101
 
102
  demo.launch(share=True, server_name='0.0.0.0', server_port=7860)
103