ABVM commited on
Commit
91cb0ea
·
verified ·
1 Parent(s): 2d54bed

Upload multi_agent.py

Browse files
Files changed (1) hide show
  1. multi_agent.py +168 -0
multi_agent.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from smolagents import (
3
+ CodeAgent,
4
+ InferenceClientModel,
5
+ VisitWebpageTool,
6
+ WebSearchTool,
7
+ WikipediaSearchTool,
8
+ PythonInterpreterTool,
9
+ FinalAnswerTool,
10
+ tool
11
+ )
12
+ from groq import Groq
13
+ from typing import Dict, Any
14
+ import os
15
+ import time
16
+
17
+ # ---- TOOLS ----
18
+ @tool
19
+ def image_process(image_file: str) -> Dict[str, str]:
20
+ """
21
+ Extract text from an image file using OCR and return OCR text and base64 encoding.
22
+
23
+ Args:
24
+ image_file: Path to the image file
25
+
26
+ Returns:
27
+ Dict with keys 'ocr_text' and 'base64_image'
28
+ """
29
+ try:
30
+ import pytesseract
31
+ from PIL import Image
32
+ from smolagents.utils import encode_image_base64
33
+ image = Image.open(image_file)
34
+ base64_img = encode_image_base64(image)
35
+ text = pytesseract.image_to_string(image)
36
+ return {
37
+ "ocr_text": text,
38
+ "base64_image": base64_img
39
+ }
40
+ except Exception as e:
41
+ return {
42
+ "ocr_text": "",
43
+ "base64_image": "",
44
+ "error": str(e)
45
+ }
46
+
47
+ # ---- GROQ MODEL WRAPPER ----
48
+ class LLMResponse:
49
+ def __init__(self, content: str, token_usage: int | None = None):
50
+ self.content = content
51
+ self.token_usage = token_usage
52
+
53
+ class GroqModel:
54
+ def __init__(self, model_name=""):
55
+ self.model_name = model_name
56
+ self.client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
57
+
58
+ def __call__(self, prompt, max_tokens=8096):
59
+ if isinstance(prompt, str):
60
+ messages = [{"role": "user", "content": prompt}]
61
+ else:
62
+ messages = prompt
63
+
64
+ response = None
65
+ for attempt in range(3):
66
+ try:
67
+ response = self.client.chat.completions.create(
68
+ messages=messages,
69
+ model=self.model_name,
70
+ stream=False,
71
+ max_tokens=max_tokens,
72
+ )
73
+ break
74
+ except Exception as e:
75
+ msg = str(e).lower()
76
+ if "rate limit" in msg and attempt < 2:
77
+ wait = 10 * (attempt + 1)
78
+ time.sleep(wait)
79
+ continue
80
+ raise
81
+
82
+
83
+ response = self.client.chat.completions.create(
84
+ messages=messages,
85
+ model=self.model_name,
86
+ stream=False,
87
+ max_tokens=max_tokens,
88
+ )
89
+
90
+
91
+ def generate(self, prompt, max_tokens=8096, **kwargs):
92
+ # For compatibility with agent frameworks
93
+ return self.__call__(prompt, max_tokens=max_tokens)
94
+
95
+
96
+ # ---- MULTI-AGENT SYSTEM ----
97
+ class MultyAgentSystem:
98
+ def __init__(self):
99
+ deepseek_model = GroqModel("deepseek-r1-distill-llama-70b")
100
+ qwen_model = GroqModel("qwen-qwq-32b")
101
+
102
+ # --- Web agent definition ---
103
+ self.web_agent = CodeAgent(
104
+ model=qwen_model,
105
+ tools=[WebSearchTool(), VisitWebpageTool(), WikipediaSearchTool()],
106
+ name="web_agent",
107
+ description=(
108
+ "You are a web browsing agent. Whenever the given {task} involves browsing "
109
+ "the web or a specific website such as Wikipedia or YouTube, you will use "
110
+ "the provided tools. For web-based factual and retrieval tasks, be as precise and source-reliable as possible."
111
+ ),
112
+ additional_authorized_imports=[
113
+ "markdownify",
114
+ "json",
115
+ "requests",
116
+ "urllib.request",
117
+ "urllib.parse",
118
+ "wikipedia-api",
119
+ ],
120
+ verbosity_level=0,
121
+ max_steps=10,
122
+ )
123
+
124
+ # --- Info agent definition ---
125
+ self.info_agent = CodeAgent(
126
+ model=qwen_model,
127
+ tools=[PythonInterpreterTool(), image_process],
128
+ name="info_agent",
129
+ description=(
130
+ "You are an agent tasked with cleaning, parsing, calculating information, and performing OCR if images are provided in the {task}. "
131
+ "You handle all math, code, and data manipulation. Use numpy, math, and available libraries. For image or chess tasks, use pytesseract, PIL, or chess as required."
132
+ ),
133
+ additional_authorized_imports=[
134
+ "numpy",
135
+ "math",
136
+ "pytesseract",
137
+ "PIL",
138
+ "chess",
139
+ ],
140
+ )
141
+
142
+ # --- Manager agent definition ---
143
+ self.manager_agent = CodeAgent(
144
+ model=deepseek_model,
145
+ tools=[FinalAnswerTool()],
146
+ managed_agents=[self.web_agent, self.info_agent],
147
+ name="manager_agent",
148
+ description=(
149
+ "You are the manager. Given a {task}, plan which agent to use: "
150
+ "If web data is needed, delegate to web_agent. If math, parsing, or code is needed, use info_agent. "
151
+ "After collecting outputs, optionally cross-validate and check correctness, then finalize and submit the best answer using FinalAnswerTool. "
152
+ "For each task, explicitly explain your planning steps and reasons for choosing which agent, and always prefer the most accurate and complete answer possible."
153
+ ),
154
+ additional_authorized_imports=[
155
+ "json",
156
+ "pandas",
157
+ "numpy",
158
+ ],
159
+ planning_interval=5,
160
+ verbosity_level=2,
161
+ max_steps=20,
162
+ )
163
+
164
+ def __call__(self, question, **kwargs):
165
+
166
+ return self.manager_agent(question, **kwargs)
167
+
168
+