omkareswarhota1234 commited on
Commit
8dc8e89
·
verified ·
1 Parent(s): fd9aa7a

Upload 45 files

Browse files
Files changed (45) hide show
  1. .dockerignore +7 -0
  2. .gitignore +13 -0
  3. .idea/.gitignore +8 -0
  4. .idea/inspectionProfiles/profiles_settings.xml +6 -0
  5. .idea/math_agent.iml +11 -0
  6. .idea/misc.xml +7 -0
  7. .idea/modules.xml +8 -0
  8. .idea/vcs.xml +6 -0
  9. .idea/workspace.xml +175 -0
  10. __init__.py +0 -0
  11. __pycache__/main.cpython-313.pyc +0 -0
  12. agents/__init__.py +0 -0
  13. agents/__pycache__/__init__.cpython-313.pyc +0 -0
  14. agents/__pycache__/feedback_agent.cpython-313.pyc +0 -0
  15. agents/__pycache__/math_solver.cpython-313.pyc +0 -0
  16. agents/__pycache__/routing_agent.cpython-313.pyc +0 -0
  17. agents/__pycache__/vector_db.cpython-313.pyc +0 -0
  18. agents/__pycache__/web_agent.cpython-313.pyc +0 -0
  19. agents/feedback_agent.py +108 -0
  20. agents/math_solver.py +74 -0
  21. agents/routing_agent.py +38 -0
  22. agents/vector_db.py +43 -0
  23. agents/web_agent.py +3 -0
  24. create_init_files.py +0 -0
  25. data/__init__.py +1 -0
  26. data/data.txt +92 -0
  27. data/embeddings/index.faiss +0 -0
  28. data/embeddings/index.pkl +3 -0
  29. data/feedback_log.json +151 -0
  30. docker-compose.yml +27 -0
  31. main.py +36 -0
  32. requirements.txt +15 -0
  33. router/__init__.py +1 -0
  34. router/__pycache__/__init__.cpython-313.pyc +0 -0
  35. router/__pycache__/feedback_router.cpython-313.pyc +0 -0
  36. router/__pycache__/rag_router.cpython-313.pyc +0 -0
  37. router/feedback_router.py +25 -0
  38. router/rag_router.py +42 -0
  39. utils/__init__.py +0 -0
  40. utils/__pycache__/__init__.cpython-313.pyc +0 -0
  41. utils/__pycache__/mcp_client.cpython-313.pyc +0 -0
  42. utils/guardrails.py +39 -0
  43. utils/jee_bench_eval.py +51 -0
  44. utils/mcp_client.py +33 -0
  45. utils/vectorstore_setup.py +45 -0
.dockerignore ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ *.pyo
4
+ *.pyd
5
+ .env
6
+ node_modules/
7
+ .git
.gitignore ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ignore Python cache and environments
2
+ __pycache__/
3
+ *.pyc
4
+ .env
5
+
6
+ # Ignore node_modules and build files
7
+ Frontend/react-app/node_modules/
8
+ Frontend/react-app/build/
9
+
10
+ # Ignore IDE and system files
11
+ .idea/
12
+ .vscode/
13
+ *.log
.idea/.gitignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Default ignored files
2
+ /shelf/
3
+ /workspace.xml
4
+ # Editor-based HTTP Client requests
5
+ /httpRequests/
6
+ # Datasource local storage ignored files
7
+ /dataSources/
8
+ /dataSources.local.xml
.idea/inspectionProfiles/profiles_settings.xml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <component name="InspectionProjectProfileManager">
2
+ <settings>
3
+ <option name="USE_PROJECT_PROFILE" value="false" />
4
+ <version value="1.0" />
5
+ </settings>
6
+ </component>
.idea/math_agent.iml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="PYTHON_MODULE" version="4">
3
+ <component name="NewModuleRootManager">
4
+ <content url="file://$MODULE_DIR$" />
5
+ <orderEntry type="jdk" jdkName="Python 3.13" jdkType="Python SDK" />
6
+ <orderEntry type="sourceFolder" forTests="false" />
7
+ </component>
8
+ <component name="PackageRequirementsSettings">
9
+ <option name="modifyBaseFiles" value="true" />
10
+ </component>
11
+ </module>
.idea/misc.xml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="Black">
4
+ <option name="sdkName" value="Python 3.13" />
5
+ </component>
6
+ <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.13" project-jdk-type="Python SDK" />
7
+ </project>
.idea/modules.xml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/math_agent.iml" filepath="$PROJECT_DIR$/.idea/math_agent.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
.idea/vcs.xml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsProjectSettings">
4
+ <option name="detectVcsMappingsAutomatically" value="false" />
5
+ </component>
6
+ </project>
.idea/workspace.xml ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="AutoImportSettings">
4
+ <option name="autoReloadType" value="SELECTIVE" />
5
+ </component>
6
+ <component name="ChangeListManager">
7
+ <list default="true" id="b3b62ef4-611e-4fb0-8f96-57c95baf16c0" name="Changes" comment="" />
8
+ <option name="SHOW_DIALOG" value="false" />
9
+ <option name="HIGHLIGHT_CONFLICTS" value="true" />
10
+ <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
11
+ <option name="LAST_RESOLUTION" value="IGNORE" />
12
+ </component>
13
+ <component name="FileTemplateManagerImpl">
14
+ <option name="RECENT_TEMPLATES">
15
+ <list>
16
+ <option value="Jupyter Notebook" />
17
+ <option value="JavaScript File" />
18
+ <option value="CSS File" />
19
+ <option value="Dockerfile" />
20
+ <option value="Python Script" />
21
+ </list>
22
+ </option>
23
+ </component>
24
+ <component name="Git.Settings">
25
+ <option name="PATH_TO_GIT" value="C:\Program Files\Git\bin\git.exe" />
26
+ <option name="PREVIEW_PUSH_PROTECTED_ONLY" value="true" />
27
+ <option name="PUSH_AUTO_UPDATE" value="true" />
28
+ <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
29
+ <option name="WARN_ABOUT_LARGE_FILES_LIMIT_MB" value="500" />
30
+ </component>
31
+ <component name="ProblemsViewState">
32
+ <option name="selectedTabId" value="CurrentFile" />
33
+ </component>
34
+ <component name="ProjectColorInfo">{
35
+ &quot;associatedIndex&quot;: 8
36
+ }</component>
37
+ <component name="ProjectId" id="34drYO4cz3qqpEqrhpo8YtDFV1j" />
38
+ <component name="ProjectViewState">
39
+ <option name="hideEmptyMiddlePackages" value="true" />
40
+ <option name="showLibraryContents" value="true" />
41
+ </component>
42
+ <component name="PropertiesComponent">{
43
+ &quot;keyToString&quot;: {
44
+ &quot;ModuleVcsDetector.initialDetectionPerformed&quot;: &quot;true&quot;,
45
+ &quot;Python.main.executor&quot;: &quot;Run&quot;,
46
+ &quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
47
+ &quot;RunOnceActivity.TerminalTabsStorage.copyFrom.TerminalArrangementManager.252&quot;: &quot;true&quot;,
48
+ &quot;RunOnceActivity.git.unshallow&quot;: &quot;true&quot;,
49
+ &quot;git-widget-placeholder&quot;: &quot;main&quot;,
50
+ &quot;js.introduce.parameter.generate.optional&quot;: &quot;false&quot;,
51
+ &quot;last_opened_file_path&quot;: &quot;D:/math_agent&quot;,
52
+ &quot;list.type.of.created.stylesheet&quot;: &quot;CSS&quot;,
53
+ &quot;node.js.detected.package.eslint&quot;: &quot;true&quot;,
54
+ &quot;node.js.detected.package.tslint&quot;: &quot;true&quot;,
55
+ &quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;,
56
+ &quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;,
57
+ &quot;nodejs_interpreter_path&quot;: &quot;C:/Program Files/nodejs/node&quot;,
58
+ &quot;nodejs_package_manager_path&quot;: &quot;C:\\Program Files\\nodejs\\npm.cmd&quot;,
59
+ &quot;settings.editor.selected.configurable&quot;: &quot;project.propVCSSupport.DirectoryMappings&quot;,
60
+ &quot;vue.rearranger.settings.migration&quot;: &quot;true&quot;
61
+ },
62
+ &quot;keyToStringList&quot;: {
63
+ &quot;ChangesTree.GroupingKeys&quot;: [
64
+ &quot;repository&quot;
65
+ ]
66
+ }
67
+ }</component>
68
+ <component name="RecentsManager">
69
+ <key name="MoveFile.RECENT_KEYS">
70
+ <recent name="D:\math_agent" />
71
+ <recent name="D:\math_agent\Frontend\react-app" />
72
+ <recent name="D:\math_agent\Backend" />
73
+ <recent name="D:\math_agent\Frontend\react-app\src" />
74
+ <recent name="D:\math_agent\Backend\agents" />
75
+ </key>
76
+ </component>
77
+ <component name="RunManager">
78
+ <configuration name="main" type="PythonConfigurationType" factoryName="Python" nameIsGenerated="true">
79
+ <module name="math_agent" />
80
+ <option name="ENV_FILES" value="" />
81
+ <option name="INTERPRETER_OPTIONS" value="" />
82
+ <option name="PARENT_ENVS" value="true" />
83
+ <envs>
84
+ <env name="PYTHONUNBUFFERED" value="1" />
85
+ </envs>
86
+ <option name="SDK_HOME" value="" />
87
+ <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
88
+ <option name="IS_MODULE_SDK" value="true" />
89
+ <option name="ADD_CONTENT_ROOTS" value="true" />
90
+ <option name="ADD_SOURCE_ROOTS" value="true" />
91
+ <EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
92
+ <option name="SCRIPT_NAME" value="D:\math_agent\main.py" />
93
+ <option name="PARAMETERS" value="" />
94
+ <option name="SHOW_COMMAND_LINE" value="false" />
95
+ <option name="EMULATE_TERMINAL" value="false" />
96
+ <option name="MODULE_MODE" value="false" />
97
+ <option name="REDIRECT_INPUT" value="false" />
98
+ <option name="INPUT_FILE" value="" />
99
+ <method v="2" />
100
+ </configuration>
101
+ <configuration default="true" type="docker-deploy" factoryName="dockerfile" temporary="true">
102
+ <deployment type="dockerfile">
103
+ <settings />
104
+ </deployment>
105
+ <method v="2" />
106
+ </configuration>
107
+ </component>
108
+ <component name="SharedIndexes">
109
+ <attachedChunks>
110
+ <set>
111
+ <option value="bundled-js-predefined-d6986cc7102b-3aa1da707db6-JavaScript-PY-252.27397.106" />
112
+ <option value="bundled-python-sdk-4e2b1448bda8-9a97661f3031-com.jetbrains.pycharm.pro.sharedIndexes.bundled-PY-252.27397.106" />
113
+ </set>
114
+ </attachedChunks>
115
+ </component>
116
+ <component name="TaskManager">
117
+ <task active="true" id="Default" summary="Default task">
118
+ <changelist id="b3b62ef4-611e-4fb0-8f96-57c95baf16c0" name="Changes" comment="" />
119
+ <created>1761554339936</created>
120
+ <option name="number" value="Default" />
121
+ <option name="presentableId" value="Default" />
122
+ <updated>1761554339936</updated>
123
+ <workItem from="1761554341477" duration="7999000" />
124
+ <workItem from="1761568509314" duration="5386000" />
125
+ <workItem from="1761574431043" duration="1735000" />
126
+ <workItem from="1761580171311" duration="28000" />
127
+ <workItem from="1761583632400" duration="120000" />
128
+ <workItem from="1761585323349" duration="7422000" />
129
+ <workItem from="1761625684154" duration="11331000" />
130
+ <workItem from="1761645283635" duration="903000" />
131
+ <workItem from="1761646224510" duration="11898000" />
132
+ <workItem from="1761662886443" duration="13770000" />
133
+ <workItem from="1761712613432" duration="8032000" />
134
+ <workItem from="1761722199651" duration="12037000" />
135
+ <workItem from="1761745345070" duration="20383000" />
136
+ <workItem from="1761799722867" duration="32479000" />
137
+ <workItem from="1761842232436" duration="12041000" />
138
+ <workItem from="1761880978556" duration="25414000" />
139
+ <workItem from="1761918369357" duration="7960000" />
140
+ <workItem from="1761927975806" duration="16724000" />
141
+ <workItem from="1761973173786" duration="61000" />
142
+ <workItem from="1761975569971" duration="4404000" />
143
+ <workItem from="1762054192318" duration="6181000" />
144
+ <workItem from="1762077461972" duration="6397000" />
145
+ </task>
146
+ <servers />
147
+ </component>
148
+ <component name="TypeScriptGeneratedFilesManager">
149
+ <option name="version" value="3" />
150
+ </component>
151
+ <component name="Vcs.Log.Tabs.Properties">
152
+ <option name="OPEN_GENERIC_TABS">
153
+ <map>
154
+ <entry key="652b8592-29cd-4a28-a51b-3c9438d35564" value="TOOL_WINDOW" />
155
+ </map>
156
+ </option>
157
+ <option name="TAB_STATES">
158
+ <map>
159
+ <entry key="652b8592-29cd-4a28-a51b-3c9438d35564">
160
+ <value>
161
+ <State />
162
+ </value>
163
+ </entry>
164
+ </map>
165
+ </option>
166
+ </component>
167
+ <component name="VcsManagerConfiguration">
168
+ <ignored-roots>
169
+ <path value="$PROJECT_DIR$" />
170
+ </ignored-roots>
171
+ </component>
172
+ <component name="com.intellij.coverage.CoverageDataManagerImpl">
173
+ <SUITE FILE_PATH="coverage/math_agent$main.coverage" NAME="main Coverage Results" MODIFIED="1761922857873" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
174
+ </component>
175
+ </project>
__init__.py ADDED
File without changes
__pycache__/main.cpython-313.pyc ADDED
Binary file (1.6 kB). View file
 
agents/__init__.py ADDED
File without changes
agents/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (129 Bytes). View file
 
agents/__pycache__/feedback_agent.cpython-313.pyc ADDED
Binary file (5.08 kB). View file
 
agents/__pycache__/math_solver.cpython-313.pyc ADDED
Binary file (3.41 kB). View file
 
agents/__pycache__/routing_agent.cpython-313.pyc ADDED
Binary file (1.88 kB). View file
 
agents/__pycache__/vector_db.cpython-313.pyc ADDED
Binary file (1.79 kB). View file
 
agents/__pycache__/web_agent.cpython-313.pyc ADDED
Binary file (323 Bytes). View file
 
agents/feedback_agent.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ import json
4
+ import dspy
5
+
6
+ # path setup
7
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
8
+
9
+ from agents.routing_agent import route_query as math_agent
10
+
11
+ FEEDBACK = os.path.join("data", "feedback_log.json")
12
+
13
+ # DSPy
14
+ lm = dspy.LM("gpt-3.5-turbo")
15
+
16
+
17
+ class MathReasoner(dspy.Module):
18
+ def __init__(self):
19
+ super().__init__()
20
+ self.prog = dspy.ChainOfThought("question->answer")
21
+
22
+ def forward(self, question):
23
+ return self.prog(question=question)
24
+
25
+
26
+ # creating feedback file
27
+ def save_feedback(query: str, answer: str, feedback: str, rating: str = None):
28
+ entry = {
29
+ "query": query,
30
+ "answer": answer,
31
+ "feedback": feedback,
32
+ "rating": rating # ADDED RATING
33
+ }
34
+
35
+ if not os.path.exists(FEEDBACK):
36
+ with open(FEEDBACK, "w") as f:
37
+ json.dump([], f)
38
+
39
+ with open(FEEDBACK, "r+") as f:
40
+ data = json.load(f)
41
+ data.append(entry)
42
+ f.seek(0)
43
+ json.dump(data, f, indent=4)
44
+
45
+ print(f"feedback is saved: {feedback.upper()}")
46
+
47
+
48
+ # optimizing the hyperparameters
49
+ def tuning(query, incorrect_answer, rating: str = None):
50
+ example = [
51
+ dspy.Example(question=query, answer="its incorrect").with_inputs("question"),
52
+ ]
53
+
54
+ # ✅ define the metric
55
+ def simple_metric(example, pred, trace=None):
56
+ try:
57
+ gold_answer = example.answer.lower().strip()
58
+ pred_answer = pred.answer.lower().strip()
59
+ return 1.0 if gold_answer == pred_answer else 0.0
60
+ except:
61
+ return 0.0
62
+
63
+ # wrapper class for math_agent
64
+ class MathAgentWrapper(dspy.Module):
65
+ def forward(self, question):
66
+ result = math_agent(question)
67
+ return dspy.Prediction(answer=result)
68
+
69
+ # instance
70
+ wrapper_model = MathAgentWrapper()
71
+
72
+ # using BootstraoFewShot optimizer
73
+ trainer = dspy.BootstrapFewShot(
74
+ metric=simple_metric,
75
+ max_bootstrapped_demos=1,
76
+ max_labeled_demos=1
77
+ )
78
+ trainer.compile(wrapper_model, trainset=example)
79
+ print("🧠 Model updated based on feedback.")
80
+
81
+
82
+ # ✅ Wrapper to get answer
83
+ def answer(query: str):
84
+ result = math_agent(query)
85
+ return result
86
+
87
+
88
+ # main test for dspy
89
+ def main():
90
+ print("=== 🧠 Feedback Agent Test Run ===")
91
+ query = "What is the integral of sin(x)?"
92
+
93
+ # Step 1: Get model's answer
94
+ ans = answer(query)
95
+ print("Agent Answer:", ans)
96
+
97
+ # Step 2: Simulate user feedback
98
+ feedback = "Incorrect — the correct answer is -cos(x) + C"
99
+ rating = "negative" # ADDED RATING
100
+ save_feedback(query, ans, feedback, rating) # PASSED RATING
101
+
102
+ # Step 3: Fine-tune the model
103
+ tuning(query, incorrect_answer=ans, rating=rating) # PASSED RATING
104
+
105
+
106
+ # for testing persopes
107
+ if __name__ == "__main__":
108
+ main()
agents/math_solver.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import sympy as sp
3
+
4
+ def try_math_solver(query: str) -> str:
5
+ q = query.lower().strip()
6
+
7
+ # Remove filler words that confuse sympy
8
+ q = re.sub(r'\b(what is|calculate|find|compute|equals?|result of|area of|value of|solve)\b', '', q)
9
+ q = q.strip()
10
+
11
+ # Handle "where x = 5" style variable substitution
12
+ variables = dict(re.findall(r'(\w+)\s*=\s*([\d\.]+)', q))
13
+ for var in variables:
14
+ q = re.sub(rf"\b{var}\s*=\s*{variables[var]}\b", '', q)
15
+ q = re.sub(r'\bwhere\b', '', q)
16
+
17
+ # Handle patterns like “add 2 and 5”
18
+ patterns = [
19
+ (r'addition of (\d+(?:\.\d+)?) and (\d+(?:\.\d+)?)', r'(\1 + \2)'),
20
+ (r'add (\d+(?:\.\d+)?) and (\d+(?:\.\d+)?)', r'(\1 + \2)'),
21
+ (r'subtract (\d+(?:\.\d+)?) from (\d+(?:\.\d+)?)', r'(\2 - \1)'),
22
+ (r'subtract (\d+(?:\.\d+)?) and (\d+(?:\.\d+)?)', r'(\1 - \2)'),
23
+ (r'multiply (\d+(?:\.\d+)?) by (\d+(?:\.\d+)?)', r'(\1 * \2)'),
24
+ (r'divide (\d+(?:\.\d+)?) by (\d+(?:\.\d+)?)', r'(\1 / \2)'),
25
+ (r'(\d+(?:\.\d+)?) power (\d+(?:\.\d+)?)', r'(\1 ** \2)'),
26
+ (r'square root of (\d+(?:\.\d+)?)', r'sqrt(\1)'),
27
+ ]
28
+ for pat, repl in patterns:
29
+ q = re.sub(pat, repl, q)
30
+
31
+ # Replace simple words with symbols
32
+ replacements = {
33
+ "plus": "+", "minus": "-", "times": "*", "x": "*",
34
+ "mod": "%", "modulus": "%", "divided by": "/",
35
+ "power of": "**", "power": "**"
36
+ }
37
+ for word, sym in replacements.items():
38
+ q = re.sub(rf"\b{word}\b", sym, q)
39
+
40
+ # Remove assignments like “area =”
41
+ q = re.sub(r'\b\w+\s*=\s*', '', q).strip()
42
+
43
+ # Allow safe math functions
44
+ allowed_funcs = {
45
+ "sqrt": sp.sqrt, "sin": sp.sin, "cos": sp.cos, "tan": sp.tan,
46
+ "log": sp.log, "pi": sp.pi, "e": sp.E
47
+ }
48
+
49
+ try:
50
+ expr = sp.sympify(q, locals=allowed_funcs)
51
+ if variables:
52
+ subs = {sp.Symbol(k): float(v) for k, v in variables.items()}
53
+ expr = expr.subs(subs)
54
+ result = expr.evalf()
55
+ return f"The answer is {result}"
56
+ except Exception as e:
57
+ return f"Sorry, couldn't solve that expression. ({e})"
58
+
59
+
60
+ if __name__ == "__main__":
61
+ tests = [
62
+ "addition of 2 and 5",
63
+ "add 10 and 20",
64
+ "what is 12 minus 5",
65
+ "multiply 6 by 3",
66
+ "divide 15 by 3",
67
+ "10 power 2",
68
+ "100 mod 3",
69
+ "square root of 81",
70
+ "2 + 5 * 3",
71
+ "area = pi * r^2 where r = 5"
72
+ ]
73
+ for t in tests:
74
+ print(f"{t} → {try_math_solver(t)}")
agents/routing_agent.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_community.embeddings import HuggingFaceEmbeddings
2
+ from langchain_community.vectorstores import FAISS
3
+ from agents.math_solver import try_math_solver
4
+ import os
5
+ import re
6
+
7
+
8
+ def route_query(query: str):
9
+ persist_dir = os.path.join("data", "embeddings")
10
+
11
+ # ✅ Load embeddings
12
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
13
+ vectordb = FAISS.load_local(persist_dir, embeddings, allow_dangerous_deserialization=True)
14
+
15
+ # ✅ Step 1: Search in FAISS
16
+ results = vectordb.similarity_search_with_score(query, k=1)
17
+
18
+ # ✅ If found in FAISS
19
+ if results and results[0][1] < 0.4:
20
+ print("📘 Answer is on data.txt")
21
+ return "KO"
22
+
23
+ else:
24
+ # ✅ Step 2: Try math solver
25
+ print("🧮 Not found in FAISS — trying math solver...")
26
+ solver_result = try_math_solver(query)
27
+ print(f"🧩 Solver result: {solver_result}")
28
+
29
+ # ✅ Check if math solver succeeded
30
+ if solver_result and not any(bad in solver_result.lower() for bad in [
31
+ "sorry", "couldn't", "could not", "error", "invalid", "failed"
32
+ ]):
33
+ print("✅ Math solver succeeded!")
34
+ return solver_result
35
+
36
+ # ✅ If not solved by FAISS or math solver → Web Search
37
+ print("🌐 Not found anywhere — going for web search")
38
+ return "WEB"
agents/vector_db.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ warnings.filterwarnings("ignore", category=UserWarning)
3
+
4
+ import os
5
+ from langchain_community.document_loaders import DirectoryLoader, TextLoader
6
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
7
+ from langchain_community.embeddings import HuggingFaceEmbeddings
8
+ from langchain_community.vectorstores import FAISS
9
+
10
+ def create_text():
11
+ # Define paths
12
+ kb_path = os.path.join("data") # your text files folder
13
+ persist_dir = os.path.join("data", "embeddings")
14
+
15
+ # if exist
16
+ os.makedirs(kb_path, exist_ok=True)
17
+ os.makedirs(persist_dir, exist_ok=True)
18
+
19
+ # Load all text files from folder
20
+ loader = DirectoryLoader(kb_path, glob="*.txt", loader_cls=TextLoader)
21
+ documents = loader.load()
22
+
23
+ if not documents:
24
+ print("⚠️ No text files found in data folder!")
25
+ return
26
+
27
+ # Split long text into chunks for embedding
28
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
29
+ chunks = text_splitter.split_documents(documents)
30
+
31
+ # Load embedding model
32
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
33
+
34
+ # Create FAISS vector DB from documents
35
+ vectordb = FAISS.from_documents(chunks, embeddings)
36
+
37
+ # Save it locally
38
+ vectordb.save_local(persist_dir)
39
+
40
+ print("vector database created", persist_dir)
41
+ return vectordb
42
+
43
+
agents/web_agent.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from utils.mcp_client import run_mcp
2
+ def answer_from_web(query):
3
+ return run_mcp(query)
create_init_files.py ADDED
File without changes
data/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # This file makes Python treat this directory as a package
data/data.txt ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Q: What is the Pythagoras theorem?
2
+ A: In a right-angled triangle, the square of the hypotenuse is equal to the sum of the squares of the other two sides. Mathematically: a² + b² = c².
3
+
4
+ Q: What is the quadratic formula?
5
+ A: For a quadratic equation ax² + bx + c = 0, the roots are given by: x = (-b ± √(b² - 4ac)) / 2a.
6
+
7
+ Q: What is the derivative of x²?
8
+ A: The derivative of x² with respect to x is 2x.
9
+
10
+ Q: What is the integral of x²?
11
+ A: The integral of x² with respect to x is (x³ / 3) + C, where C is the constant of integration.
12
+
13
+ Q: What is the area of a circle?
14
+ A: The area of a circle is given by A = πr², where r is the radius.
15
+
16
+ Q: What is the circumference of a circle?
17
+ A: The circumference of a circle is given by C = 2πr, where r is the radius.
18
+
19
+ Q: What is the slope of a line passing through points (x1, y1) and (x2, y2)?
20
+ A: The slope is given by m = (y2 - y1) / (x2 - x1).
21
+
22
+ Q: What is the formula for simple interest?
23
+ A: Simple Interest = (Principal × Rate × Time) / 100.
24
+
25
+ Q: What is the formula for compound interest?
26
+ A: Compound Interest = Principal × (1 + Rate/100)^Time - Principal.
27
+
28
+ Q: What is the derivative of sin(x)?
29
+ A: The derivative of sin(x) is cos(x).
30
+
31
+ Q: What is the derivative of cos(x)?
32
+ A: The derivative of cos(x) is -sin(x).
33
+
34
+ Q: What is the integral of sin(x)?
35
+ A: The integral of sin(x) is -cos(x) + C.
36
+
37
+ Q: What is the integral of cos(x)?
38
+ A: The integral of cos(x) is sin(x) + C.
39
+
40
+ Q: What is the distance formula in coordinate geometry?
41
+ A: The distance between points (x1, y1) and (x2, y2) is √((x2 - x1)² + (y2 - y1)²).
42
+
43
+ Q: What is the midpoint formula?
44
+ A: The midpoint of a line joining (x1, y1) and (x2, y2) is ((x1 + x2)/2, (y1 + y2)/2).
45
+
46
+ Q: What is the sum of the first n natural numbers?
47
+ A: The sum is given by S = n(n + 1)/2.
48
+
49
+ Q: What is the sum of the first n even numbers?
50
+ A: The sum is n(n + 1).
51
+
52
+ Q: What is the sum of the first n odd numbers?
53
+ A: The sum is n².
54
+
55
+ Q: What is the formula for the area of a triangle?
56
+ A: Area = ½ × base × height.
57
+
58
+ Q: What is the trigonometric identity involving sin²(x) and cos²(x)?
59
+ A: sin²(x) + cos²(x) = 1.
60
+
61
+ Q: What is the binomial theorem?
62
+ A: The binomial theorem states that (a + b)^n = Σ [nCk * a^(n-k) * b^k], where the summation runs from k = 0 to n.
63
+
64
+ Q: What is the limit of sin(x)/x as x approaches 0?
65
+ A: The limit of sin(x)/x as x → 0 is 1.
66
+
67
+ Q: What is the derivative of e^x?
68
+ A: The derivative of e^x with respect to x is e^x.
69
+
70
+ Q: What is the derivative of ln(x)?
71
+ A: The derivative of ln(x) with respect to x is 1/x.
72
+
73
+ Q: What is the area under y = x between 0 and 2?
74
+ A: The area is ∫(0 to 2) x dx = [x² / 2]₀² = 2.
75
+
76
+ Q: What is the perimeter of a rectangle?
77
+ A: The perimeter of a rectangle is 2 × (length + width).
78
+
79
+ Q: What is the formula for volume of a sphere?
80
+ A: Volume = (4/3)πr³.
81
+
82
+ Q: What is the surface area of a sphere?
83
+ A: Surface Area = 4πr².
84
+
85
+ Q: What is the mean of numbers 4, 8, and 12?
86
+ A: Mean = (4 + 8 + 12) / 3 = 8.
87
+
88
+ Q: What is the median of the numbers 3, 5, 7, 9, 11?
89
+ A: The median is 7.
90
+
91
+ Q: What is the mode of the numbers 2, 3, 3, 5, 7?
92
+ A: The mode is 3.
data/embeddings/index.faiss ADDED
Binary file (6.19 kB). View file
 
data/embeddings/index.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2cf3b3fcdfb8202be6e4a12816b8b4ce8f98abb6c763a74de741d4aa3151394c
3
+ size 4343
data/feedback_log.json ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "timestamp": "2025-10-28T23:44:33.438347",
4
+ "query": "What is the integral of sin(x)?",
5
+ "answer": "WEB",
6
+ "feedback": "Incorrect \u2014 the correct answer is -cos(x) + C"
7
+ },
8
+ {
9
+ "timestamp": "2025-10-28T23:47:37.610680",
10
+ "query": "What is the integral of sin(x)?",
11
+ "answer": "WEB",
12
+ "feedback": "Incorrect \u2014 the correct answer is -cos(x) + C"
13
+ },
14
+ {
15
+ "timestamp": "2025-10-28T23:50:34.812828",
16
+ "query": "What is the integral of sin(x)?",
17
+ "answer": "WEB",
18
+ "feedback": "Incorrect \u2014 the correct answer is -cos(x) + C"
19
+ },
20
+ {
21
+ "timestamp": "2025-10-28T23:52:07.815951",
22
+ "query": "What is the integral of sin(x)?",
23
+ "answer": "WEB",
24
+ "feedback": "Incorrect \u2014 the correct answer is -cos(x) + C"
25
+ },
26
+ {
27
+ "timestamp": "2025-10-28T23:55:11.166467",
28
+ "query": "What is the integral of sin(x)?",
29
+ "answer": "WEB",
30
+ "feedback": "Incorrect \u2014 the correct answer is -cos(x) + C"
31
+ },
32
+ {
33
+ "timestamp": "2025-10-28T23:58:22.966961",
34
+ "query": "What is the integral of sin(x)?",
35
+ "answer": "WEB",
36
+ "feedback": "Incorrect \u2014 the correct answer is -cos(x) + C"
37
+ },
38
+ {
39
+ "timestamp": "2025-10-28T23:59:57.870620",
40
+ "query": "What is the integral of sin(x)?",
41
+ "answer": "WEB",
42
+ "feedback": "Incorrect \u2014 the correct answer is -cos(x) + C"
43
+ },
44
+ {
45
+ "timestamp": "2025-10-29T00:01:47.611761",
46
+ "query": "What is the integral of sin(x)?",
47
+ "answer": "WEB",
48
+ "feedback": "Incorrect \u2014 the correct answer is -cos(x) + C"
49
+ },
50
+ {
51
+ "timestamp": "2025-10-29T00:03:41.277987",
52
+ "query": "What is the integral of sin(x)?",
53
+ "answer": "WEB",
54
+ "feedback": "Incorrect \u2014 the correct answer is -cos(x) + C"
55
+ },
56
+ {
57
+ "timestamp": "2025-10-29T00:13:19.920208",
58
+ "query": "What is the integral of sin(x)?",
59
+ "answer": "WEB",
60
+ "feedback": "Incorrect \u2014 the correct answer is -cos(x) + C"
61
+ },
62
+ {
63
+ "timestamp": "2025-10-29T00:15:51.787155",
64
+ "query": "What is the integral of sin(x)?",
65
+ "answer": "WEB",
66
+ "feedback": "Incorrect \u2014 the correct answer is -cos(x) + C"
67
+ },
68
+ {
69
+ "timestamp": "2025-10-29T00:17:35.253793",
70
+ "query": "What is the integral of sin(x)?",
71
+ "answer": "WEB",
72
+ "feedback": "Incorrect \u2014 the correct answer is -cos(x) + C"
73
+ },
74
+ {
75
+ "timestamp": "2025-10-29T00:20:26.191961",
76
+ "query": "What is the integral of sin(x)?",
77
+ "answer": "WEB",
78
+ "feedback": "Incorrect \u2014 the correct answer is -cos(x) + C"
79
+ },
80
+ {
81
+ "timestamp": "2025-10-29T00:21:49.889546",
82
+ "query": "What is the integral of sin(x)?",
83
+ "answer": "WEB",
84
+ "feedback": "Incorrect \u2014 the correct answer is -cos(x) + C"
85
+ },
86
+ {
87
+ "timestamp": "2025-10-29T00:29:02.417399",
88
+ "query": "What is the integral of sin(x)?",
89
+ "answer": "WEB",
90
+ "feedback": "Incorrect \u2014 the correct answer is -cos(x) + C"
91
+ },
92
+ {
93
+ "timestamp": "2025-10-29T00:30:43.568817",
94
+ "query": "What is the integral of sin(x)?",
95
+ "answer": "WEB",
96
+ "feedback": "Incorrect \u2014 the correct answer is -cos(x) + C"
97
+ },
98
+ {
99
+ "timestamp": "2025-10-29T10:11:22.019712",
100
+ "query": "What is the integral of sin(x)?",
101
+ "answer": "WEB",
102
+ "feedback": "Incorrect \u2014 the correct answer is -cos(x) + C"
103
+ },
104
+ {
105
+ "timestamp": "2025-10-29T11:35:41.805717",
106
+ "query": "integration of sin(x)",
107
+ "answer": "The integral of sin(x) sin ( x ) with respect to x x is \u2212cos(x) - cos ( x ) . \u2212cos(x)+C - cos ( x ) + C. sin(x) s i n \u2061 ( x ) Mathematically, this is written as **\u222b sin x dx = -cos x + C**, were, C is the integration constant. * \u222b sin x dx = -cos x + C, where C is the constant of integration. \u222b sin x dx = -cos x + C -cos x + C = \u222b sin x dx **Answer:** \u222b sin x cos x dx = (-cos 2x)/4 + C \u222b sin u (1/2) du = (1/2) (-cos u) + C (as the integration of sin x is -cos x) **Answer:** \u222b x sin (x2) dx = (-cos x2)/2+C The integral of sin x is -cos x + C. Substituting u = 3x back, we get \u222b sin 3x dx = (1/3) (-cos (3x)) + C. Integral of sin(x)\nblackpenredpen\n1380000 subscribers\n1082 likes\n200320 views\n22 Feb 2015\nThe integral of sin(x) is just -cos(x)+C because the derivative of -cos(x) is sin(x).\n\nCheck out my 100 integrals for more calculus integral practice problems. https://youtu.be/dgm4-3-Iv3s?si=lTybJlpTMFdQINXr\n----------------------------------------\n\ud83d\udecd Shop my math t-shirt & hoodies: amzn.to/3qBeuw6\n\ud83d\udcaa Get my math notes by becoming a patron: https://www.patreon.com/blackpenredpen\n#blackpenredpen #math #calculus #apcalculus\n57 comments\n Our rough (rough!) conversion to Plain English is: The integral of sin(x) multiplies our intended path length (from 0 to x) by a percentage. # Integral of Sin x * What is Integral of Sin x? * Integral of Sin x From 0 to \u03c0 * Integral of Sin x From 0 to \u03c0/2 ## ****What is Integral of Sin x?**** The integral of the sine function, \u222b sin(x) dx, is equal to -cos(x) + C, where C is the constant of integration. Integral of sin(x) dx = -\u222b du Integral of sin(x) dx = -u + C Integral of sin(x) dx = -cos(x) + C ## ****Integral of Sin x From 0 to**** \u03c0 ## ****Integral of Sin x From 0 to**** \u03c0****/2**** ****Example 7: Find integral of x sin 2x dx**** ****Example 8: Find integral of sin x cos 2x****",
108
+ "feedback": "please give in 50 words"
109
+ },
110
+ {
111
+ "timestamp": "2025-10-29T19:15:40.383977",
112
+ "query": "What is the integral of sin(x)?",
113
+ "answer": "WEB",
114
+ "feedback": "Incorrect \u2014 the correct answer is -cos(x) + C"
115
+ },
116
+ {
117
+ "query": "derivative of sin(x)",
118
+ "answer": "The derivative of the sine function, sin\u2061(x), is the cosine function, cos\u2061(x). Mathematically, if f(x)=sin(x), then f\u2032(x)=cos\u2061(x). This result Here also we are going to prove the derivative of sin x to be -cos x using the first principle. The derivative of sin x is cos x. Thus, we have proved that the derivative of sin x is cos x. Therefore, the derivative of sin is cos x and is proved by using the quotient rule. Derivative of Sin x Worksheet Therefore, the derivative of sin x is cos x. * The derivative of sin x is cos x. Thus, the derivative of sin 3x is 3 cos 3x. Therefore, the derivative of sin x by first principle is cos x. We know that the derivative of sin x is cos x. So the derivative of sin x2 using this and using the chain rule is cos x2\u00b7 d/dx(x2). ## Derivative of sin x using the First Principle Method f\u2019(x) = limh\u21920 [sin x cos h + cos x sin h \u2013 sin x]/h f\u2019(x) = limh\u21920 [-sin x(1-cosh) + cos x sin h]/h sin (0/2)) + cos x (1) f\u2019(x) = \u2013 sin x(0) + cos x Thus, the derivative of sin x is cos x, is derived. ### Derivative of Sin x Examples Now, we have to find the derivative of sin (x+1), using the 1st principle. Hence, the derivative of sin (x+1), with respect to x is cos (x+1). Find the derivative of sin 2x. **To find:** derivative of sin 2x. Hence, the derivative of sin 2x is 2 cos 2x. ddx[sinx]=cosx Certainly, by the limit definition of the derivative, we know that ddx[sinx]=limh\u21920sin(x+h)\u2212sin(x)h ddx[sinx]=limh\u21920sinxcosh+cosxsinh\u2212sinxh Seeing all of the components of a similar limit in our expression for the derivative, (i.e., there is a sinh in the numerator, an h in the denominator, and both of these are inside a limit as h\u21920), we use algebra and the limit laws to reveal this known limit in our expression: ddx[sinx]=limh\u21920[cosxsinhh+sinxcosh\u2212sinxh]=limh\u21920[cosx\u22c5sinhh+sinxcosh\u2212sinxh]=limh\u21920cosx\u22c5limh\u21920sinhh+limh\u21920sinxcosh\u2212sinxh Note, the first limit in the last line above is of an expression that does not depend on h, and hence effectively the limit of a constant. ddx[sinx]=cosx+limh\u21920sinxcosh\u2212sinxh Pulling out the common factor of sinx in the remaining limit and splitting the resulting product with the limit laws again, we see another familiar limit -- one we which we know equals zero... ddx[sinx]=cosx+limh\u21920sinx(cosh\u22121)h=cosx+[limh\u21920sinx]\u22c5[limh\u21920cosh\u22121h]=cosx+sinx\u22c50=cosx d/dx(sin x) = \u03c0/180 cos x \"\"\" Which seems to suggest that the d/dx sin(x) is not equal to the cos(x) when degrees are used. That a constant must",
119
+ "feedback": "its cos(x)+c"
120
+ },
121
+ {
122
+ "query": "derivative of sin(x)",
123
+ "answer": "The derivative of the sine function, sin\u2061(x), is the cosine function, cos\u2061(x). Mathematically, if f(x)=sin(x), then f\u2032(x)=cos\u2061(x). This result Here also we are going to prove the derivative of sin x to be -cos x using the first principle. The derivative of sin x is cos x. Thus, we have proved that the derivative of sin x is cos x. Therefore, the derivative of sin is cos x and is proved by using the quotient rule. Derivative of Sin x Worksheet Therefore, the derivative of sin x is cos x. * The derivative of sin x is cos x. Thus, the derivative of sin 3x is 3 cos 3x. Therefore, the derivative of sin x by first principle is cos x. We know that the derivative of sin x is cos x. So the derivative of sin x2 using this and using the chain rule is cos x2\u00b7 d/dx(x2). ## Derivative of sin x using the First Principle Method f\u2019(x) = limh\u21920 [sin x cos h + cos x sin h \u2013 sin x]/h f\u2019(x) = limh\u21920 [-sin x(1-cosh) + cos x sin h]/h sin (0/2)) + cos x (1) f\u2019(x) = \u2013 sin x(0) + cos x Thus, the derivative of sin x is cos x, is derived. ### Derivative of Sin x Examples Now, we have to find the derivative of sin (x+1), using the 1st principle. Hence, the derivative of sin (x+1), with respect to x is cos (x+1). Find the derivative of sin 2x. **To find:** derivative of sin 2x. Hence, the derivative of sin 2x is 2 cos 2x. ddx[sinx]=cosx Certainly, by the limit definition of the derivative, we know that ddx[sinx]=limh\u21920sin(x+h)\u2212sin(x)h ddx[sinx]=limh\u21920sinxcosh+cosxsinh\u2212sinxh Seeing all of the components of a similar limit in our expression for the derivative, (i.e., there is a sinh in the numerator, an h in the denominator, and both of these are inside a limit as h\u21920), we use algebra and the limit laws to reveal this known limit in our expression: ddx[sinx]=limh\u21920[cosxsinhh+sinxcosh\u2212sinxh]=limh\u21920[cosx\u22c5sinhh+sinxcosh\u2212sinxh]=limh\u21920cosx\u22c5limh\u21920sinhh+limh\u21920sinxcosh\u2212sinxh Note, the first limit in the last line above is of an expression that does not depend on h, and hence effectively the limit of a constant. ddx[sinx]=cosx+limh\u21920sinxcosh\u2212sinxh Pulling out the common factor of sinx in the remaining limit and splitting the resulting product with the limit laws again, we see another familiar limit -- one we which we know equals zero... ddx[sinx]=cosx+limh\u21920sinx(cosh\u22121)h=cosx+[limh\u21920sinx]\u22c5[limh\u21920cosh\u22121h]=cosx+sinx\u22c50=cosx d/dx(sin x) = \u03c0/180 cos x \"\"\" Which seems to suggest that the d/dx sin(x) is not equal to the cos(x) when degrees are used. That a constant must",
124
+ "feedback": "its cos(x)+c",
125
+ "rating": null
126
+ },
127
+ {
128
+ "query": "derivative of sinx",
129
+ "answer": "The derivative of sin x is cos x, which is the rate of change of the sine function at any given point. Here also we are going to prove the derivative of sin x to be -cos x using the first principle. The derivative of sin x is cos x. Thus, we have proved that the derivative of sin x is cos x. Therefore, the derivative of sin is cos x and is proved by using the quotient rule. Derivative of Sin x Worksheet Therefore, the derivative of sin x is cos x. * The derivative of sin x is cos x. Thus, the derivative of sin 3x is 3 cos 3x. Therefore, the derivative of sin x by first principle is cos x. We know that the derivative of sin x is cos x. So the derivative of sin x2 using this and using the chain rule is cos x2\u00b7 d/dx(x2). ## Derivative of sin x using the First Principle Method f\u2019(x) = limh\u21920 [sin x cos h + cos x sin h \u2013 sin x]/h f\u2019(x) = limh\u21920 [-sin x(1-cosh) + cos x sin h]/h sin (0/2)) + cos x (1) f\u2019(x) = \u2013 sin x(0) + cos x Thus, the derivative of sin x is cos x, is derived. ### Derivative of Sin x Examples Now, we have to find the derivative of sin (x+1), using the 1st principle. Hence, the derivative of sin (x+1), with respect to x is cos (x+1). Find the derivative of sin 2x. **To find:** derivative of sin 2x. Hence, the derivative of sin 2x is 2 cos 2x. : r/calculus : r/calculus Image 1: r/calculus icon Go to calculus r/calculus Image 3: r/calculus iconr/calculus Welcome to r/calculus - a space for learning calculus and related disciplines. We learned in class that the derivative of sin(x) is cos(x). New to Reddit? * Reddit reReddit: Top posts of October 6, 2016 * * * * Reddit reReddit: Top posts of October 2016 * * * * Reddit reReddit: Top posts of 2016 * * * * Reddit Meta * Games * Gaming News & Discussion * Other Games * Action Movies & Series * Animated Movies & Series * Comedy Movies & Series * Romance Movies & Series * Superhero Movies & Series * About Reddit * Best of Reddit ddx[sinx]=cosx Certainly, by the limit definition of the derivative, we know that ddx[sinx]=limh\u21920sin(x+h)\u2212sin(x)h ddx[sinx]=limh\u21920sinxcosh+cosxsinh\u2212sinxh Seeing all of the components of a similar limit in our expression for the derivative, (i.e., there is a sinh in the numerator, an h in the denominator, and both of these are inside a limit as h\u21920), we use algebra and the limit laws to reveal this known limit in our expression: ddx[sinx]=limh\u21920[cosxsinhh+sinxcosh\u2212sinxh]=limh\u21920[cosx\u22c5sinhh+sinxcosh\u2212sinxh]=limh\u21920cosx\u22c5limh\u21920sinhh+limh\u21920sinxcosh\u2212sinxh Note, the first limit in the last line above is of an expression that does not depend on h, and hence effectively the limit of a constant. ddx[sinx]=cosx+limh\u21920sinxcosh\u2212sinxh Pulling out the common factor of sinx in the remaining limit and splitting the resulting product with the limit laws again, we see another familiar limit -- one we which we know equals zero... ddx[sinx]=cosx+limh\u21920sinx(cosh\u22121)h=cosx+[limh\u21920sinx]\u22c5[limh\u21920cosh\u22121h]=cosx+sinx\u22c50=cosx",
130
+ "feedback": "good",
131
+ "rating": null
132
+ },
133
+ {
134
+ "query": "derivative of sinx",
135
+ "answer": "The derivative of sin x is cos x, which is the rate of change of the sine function at any given point. Here also we are going to prove the derivative of sin x to be -cos x using the first principle. The derivative of sin x is cos x. Thus, we have proved that the derivative of sin x is cos x. Therefore, the derivative of sin is cos x and is proved by using the quotient rule. Derivative of Sin x Worksheet Therefore, the derivative of sin x is cos x. * The derivative of sin x is cos x. Thus, the derivative of sin 3x is 3 cos 3x. Therefore, the derivative of sin x by first principle is cos x. We know that the derivative of sin x is cos x. So the derivative of sin x2 using this and using the chain rule is cos x2\u00b7 d/dx(x2). ## Derivative of sin x using the First Principle Method f\u2019(x) = limh\u21920 [sin x cos h + cos x sin h \u2013 sin x]/h f\u2019(x) = limh\u21920 [-sin x(1-cosh) + cos x sin h]/h sin (0/2)) + cos x (1) f\u2019(x) = \u2013 sin x(0) + cos x Thus, the derivative of sin x is cos x, is derived. ### Derivative of Sin x Examples Now, we have to find the derivative of sin (x+1), using the 1st principle. Hence, the derivative of sin (x+1), with respect to x is cos (x+1). Find the derivative of sin 2x. **To find:** derivative of sin 2x. Hence, the derivative of sin 2x is 2 cos 2x. : r/calculus : r/calculus Image 1: r/calculus icon Go to calculus r/calculus Image 3: r/calculus iconr/calculus Welcome to r/calculus - a space for learning calculus and related disciplines. We learned in class that the derivative of sin(x) is cos(x). New to Reddit? * Reddit reReddit: Top posts of October 6, 2016 * * * * Reddit reReddit: Top posts of October 2016 * * * * Reddit reReddit: Top posts of 2016 * * * * Reddit Meta * Games * Gaming News & Discussion * Other Games * Action Movies & Series * Animated Movies & Series * Comedy Movies & Series * Romance Movies & Series * Superhero Movies & Series * About Reddit * Best of Reddit ddx[sinx]=cosx Certainly, by the limit definition of the derivative, we know that ddx[sinx]=limh\u21920sin(x+h)\u2212sin(x)h ddx[sinx]=limh\u21920sinxcosh+cosxsinh\u2212sinxh Seeing all of the components of a similar limit in our expression for the derivative, (i.e., there is a sinh in the numerator, an h in the denominator, and both of these are inside a limit as h\u21920), we use algebra and the limit laws to reveal this known limit in our expression: ddx[sinx]=limh\u21920[cosxsinhh+sinxcosh\u2212sinxh]=limh\u21920[cosx\u22c5sinhh+sinxcosh\u2212sinxh]=limh\u21920cosx\u22c5limh\u21920sinhh+limh\u21920sinxcosh\u2212sinxh Note, the first limit in the last line above is of an expression that does not depend on h, and hence effectively the limit of a constant. ddx[sinx]=cosx+limh\u21920sinxcosh\u2212sinxh Pulling out the common factor of sinx in the remaining limit and splitting the resulting product with the limit laws again, we see another familiar limit -- one we which we know equals zero... ddx[sinx]=cosx+limh\u21920sinx(cosh\u22121)h=cosx+[limh\u21920sinx]\u22c5[limh\u21920cosh\u22121h]=cosx+sinx\u22c50=cosx",
136
+ "feedback": "good",
137
+ "rating": null
138
+ },
139
+ {
140
+ "query": "derivative of sinx",
141
+ "answer": "The derivative of sin x is cos x, which is the rate of change of the sine function at any given point. Here also we are going to prove the derivative of sin x to be -cos x using the first principle. The derivative of sin x is cos x. Thus, we have proved that the derivative of sin x is cos x. Therefore, the derivative of sin is cos x and is proved by using the quotient rule. Derivative of Sin x Worksheet Therefore, the derivative of sin x is cos x. * The derivative of sin x is cos x. Thus, the derivative of sin 3x is 3 cos 3x. Therefore, the derivative of sin x by first principle is cos x. We know that the derivative of sin x is cos x. So the derivative of sin x2 using this and using the chain rule is cos x2\u00b7 d/dx(x2). ## Derivative of sin x using the First Principle Method f\u2019(x) = limh\u21920 [sin x cos h + cos x sin h \u2013 sin x]/h f\u2019(x) = limh\u21920 [-sin x(1-cosh) + cos x sin h]/h sin (0/2)) + cos x (1) f\u2019(x) = \u2013 sin x(0) + cos x Thus, the derivative of sin x is cos x, is derived. ### Derivative of Sin x Examples Now, we have to find the derivative of sin (x+1), using the 1st principle. Hence, the derivative of sin (x+1), with respect to x is cos (x+1). Find the derivative of sin 2x. **To find:** derivative of sin 2x. Hence, the derivative of sin 2x is 2 cos 2x. : r/calculus : r/calculus Image 1: r/calculus icon Go to calculus r/calculus Image 3: r/calculus iconr/calculus Welcome to r/calculus - a space for learning calculus and related disciplines. We learned in class that the derivative of sin(x) is cos(x). New to Reddit? * Reddit reReddit: Top posts of October 6, 2016 * * * * Reddit reReddit: Top posts of October 2016 * * * * Reddit reReddit: Top posts of 2016 * * * * Reddit Meta * Games * Gaming News & Discussion * Other Games * Action Movies & Series * Animated Movies & Series * Comedy Movies & Series * Romance Movies & Series * Superhero Movies & Series * About Reddit * Best of Reddit ddx[sinx]=cosx Certainly, by the limit definition of the derivative, we know that ddx[sinx]=limh\u21920sin(x+h)\u2212sin(x)h ddx[sinx]=limh\u21920sinxcosh+cosxsinh\u2212sinxh Seeing all of the components of a similar limit in our expression for the derivative, (i.e., there is a sinh in the numerator, an h in the denominator, and both of these are inside a limit as h\u21920), we use algebra and the limit laws to reveal this known limit in our expression: ddx[sinx]=limh\u21920[cosxsinhh+sinxcosh\u2212sinxh]=limh\u21920[cosx\u22c5sinhh+sinxcosh\u2212sinxh]=limh\u21920cosx\u22c5limh\u21920sinhh+limh\u21920sinxcosh\u2212sinxh Note, the first limit in the last line above is of an expression that does not depend on h, and hence effectively the limit of a constant. ddx[sinx]=cosx+limh\u21920sinxcosh\u2212sinxh Pulling out the common factor of sinx in the remaining limit and splitting the resulting product with the limit laws again, we see another familiar limit -- one we which we know equals zero... ddx[sinx]=cosx+limh\u21920sinx(cosh\u22121)h=cosx+[limh\u21920sinx]\u22c5[limh\u21920cosh\u22121h]=cosx+sinx\u22c50=cosx",
142
+ "feedback": "its too long!",
143
+ "rating": null
144
+ },
145
+ {
146
+ "query": "derivative of sinx",
147
+ "answer": "The derivative of sin x is the rate of change with respect to angle ie, x. The resultant of the derivative of sin x is cos x. Here also we are going to prove the derivative of sin x to be -cos x using the first principle. The derivative of sin x is cos x. Thus, we have proved that the derivative of sin x is cos x. Therefore, the derivative of sin is cos x and is proved by using the quotient rule. Derivative of Sin x Worksheet Therefore, the derivative of sin x is cos x. * The derivative of sin x is cos x. Thus, the derivative of sin 3x is 3 cos 3x. Therefore, the derivative of sin x by first principle is cos x. We know that the derivative of sin x is cos x. So the derivative of sin x2 using this and using the chain rule is cos x2\u00b7 d/dx(x2). The derivative of sin(x) is cos(x). Why? The derivative of any given function is simply the slope of the tangent line to original function ## Derivative of sin x using the First Principle Method f\u2019(x) = limh\u21920 [sin x cos h + cos x sin h \u2013 sin x]/h f\u2019(x) = limh\u21920 [-sin x(1-cosh) + cos x sin h]/h sin (0/2)) + cos x (1) f\u2019(x) = \u2013 sin x(0) + cos x Thus, the derivative of sin x is cos x, is derived. ### Derivative of Sin x Examples Now, we have to find the derivative of sin (x+1), using the 1st principle. Hence, the derivative of sin (x+1), with respect to x is cos (x+1). Find the derivative of sin 2x. **To find:** derivative of sin 2x. Hence, the derivative of sin 2x is 2 cos 2x. : r/calculus : r/calculus Image 1: r/calculus icon Go to calculus r/calculus Image 3: r/calculus iconr/calculus Welcome to r/calculus - a space for learning calculus and related disciplines. We learned in class that the derivative of sin(x) is cos(x). New to Reddit? * Reddit reReddit: Top posts of October 6, 2016 * * * * Reddit reReddit: Top posts of October 2016 * * * * Reddit reReddit: Top posts of 2016 * * * * Reddit Meta * Games * Gaming News & Discussion * Other Games * Action Movies & Series * Animated Movies & Series * Comedy Movies & Series * Romance Movies & Series * Superhero Movies & Series * About Reddit * Best of Reddit",
148
+ "feedback": "liitle bit small",
149
+ "rating": null
150
+ }
151
+ ]
docker-compose.yml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ backend:
3
+ build: .
4
+ ports:
5
+ - "8000:8000"
6
+ environment:
7
+ - PORT=8000
8
+ command: uvicorn main:app --host 0.0.0.0 --port 8000
9
+
10
+
11
+ frontend:
12
+ build:
13
+ context: ./Frontend/react-app
14
+ dockerfile: Dockerfile
15
+ ports:
16
+ - "3000:80"
17
+
18
+ backend_v2:
19
+ build:
20
+ context: .
21
+ dockerfile: Dockerfile.v2
22
+ container_name: math_agent_v2
23
+ ports:
24
+ - "8080:8000"
25
+ environment:
26
+ - PORT=8000
27
+ command: uvicorn main:app --host 0.0.0.0 --port 8000
main.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.environ["USE_TF"] = "0"
3
+ import sys
4
+
5
+ # Add the current directory to Python path so Backend imports work
6
+ current_dir = os.path.dirname(os.path.abspath(__file__))
7
+ sys.path.insert(0, current_dir)
8
+
9
+ from fastapi import FastAPI
10
+ from fastapi.middleware.cors import CORSMiddleware
11
+ from router.rag_router import router as rag_router
12
+ from router.feedback_router import router as feedback_router
13
+ app = FastAPI(
14
+ title="Math Routing Agent ",
15
+ description="Hello",
16
+ version="1.0.0"
17
+ )
18
+
19
+ app.add_middleware(
20
+ CORSMiddleware,
21
+ allow_origins=["*"], # you can restrict this later to your React app
22
+ allow_credentials=True,
23
+ allow_methods=["*"],
24
+ allow_headers=["*"],
25
+ )
26
+ #Routers
27
+ app.include_router(rag_router, prefix="/api/query", tags=["RAG Router"])
28
+ app.include_router(feedback_router, prefix="/api/feedback", tags=["Feedback Router"])
29
+ # Endpoint
30
+ @app.get("/")
31
+ async def root():
32
+ return {"message": "Math Routing Agent API is on"}
33
+
34
+ if __name__ == "__main__":
35
+ import uvicorn
36
+ uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ sympy
2
+ requests~=2.32.5
3
+ python-dotenv~=1.2.1
4
+ shim~=0.1.0
5
+ langchain-community~=0.4.1
6
+ langchain-text-splitters~=1.0.0
7
+ qdrant-client~=1.15.1
8
+ dspy~=3.0.3
9
+ fastapi~=0.120.0
10
+ pydantic~=2.12.3
11
+ uvicorn~=0.38.0
12
+ sentence-transformers==5.1.2
13
+ faiss-cpu
14
+
15
+
router/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # This file makes Python treat this directory as a package
router/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (129 Bytes). View file
 
router/__pycache__/feedback_router.cpython-313.pyc ADDED
Binary file (1.54 kB). View file
 
router/__pycache__/rag_router.cpython-313.pyc ADDED
Binary file (1.98 kB). View file
 
router/feedback_router.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, HTTPException
2
+ from pydantic import BaseModel
3
+ from agents.feedback_agent import save_feedback, tuning
4
+
5
+ router = APIRouter()
6
+
7
+ class Feedback(BaseModel):
8
+ query: str
9
+ answer: str
10
+ feedback: str
11
+ rating:str=None# user’s correction or comment
12
+
13
+ @router.post("/submit")
14
+ async def submit_feedback(feedback: Feedback):
15
+ try:
16
+ save_feedback(feedback.query, feedback.answer, feedback.feedback)
17
+ tuning(feedback.query, incorrect_answer=feedback.feedback)
18
+
19
+ return {
20
+ "status": "success",
21
+ "message": "Feedback is saved and model updated successfully",
22
+ "data": feedback.model_dump(),
23
+ }
24
+ except Exception as e:
25
+ raise HTTPException(status_code=500, detail=str(e))
router/rag_router.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import HTTPException, APIRouter
2
+ from pydantic import BaseModel
3
+
4
+ from agents.routing_agent import route_query
5
+ from agents.vector_db import create_text
6
+ from agents.web_agent import answer_from_web
7
+
8
+ router = APIRouter()
9
+
10
+ class QueryInput(BaseModel):
11
+ question: str
12
+
13
+ class QueryResponse(BaseModel):
14
+ source: str
15
+ answer: str
16
+
17
+ @router.post("/ask", response_model=QueryResponse)
18
+ async def ask(query: QueryInput):
19
+ try:
20
+ user_question = query.question
21
+ print(f"🧠 Received query: {user_question}")
22
+
23
+ decision = route_query(user_question)
24
+ print(f"📤 Routing result: {decision}")
25
+
26
+ if decision == "KO":
27
+ answer = create_text(user_question)
28
+ return QueryResponse(source="Knowledge Base", answer=answer)
29
+
30
+ elif decision == "WEB":
31
+ answer = answer_from_web(user_question)
32
+ return QueryResponse(source="Web Search", answer=answer)
33
+
34
+ else:
35
+ # ✅ Math solver gave an actual answer
36
+ return QueryResponse(source="Math Solver", answer=decision)
37
+
38
+ except Exception as e:
39
+ print(f"❌ Error: {e}")
40
+ raise HTTPException(status_code=500, detail=str(e))
41
+
42
+
utils/__init__.py ADDED
File without changes
utils/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (128 Bytes). View file
 
utils/__pycache__/mcp_client.cpython-313.pyc ADDED
Binary file (1.47 kB). View file
 
utils/guardrails.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ def validate_math_query(query: str) -> bool:
3
+
4
+ if not query or len(query.strip()) == 0:
5
+ return False
6
+
7
+
8
+ # block irrevalent characters
9
+ disallowed_patterns=[
10
+ r"import\s+", r"exec\s+", r"os\.system", r"subprocess", r"__"
11
+ ]
12
+
13
+ for pattern in disallowed_patterns:
14
+ if re.search(pattern, query):
15
+ return False
16
+
17
+ safe_pattern= r"^[0-9a-zA-Z\s\+\-\*\/\^\(\)\=\?\.\,]+$"
18
+ return bool(re.match(safe_pattern, query))
19
+
20
+ #to clean the model response
21
+ def sanitize(response:str) -> str:
22
+ cleaned=re.sub(r"\s+"," ",response)
23
+ cleaned =re.sub(r"^\s+"," ",cleaned)
24
+ return cleaned.strip()
25
+
26
+ if __name__ == "__main__":
27
+ test_queries = [
28
+ "Solve 2x + 3 = 7",
29
+ "import os; os.system('rm -rf /')",
30
+ "Find derivative of sin(x)^2",
31
+ ""
32
+ ]
33
+
34
+ for q in test_queries:
35
+ print(f"\n Query: {q}")
36
+ print("Valid " if validate_math_query(q) else " Invalid")
37
+
38
+ resp = "```python\nAnswer = 42\n```"
39
+ print("\nCleaned Output:", sanitize(resp))
utils/jee_bench_eval.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from agents.routing_agent import route_query
2
+ from utils.guardrails import validate_math_query, sanitize
3
+
4
+ def evaluate(txt_path:str):
5
+
6
+ total,correct=0,0
7
+ results=[]
8
+
9
+ with open(txt_path,"r" ,encoding="utf-8") as f:
10
+ content=f.read().strip().split("\n\n")
11
+
12
+ for block in content:
13
+ if not block.strip():
14
+ continue
15
+
16
+ lines = block.strip().split("\n")
17
+ question=next((l[3:].strip() for l in lines if l.startswith("Q:")),None)
18
+ expected=next((l[3:].strip().lower() for l in lines if l.startswith("A:")),"")
19
+
20
+ if not question or not expected:
21
+ continue
22
+
23
+ if not validate_math_query(question):
24
+ print(f"⚠️ Skipping invalid query: {question}")
25
+ continue
26
+
27
+ response=route_query(question)
28
+ cleaned=sanitize(response).lower()
29
+
30
+ is_right=expected in cleaned
31
+ results.append({
32
+ "Question": question,
33
+ "Expected": expected,
34
+ "ModelAnswer": cleaned,
35
+ "Match": is_right
36
+ })
37
+
38
+ total+=1
39
+
40
+ if is_right:
41
+ correct+=1
42
+
43
+ accuracy = (correct / total * 100) if total > 0 else 0.0
44
+
45
+
46
+ print(f"{accuracy:.2f}% ({correct}/{total})")
47
+ print(results)
48
+
49
+ if __name__ == "__main__":
50
+ txt_file = "data/data.txt"
51
+ evaluate(txt_file)
utils/mcp_client.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # backend/utils/mcp_client.py
2
+ import os
3
+ import requests
4
+ from dotenv import load_dotenv
5
+
6
+ # Load environment variables
7
+ load_dotenv()
8
+
9
+ TAVILY_API_KEY = os.getenv("TAVILY_API_KEY", "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")
10
+ TAVILY_ENDPOINT = "https://api.tavily.com/search"
11
+
12
+ def run_mcp(query, k=2):
13
+ #we are using tavily api for external search
14
+ headers = {"Content-Type": "application/json"}
15
+ data = {
16
+ "api_key": TAVILY_API_KEY,
17
+ "query": query,
18
+ "num_results": k
19
+ }
20
+
21
+ try:
22
+ response = requests.post(TAVILY_ENDPOINT, json=data, headers=headers)
23
+ response.raise_for_status()
24
+ results = response.json()
25
+
26
+ # Extract and combine content snippets
27
+ context = " ".join([r.get("content", "") for r in results.get("results", [])])
28
+ return context.strip() or "No relevant web data found."
29
+ except Exception as e:
30
+ print(f" MCP search failed: {e}")
31
+ return "Web search unavailable."
32
+
33
+
utils/vectorstore_setup.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from langchain_community.document_loaders import DirectoryLoader, TextLoader
3
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
4
+ from langchain_community.embeddings import HuggingFaceEmbeddings
5
+ from langchain_qdrant import QdrantVectorStore
6
+ from qdrant_client import QdrantClient
7
+
8
+ def setup_qdrant_vectorstore():
9
+
10
+ #here i want to create a Qdrant VectorDB with the help of hugggingface embeddings
11
+ kb_path=os.path.join("data")
12
+ os.makedirs(kb_path, exist_ok=True)
13
+
14
+ #connect local Qdrant
15
+ client=QdrantClient(host="localhost",port=6333)
16
+
17
+ #Loading data with directory laoder
18
+ loader = DirectoryLoader(kb_path, glob="*.txt", loader_cls=TextLoader)
19
+ documents = loader.load()
20
+
21
+ #split the text data
22
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
23
+ chunks = text_splitter.split_documents(documents)
24
+
25
+ #embedding
26
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
27
+
28
+ vectordb=QdrantVectorStore.from_documents(
29
+ documents=chunks,
30
+ embedding=embeddings,
31
+ url="http://localhost:6333",
32
+ collection_name="math_knowledge_base"
33
+ )
34
+
35
+ print(" Qdrant Vector Store setup completed!")
36
+ return vectordb
37
+
38
+ if __name__ == "__main__":
39
+ print("Testing Qdrant Vector Store setup")
40
+
41
+ vectordb = setup_qdrant_vectorstore()
42
+
43
+ # simple check
44
+ print("VectorDB successfully created!")
45
+ print("Collections available:", vectordb.client.get_collections())