SantoshKumar1310 commited on
Commit
6bcd5cb
·
verified ·
1 Parent(s): 3305636

Create agents.py

Browse files
Files changed (1) hide show
  1. agents.py +93 -0
agents.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ """
3
+ Agent implementation with tool calling capabilities
4
+ """
5
+
6
+ class Agent:
7
+ """
8
+ Basic agent that uses an LLM and tools to answer questions.
9
+ """
10
+
11
+ def __init__(self, model, tools):
12
+ self.model = model
13
+ self.tools = {tool.name: tool for tool in tools}
14
+ self.max_iterations = 10
15
+
16
+ def __call__(self, question: str) -> str:
17
+ """
18
+ Run the agent on a question.
19
+ Returns the final answer as a string.
20
+ """
21
+ print(f"\n{'='*60}")
22
+ print(f"QUESTION: {question[:100]}...")
23
+ print(f"{'='*60}")
24
+
25
+ messages = [
26
+ {
27
+ "role": "system",
28
+ "content": """You are a helpful AI assistant that answers questions accurately.
29
+
30
+ When you need information:
31
+ - Use web_search to find current information online
32
+ - Use wikipedia_search for encyclopedic knowledge
33
+ - Use calculate for mathematical operations
34
+
35
+ Always provide a direct, concise answer. If you don't know, search for the information.
36
+ For questions about files, images, or attachments you cannot access, respond with "File not found".
37
+
38
+ Format your final answer clearly and concisely."""
39
+ },
40
+ {
41
+ "role": "user",
42
+ "content": question
43
+ }
44
+ ]
45
+
46
+ for iteration in range(self.max_iterations):
47
+ # Get response from model
48
+ response = self.model.generate(messages, tools=list(self.tools.values()))
49
+
50
+ # Check if model wants to use a tool
51
+ if response.get("tool_calls"):
52
+ print(f"\nIteration {iteration + 1}: Tool calls requested")
53
+
54
+ for tool_call in response["tool_calls"]:
55
+ tool_name = tool_call["name"]
56
+ tool_args = tool_call["arguments"]
57
+
58
+ print(f" → {tool_name}({tool_args})")
59
+
60
+ if tool_name in self.tools:
61
+ try:
62
+ result = self.tools[tool_name](**tool_args)
63
+ print(f" ← Result: {str(result)[:100]}...")
64
+
65
+ # Add tool result to messages
66
+ messages.append({
67
+ "role": "assistant",
68
+ "content": f"Used {tool_name}",
69
+ "tool_calls": [tool_call]
70
+ })
71
+ messages.append({
72
+ "role": "tool",
73
+ "name": tool_name,
74
+ "content": str(result)
75
+ })
76
+ except Exception as e:
77
+ print(f" ← Error: {e}")
78
+ messages.append({
79
+ "role": "tool",
80
+ "name": tool_name,
81
+ "content": f"Error: {str(e)}"
82
+ })
83
+ else:
84
+ print(f" ← Tool not found!")
85
+ else:
86
+ # Model provided final answer
87
+ answer = response.get("content", "Unknown")
88
+ print(f"\n✓ ANSWER: {answer}")
89
+ print(f"{'='*60}\n")
90
+ return answer.strip()
91
+
92
+ print(f"\n⚠ Max iterations reached")
93
+ return "Unknown"