ChrisSacrumCor commited on
Commit
5b36338
·
verified ·
1 Parent(s): 0f2b6ee

Create assistant/ai_assistant.py

Browse files
Files changed (1) hide show
  1. assistant/ai_assistant.py +150 -0
assistant/ai_assistant.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ AI Assistant for Gradio MCP system.
3
+ Handles intelligent responses for both sensitive operations and safe commands.
4
+ """
5
+
6
+ import openai
7
+ import json
8
+ from typing import Dict, Any, List
9
+ from shared.config import config
10
+ import logging
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ class GradioAIAssistant:
15
+ """AI Assistant optimized for Gradio MCP integration"""
16
+
17
+ def __init__(self):
18
+ self.client = openai.OpenAI(api_key=config.openai.api_key)
19
+
20
+ def process_tool_result(self, user_message: str, tool_result: Dict[str, Any]) -> str:
21
+ """
22
+ Process tool execution result and generate intelligent response.
23
+ This is called by Gradio after tool execution.
24
+ """
25
+ tool_type = tool_result.get("tool_type", "unknown")
26
+
27
+ if tool_type == "sensitive_operation":
28
+ return self._handle_sensitive_result(user_message, tool_result)
29
+ elif tool_type == "safe_command":
30
+ return self._handle_safe_result(user_message, tool_result)
31
+ else:
32
+ return self._handle_unknown_result(user_message, tool_result)
33
+
34
+ def _handle_sensitive_result(self, user_message: str, result: Dict[str, Any]) -> str:
35
+ """Handle results from sensitive operations with educational approach"""
36
+
37
+ prompt = f"""You are an expert Linux system administrator and teacher.
38
+
39
+ A user requested: "{user_message}"
40
+
41
+ This triggered a SENSITIVE system operation with the following result:
42
+ {json.dumps(result, indent=2)}
43
+
44
+ Respond with a Socratic, educational approach:
45
+
46
+ If SUCCESSFUL:
47
+ - Explain what was accomplished and why it matters
48
+ - Discuss the security implications
49
+ - Suggest best practices or next steps
50
+ - Ask if they understand the implications
51
+
52
+ If FAILED:
53
+ - Help them understand why it failed
54
+ - Guide them through what needs to be corrected
55
+ - Ask clarifying questions to gather missing information
56
+ - Provide learning opportunities
57
+
58
+ If MISSING INFORMATION:
59
+ - Ask specific questions to gather needed details
60
+ - Explain why each parameter is important
61
+ - Provide examples of good values
62
+ - Guide them step by step
63
+
64
+ Be conversational, helpful, and educational. This is a teaching moment."""
65
+
66
+ return self._call_openai(prompt)
67
+
68
+ def _handle_safe_result(self, user_message: str, result: Dict[str, Any]) -> str:
69
+ """Handle results from safe operations with clear explanations"""
70
+
71
+ prompt = f"""You are a helpful Linux system administrator.
72
+
73
+ A user requested: "{user_message}"
74
+
75
+ This executed a SAFE system command with the following result:
76
+ {json.dumps(result, indent=2)}
77
+
78
+ Provide a clear, informative response:
79
+
80
+ If SUCCESSFUL:
81
+ - Explain the output in an easy-to-understand way
82
+ - Highlight important information
83
+ - Suggest related commands that might be useful
84
+ - Keep it concise but helpful
85
+
86
+ If FAILED:
87
+ - Explain what went wrong
88
+ - Suggest how to fix it
89
+ - Provide alternative approaches
90
+
91
+ Format the response to be helpful and professional. Focus on making the technical information accessible."""
92
+
93
+ return self._call_openai(prompt)
94
+
95
+ def _handle_unknown_result(self, user_message: str, result: Dict[str, Any]) -> str:
96
+ """Handle unknown or error results"""
97
+
98
+ return f"""I encountered an issue processing your request: "{user_message}"
99
+
100
+ Result: {json.dumps(result, indent=2)}
101
+
102
+ This might be due to:
103
+ - An unrecognized command or operation
104
+ - A system error
105
+ - Missing configuration
106
+
107
+ Could you please rephrase your request or try a different approach? I'm here to help with Linux system administration tasks."""
108
+
109
+ def generate_help_response(self) -> str:
110
+ """Generate a helpful introduction to the system"""
111
+
112
+ prompt = """You are a Linux system administration assistant with AI capabilities.
113
+
114
+ Generate a helpful introduction that explains:
115
+ - What kinds of tasks you can help with
116
+ - Examples of safe operations (file listing, system info, etc.)
117
+ - Examples of sensitive operations that require careful consideration
118
+ - How you use a Socratic approach for sensitive tasks
119
+ - Encourage users to ask questions and learn
120
+
121
+ Keep it friendly, professional, and encouraging. Make users feel confident about learning Linux administration."""
122
+
123
+ return self._call_openai(prompt)
124
+
125
+ def _call_openai(self, prompt: str) -> str:
126
+ """Make OpenAI API call with error handling"""
127
+ try:
128
+ response = self.client.chat.completions.create(
129
+ model=config.openai.model,
130
+ messages=[
131
+ {
132
+ "role": "system",
133
+ "content": "You are an expert Linux system administrator and educator. Provide helpful, accurate, and educational responses."
134
+ },
135
+ {
136
+ "role": "user",
137
+ "content": prompt
138
+ }
139
+ ],
140
+ temperature=config.openai.temperature,
141
+ max_tokens=config.openai.max_tokens
142
+ )
143
+ return response.choices[0].message.content
144
+
145
+ except Exception as e:
146
+ logger.error(f"OpenAI API error: {e}")
147
+ return f"I apologize, but I encountered an error generating a response. The operation completed with the following result: {json.dumps(result if 'result' in locals() else {}, indent=2)}"
148
+
149
+ # Global assistant instance
150
+ assistant = GradioAIAssistant()