codeboosterstech commited on
Commit
d5b3078
·
verified ·
1 Parent(s): 13bcc0d

Update multi_agent.py

Browse files
Files changed (1) hide show
  1. multi_agent.py +82 -141
multi_agent.py CHANGED
@@ -1,145 +1,86 @@
1
- """
2
- Enhanced multi-agent system with dynamic marks configuration
3
- """
4
-
5
  import json
6
- import time
7
- from typing import Dict, Any, Tuple
8
- from agents import GeneratorAgent, VerifierAgent, FormatterAgent, SearchAgent
9
- from prompts import get_generator_prompt, VERIFIER_PROMPT, FORMATTER_PROMPT
10
-
11
- class MultiAgentSystem:
12
- """Enhanced orchestrator with dynamic marks support"""
13
-
14
- def __init__(self):
15
- self.generator = GeneratorAgent()
16
- self.verifier = VerifierAgent()
17
- self.formatter = FormatterAgent()
18
- self.searcher = SearchAgent()
19
-
20
- self.progress = {
21
- "stage": "ready",
22
- "message": "System ready",
23
- "percentage": 0
24
- }
25
-
26
- def update_progress(self, stage: str, message: str, percentage: int):
27
- """Update generation progress"""
28
- self.progress = {
29
- "stage": stage,
30
- "message": message,
31
- "percentage": percentage
32
- }
33
- print(f"Progress: {stage} - {message} ({percentage}%)")
34
-
35
- def extract_syllabus_from_pdf(self, pdf_file) -> str:
36
- """Extract text from uploaded syllabus PDF"""
 
 
 
37
  try:
38
- import PyPDF2
39
- pdf_reader = PyPDF2.PdfReader(pdf_file)
40
- text = ""
41
- for page in pdf_reader.pages:
42
- text += page.extract_text()
43
- return text[:3000]
44
- except Exception as e:
45
- print(f"PDF extraction error: {e}")
46
- return "Syllabus text extraction failed. Using default template."
47
-
48
- def extract_reference_from_pdf(self, pdf_file) -> str:
49
- """Extract text from reference question paper PDF"""
50
- if pdf_file is None:
51
- return "No reference question paper provided."
52
-
53
  try:
54
- import PyPDF2
55
- pdf_reader = PyPDF2.PdfReader(pdf_file)
56
- text = ""
57
- for page in pdf_reader.pages[:3]:
58
- text += page.extract_text()
59
- return text[:2000]
60
- except Exception as e:
61
- print(f"Reference PDF extraction error: {e}")
62
- return "Reference paper extraction failed."
63
-
64
- def generate_exam_package(self,
65
- subject: str,
66
- stream: str,
67
- part_a_count: int,
68
- part_b_count: int,
69
- part_c_count: int,
70
- part_a_marks: int = 2,
71
- part_b_marks: int = 13,
72
- part_c_marks: int = 14,
73
- syllabus_file = None,
74
- reference_file = None) -> Tuple[Dict[str, Any], str]:
75
- """Enhanced main method with dynamic marks"""
76
-
 
 
77
  try:
78
- # Stage 1: Data Preparation
79
- self.update_progress("preparation", "Extracting syllabus and reference data", 10)
80
- syllabus_text = self.extract_syllabus_from_pdf(syllabus_file)
81
- reference_text = self.extract_reference_from_pdf(reference_file)
82
-
83
- # Stage 2: Realtime Search
84
- self.update_progress("search", "Fetching recent developments", 20)
85
- realtime_updates = self.searcher.get_realtime_updates(subject)
86
-
87
- # Stage 3: Generation with dynamic marks
88
- self.update_progress("generation", "Generating question paper structure", 40)
89
- generator_prompt = get_generator_prompt(
90
- subject=subject,
91
- stream=stream,
92
- syllabus_text=syllabus_text,
93
- reference_text=reference_text,
94
- realtime_updates=realtime_updates,
95
- part_a_count=part_a_count,
96
- part_b_count=part_b_count,
97
- part_c_count=part_c_count,
98
- part_a_marks=part_a_marks,
99
- part_b_marks=part_b_marks,
100
- part_c_marks=part_c_marks
101
- )
102
-
103
- generated_content = self.generator.generate_question_paper(generator_prompt)
104
-
105
- if "error" in generated_content:
106
- return {}, "Generation failed: " + generated_content["error"]
107
-
108
- # Stage 4: Verification with dynamic marks
109
- self.update_progress("verification", "Verifying quality and standards", 60)
110
- verifier_prompt = VERIFIER_PROMPT.format(
111
- generated_content=json.dumps(generated_content, indent=2),
112
- bloom_mix="60% R/U, 40% A/An/Ev" if stream == "CSE" else "50% R/U, 50% A/An/Ev",
113
- part_a_count=part_a_count,
114
- part_b_count=part_b_count,
115
- part_c_count=part_c_count,
116
- part_a_marks=part_a_marks,
117
- part_b_marks=part_b_marks,
118
- part_c_marks=part_c_marks,
119
- tag_requirements="Company tags" if stream == "CSE" else "GATE tags"
120
- )
121
-
122
- verification_result = self.verifier.verify_content(verifier_prompt)
123
-
124
- # Stage 5: Formatting
125
- self.update_progress("formatting", "Creating final outputs and answers", 80)
126
- formatter_prompt = FORMATTER_PROMPT.format(
127
- original_content=json.dumps(generated_content, indent=2),
128
- corrections=json.dumps(verification_result, indent=2)
129
- )
130
-
131
- final_output = self.formatter.format_final_output(formatter_prompt)
132
-
133
- # Stage 6: Completion
134
- self.update_progress("completion", "Package generation complete", 100)
135
-
136
- return final_output, "Success"
137
-
138
- except Exception as e:
139
- error_msg = f"System error: {str(e)}"
140
- print(error_msg)
141
- return {}, error_msg
142
-
143
- def get_progress(self) -> Dict[str, Any]:
144
- """Get current progress"""
145
- return self.progress
 
 
 
 
 
1
  import json
2
+ from agents import GroqClient, SerpClient
3
+ from prompts import build_master_prompt
4
+
5
+
6
+ GENERATOR_MODEL = "llama-3.1-70b-versatile"
7
+ VERIFIER_MODEL = "gemma2-27b-it"
8
+ FORMATTER_MODEL = "mixtral-8x7b-32768"
9
+
10
+
11
+ class MultiAgentOrchestrator:
12
+ def __init__(self, groq: GroqClient, serp: SerpClient):
13
+ self.groq = groq
14
+ self.serp = serp
15
+
16
+ def run_pipeline(self, subject, stream, partA, partB, partC, syllabus_text, ref_qp_text):
17
+
18
+ # 1) Real-time search
19
+ serp_results = self.serp.search(f"{subject} latest 2024 2025")
20
+ snippets = "\n".join([r.get("snippet", "") for r in serp_results[:3]])
21
+
22
+ # 2) Build master prompt
23
+ master_prompt = build_master_prompt(
24
+ subject, stream, partA, partB, partC,
25
+ syllabus_text, ref_qp_text, snippets
26
+ )
27
+
28
+ # 3) AGENT 1 — GENERATOR
29
+ gen_output = self.groq.ask(
30
+ [{"role": "system", "content": "Exam generator agent."},
31
+ {"role": "user", "content": master_prompt}],
32
+ model=GENERATOR_MODEL
33
+ )
34
+
35
+ # Extract JSON from generator
36
  try:
37
+ json_start = gen_output.rfind("{")
38
+ qp_json = json.loads(gen_output[json_start:])
39
+ except:
40
+ qp_json = {"raw": gen_output}
41
+
42
+ # 4) AGENT 2 — VERIFIER
43
+ ver_prompt = f"Check this QP JSON for errors and propose corrections:\n{json.dumps(qp_json)}"
44
+ verifier_output = self.groq.ask(
45
+ [{"role": "system", "content": "Verifier agent."},
46
+ {"role": "user", "content": ver_prompt}],
47
+ model=VERIFIER_MODEL
48
+ )
49
+
 
 
50
  try:
51
+ corrections = json.loads(verifier_output)
52
+ except:
53
+ corrections = {"notes": verifier_output}
54
+
55
+ # 5) AGENT 3 — FORMATTER
56
+ fmt_prompt = f"""
57
+ Apply corrections to QP JSON and produce:
58
+ 1. final_qp
59
+ 2. answers
60
+ 3. obe
61
+ All inside ONE valid JSON object.
62
+
63
+ Original QP:
64
+ {json.dumps(qp_json)}
65
+
66
+ Corrections:
67
+ {json.dumps(corrections)}
68
+ """
69
+
70
+ final_output = self.groq.ask(
71
+ [{"role": "system", "content": "Formatter agent."},
72
+ {"role": "user", "content": fmt_prompt}],
73
+ model=FORMATTER_MODEL
74
+ )
75
+
76
  try:
77
+ final_json = json.loads(final_output)
78
+ except:
79
+ final_json = {"raw": final_output}
80
+
81
+ return {
82
+ "generator_raw": gen_output,
83
+ "qp_json": qp_json,
84
+ "verifier": corrections,
85
+ "final": final_json
86
+ }