Jayashree Sridhar commited on
Commit
f130374
·
1 Parent(s): 21bebf5

modified llm & knowledge tools

Browse files
agents/tools/knowledge_tools.py CHANGED
@@ -1,216 +1,34 @@
1
- """
2
- Knowledge Base Tools for RAG (modular class version)
3
- """
4
- # from utils.knowledge_base import KnowledgeBase
5
-
6
- # class KnowledgeTools:
7
- # def __init__(self, config=None):
8
- # self.config = config
9
- # self.kb = KnowledgeBase(self.config)
10
-
11
- # def search_knowledge(self, query: str, k: int = 5):
12
- # """Search spiritual and self-help texts for relevant wisdom."""
13
- # if not self.kb.is_initialized():
14
- # return [{
15
- # "text": "Wisdom comes from understanding ourselves.",
16
- # "source": "General Wisdom",
17
- # "score": 1.0
18
- # }]
19
- # return self.kb.search(query, k=k)
20
-
21
- # def extract_wisdom(self, search_results: list, user_context: dict):
22
- # """Extract most relevant wisdom for user's situation."""
23
- # emotion = user_context.get("primary_emotion", "neutral")
24
- # concerns = user_context.get("concerns", [])
25
- # scored_results = []
26
- # for result in search_results:
27
- # score = result["score"]
28
- # # Boost score if emotion matches
29
- # if emotion.lower() in result["text"].lower():
30
- # score *= 1.5
31
- # # Boost score if concerns match
32
- # for concern in concerns:
33
- # if concern.lower() in result["text"].lower():
34
- # score *= 1.3
35
- # result["relevance_score"] = score
36
- # scored_results.append(result)
37
- # scored_results.sort(key=lambda x: x["relevance_score"], reverse=True)
38
- # return scored_results[:3]
39
-
40
- # def suggest_practices(self, emotional_state: str, cultural_context: str = None):
41
- # """Suggest appropriate meditation or practice."""
42
- # practices = {
43
- # "anxiety": {
44
- # "name": "Box Breathing Technique",
45
- # "description": "A powerful technique used by Navy SEALs to calm anxiety",
46
- # "steps": [
47
- # "Sit comfortably with back straight",
48
- # "Exhale all air from your lungs",
49
- # "Inhale through nose for 4 counts",
50
- # "Hold breath for 4 counts",
51
- # "Exhale through mouth for 4 counts",
52
- # "Hold empty for 4 counts",
53
- # "Repeat 4-8 times"
54
- # ],
55
- # "benefits": "Activates parasympathetic nervous system, reduces cortisol",
56
- # "duration": "5-10 minutes",
57
- # "origin": "Modern breathwork"
58
- # },
59
- # "sadness": {
60
- # "name": "Metta (Loving-Kindness) Meditation",
61
- # "description": "Ancient Buddhist practice to cultivate compassion",
62
- # "steps": [
63
- # "Sit comfortably, close your eyes",
64
- # "Place hand on heart",
65
- # "Begin with self: 'May I be happy, may I be peaceful'",
66
- # "Extend to loved ones",
67
- # "Include neutral people",
68
- # "Embrace difficult people",
69
- # "Radiate to all beings"
70
- # ],
71
- # "benefits": "Increases self-compassion, reduces depression",
72
- # "duration": "15-20 minutes",
73
- # "origin": "Buddhist tradition"
74
- # },
75
- # "stress": {
76
- # "name": "Progressive Muscle Relaxation",
77
- # "description": "Systematic tension and release technique",
78
- # "steps": [
79
- # "Lie down comfortably",
80
- # "Start with toes - tense for 5 seconds",
81
- # "Release suddenly, notice relaxation",
82
- # "Move up through each muscle group",
83
- # "Face and scalp last",
84
- # "Rest in full body relaxation"
85
- # ],
86
- # "benefits": "Reduces physical tension, improves sleep",
87
- # "duration": "15-20 minutes",
88
- # "origin": "Dr. Edmund Jacobson, 1920s"
89
- # }
90
- # }
91
- # default = {
92
- # "name": "Mindful Breathing",
93
- # "description": "Foundation of all meditation practices",
94
- # "steps": [
95
- # "Sit comfortably",
96
- # "Follow natural breath",
97
- # "Count breaths 1-10",
98
- # "Start again when distracted",
99
- # "No judgment, just awareness"
100
- # ],
101
- # "benefits": "Calms mind, improves focus",
102
- # "duration": "5-15 minutes",
103
- # "origin": "Universal practice"
104
- # }
105
- # return practices.get(emotional_state.lower(), default)
106
-
107
  from .base_tool import BaseTool
108
  from utils.knowledge_base import KnowledgeBase
109
 
110
  class SearchKnowledgeTool(BaseTool):
 
 
111
  def __init__(self, config=None):
112
- super().__init__(config)
113
  self.kb = KnowledgeBase(config)
114
  def __call__(self, query: str, k: int = 5):
115
- if not self.kb.is_initialized():
116
- return [
117
- {"text": "Wisdom comes from understanding ourselves.", "source": "General Wisdom", "score": 1.0}
118
- ]
119
- return self.kb.search(query, k=k)
120
 
121
  class ExtractWisdomTool(BaseTool):
 
 
122
  def __init__(self, config=None):
123
- super().__init__(config)
124
  def __call__(self, search_results: list, user_context: dict):
125
- # ...Use your logic from extract_wisdom...
126
- emotion = user_context.get("primary_emotion", "neutral")
127
- concerns = user_context.get("concerns", [])
128
- scored_results = []
129
- for result in search_results:
130
- score = result["score"]
131
- if emotion.lower() in result["text"].lower():
132
- score *= 1.5
133
- for concern in concerns:
134
- if concern.lower() in result["text"].lower():
135
- score *= 1.3
136
- result["relevance_score"] = score
137
- scored_results.append(result)
138
- scored_results.sort(key=lambda x: x["relevance_score"], reverse=True)
139
- return scored_results[:3]
140
 
141
  class SuggestPracticesTool(BaseTool):
 
 
142
  def __init__(self, config=None):
143
- super().__init__(config)
144
  def __call__(self, emotional_state: str, cultural_context: str = None):
145
- # ... your original logic ...
146
- practices = {
147
- "anxiety": {
148
- "name": "Box Breathing Technique",
149
- "description": "A powerful technique used by Navy SEALs to calm anxiety",
150
- "steps": [
151
- "Sit comfortably with back straight",
152
- "Exhale all air from your lungs",
153
- "Inhale through nose for 4 counts",
154
- "Hold breath for 4 counts",
155
- "Exhale through mouth for 4 counts",
156
- "Hold empty for 4 counts",
157
- "Repeat 4-8 times"
158
- ],
159
- "benefits": "Activates parasympathetic nervous system, reduces cortisol",
160
- "duration": "5-10 minutes",
161
- "origin": "Modern breathwork"
162
- },
163
- "sadness": {
164
- "name": "Metta (Loving-Kindness) Meditation",
165
- "description": "Ancient Buddhist practice to cultivate compassion",
166
- "steps": [
167
- "Sit comfortably, close your eyes",
168
- "Place hand on heart",
169
- "Begin with self: 'May I be happy, may I be peaceful'",
170
- "Extend to loved ones",
171
- "Include neutral people",
172
- "Embrace difficult people",
173
- "Radiate to all beings"
174
- ],
175
- "benefits": "Increases self-compassion, reduces depression",
176
- "duration": "15-20 minutes",
177
- "origin": "Buddhist tradition"
178
- },
179
- "stress": {
180
- "name": "Progressive Muscle Relaxation",
181
- "description": "Systematic tension and release technique",
182
- "steps": [
183
- "Lie down comfortably",
184
- "Start with toes - tense for 5 seconds",
185
- "Release suddenly, notice relaxation",
186
- "Move up through each muscle group",
187
- "Face and scalp last",
188
- "Rest in full body relaxation"
189
- ],
190
- "benefits": "Reduces physical tension, improves sleep",
191
- "duration": "15-20 minutes",
192
- "origin": "Dr. Edmund Jacobson, 1920s"
193
- }
194
- # Fill out as in your original
195
- }
196
- # default omitted for brevity
197
- return practices.get(emotional_state.lower(), {
198
- "name": "Mindful Breathing",
199
- "description": "Foundation of all meditation practices",
200
- "steps": [
201
- "Sit comfortably",
202
- "Follow natural breath",
203
- "Count breaths 1-10",
204
- "Start again when distracted",
205
- "No judgment, just awareness"
206
- ],
207
- "benefits": "Calms mind, improves focus",
208
- "duration": "5-15 minutes",
209
- "origin": "Universal practice"
210
- })
211
 
212
  class KnowledgeTools:
213
  def __init__(self, config=None):
214
  self.search_knowledge = SearchKnowledgeTool(config)
215
  self.extract_wisdom = ExtractWisdomTool(config)
216
- self.suggest_practices = SuggestPracticesTool(config)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from .base_tool import BaseTool
2
  from utils.knowledge_base import KnowledgeBase
3
 
4
  class SearchKnowledgeTool(BaseTool):
5
+ name: str = "search_knowledge"
6
+ description: str = "Search self-help or spiritual wisdom."
7
  def __init__(self, config=None):
8
+ super().__init__()
9
  self.kb = KnowledgeBase(config)
10
  def __call__(self, query: str, k: int = 5):
11
+ return self.kb.search(query, k=k) if self.kb.is_initialized() else \
12
+ [{"text": "General wisdom", "score": 1.0}]
 
 
 
13
 
14
  class ExtractWisdomTool(BaseTool):
15
+ name: str = "extract_wisdom"
16
+ description: str = "Extract most relevant wisdom for a given query."
17
  def __init__(self, config=None):
18
+ super().__init__()
19
  def __call__(self, search_results: list, user_context: dict):
20
+ return search_results[:3]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  class SuggestPracticesTool(BaseTool):
23
+ name: str = "suggest_practices"
24
+ description: str = "Recommend meditations or self-care practices."
25
  def __init__(self, config=None):
26
+ super().__init__()
27
  def __call__(self, emotional_state: str, cultural_context: str = None):
28
+ return {"name": "Mindful Breathing", "description": "Focus on your breath to calm the mind."}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
  class KnowledgeTools:
31
  def __init__(self, config=None):
32
  self.search_knowledge = SearchKnowledgeTool(config)
33
  self.extract_wisdom = ExtractWisdomTool(config)
34
+ self.suggest_practices = SuggestPracticesTool(config)
agents/tools/llm_tools.py CHANGED
@@ -1,115 +1,38 @@
1
- # """
2
- # Mistral LLM Tools for CrewAI (modular class version)
3
- # """
4
- # #from models.mistral_model import MistralModel
5
- # from models.tinygpt2_model import TinyGPT2Model
6
-
7
- # class LLMTools:
8
- # def __init__(self, config=None):
9
- # self.config = config
10
- # self.model =TinyGPT2Model()
11
-
12
- # def mistral_chat(self, prompt: str, context: dict = None) -> str:
13
- # """Chat with Mistral AI for intelligent responses."""
14
- # if context:
15
- # full_prompt = f"""
16
- # Context: {context}
17
- # User Query: {prompt}
18
- # Provide a thoughtful, compassionate response.
19
- # """
20
- # else:
21
- # full_prompt = prompt
22
- # return self.model.generate(full_prompt)
23
-
24
- # def generate_advice(self, user_analysis: dict, wisdom_quotes: list) -> str:
25
- # """Generate personalized advice based on user's situation."""
26
- # prompt = f"""
27
- # Based on this user analysis:
28
- # - Emotional state: {user_analysis.get('primary_emotion')}
29
- # - Concerns: {user_analysis.get('concerns')}
30
- # - Needs: {user_analysis.get('needs')}
31
- # And these relevant wisdom quotes:
32
- # {wisdom_quotes}
33
- # Generate compassionate, personalized advice that:
34
- # 1. Acknowledges their feelings
35
- # 2. Offers practical guidance
36
- # 3. Includes relevant wisdom
37
- # 4. Suggests actionable steps
38
- # 5. Maintains hope and encouragement
39
- # Be specific to their situation, not generic.
40
- # """
41
- # return self.model.generate(prompt, max_length=500)
42
-
43
- # def summarize_conversation(self, conversation: list) -> str:
44
- # """Summarize conversation maintaining key insights."""
45
- # prompt = f"""
46
- # Summarize this coaching conversation:
47
- # {conversation}
48
- # Include:
49
- # 1. Main concerns discussed
50
- # 2. Key insights shared
51
- # 3. Progress made
52
- # 4. Next steps suggested
53
- # Keep it concise but meaningful.
54
- # """
55
- # return self.model.generate(prompt, max_length=200)
56
-
57
  from .base_tool import BaseTool
58
  from models.tinygpt2_model import TinyGPT2Model
59
 
60
  class MistralChatTool(BaseTool):
 
 
61
  def __init__(self, config=None):
62
- super().__init__(config)
63
  self.model = TinyGPT2Model()
64
  def __call__(self, prompt: str, context: dict = None):
65
- if context:
66
- full_prompt = f"Context: {context}\nUser Query: {prompt}\nProvide a thoughtful, compassionate response."
67
- else:
68
- full_prompt = prompt
69
- return self.model.generate(full_prompt)
70
 
71
  class GenerateAdviceTool(BaseTool):
 
 
72
  def __init__(self, config=None):
73
- super().__init__(config)
74
  self.model = TinyGPT2Model()
75
  def __call__(self, user_analysis: dict, wisdom_quotes: list):
76
- prompt = f"""
77
- Based on this user analysis:
78
- - Emotional state: {user_analysis.get('primary_emotion')}
79
- - Concerns: {user_analysis.get('concerns')}
80
- - Needs: {user_analysis.get('needs')}
81
- And these relevant wisdom quotes:
82
- {wisdom_quotes}
83
- Generate compassionate, personalized advice that:
84
- 1. Acknowledges their feelings
85
- 2. Offers practical guidance
86
- 3. Includes relevant wisdom
87
- 4. Suggests actionable steps
88
- 5. Maintains hope and encouragement
89
- Be specific to their situation, not generic.
90
- """
91
- return self.model.generate(prompt, max_length=500)
92
 
93
  class SummarizeConversationTool(BaseTool):
 
 
94
  def __init__(self, config=None):
95
- super().__init__(config)
96
  self.model = TinyGPT2Model()
97
  def __call__(self, conversation: list):
98
- prompt = f"""
99
- Summarize this coaching conversation:
100
- {conversation}
101
- Include:
102
- 1. Main concerns discussed
103
- 2. Key insights shared
104
- 3. Progress made
105
- 4. Next steps suggested
106
- Keep it concise but meaningful.
107
- """
108
  return self.model.generate(prompt, max_length=200)
109
 
110
  class LLMTools:
111
  def __init__(self, config=None):
112
  self.mistral_chat = MistralChatTool(config)
113
  self.generate_advice = GenerateAdviceTool(config)
114
- self.summarize_conversation = SummarizeConversationTool(config)
115
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from .base_tool import BaseTool
2
  from models.tinygpt2_model import TinyGPT2Model
3
 
4
  class MistralChatTool(BaseTool):
5
+ name: str = "mistral_chat"
6
+ description: str = "Generate an empathetic AI chat response."
7
  def __init__(self, config=None):
8
+ super().__init__()
9
  self.model = TinyGPT2Model()
10
  def __call__(self, prompt: str, context: dict = None):
11
+ msg = f"Context: {context}\nUser: {prompt}" if context else prompt
12
+ return self.model.generate(msg)
 
 
 
13
 
14
  class GenerateAdviceTool(BaseTool):
15
+ name: str = "generate_advice"
16
+ description: str = "Generate personalized advice."
17
  def __init__(self, config=None):
18
+ super().__init__()
19
  self.model = TinyGPT2Model()
20
  def __call__(self, user_analysis: dict, wisdom_quotes: list):
21
+ prompt = f"Advice for: {user_analysis}, with wisdom: {wisdom_quotes}"
22
+ return self.model.generate(prompt, max_length=300)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  class SummarizeConversationTool(BaseTool):
25
+ name: str = "summarize_conversation"
26
+ description: str = "Summarize chat with insights and next steps."
27
  def __init__(self, config=None):
28
+ super().__init__()
29
  self.model = TinyGPT2Model()
30
  def __call__(self, conversation: list):
31
+ prompt = f"Summarize: {conversation}"
 
 
 
 
 
 
 
 
 
32
  return self.model.generate(prompt, max_length=200)
33
 
34
  class LLMTools:
35
  def __init__(self, config=None):
36
  self.mistral_chat = MistralChatTool(config)
37
  self.generate_advice = GenerateAdviceTool(config)
38
+ self.summarize_conversation = SummarizeConversationTool(config)