nadim71 commited on
Commit
73a2eb4
·
verified ·
1 Parent(s): 81917a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +167 -0
app.py CHANGED
@@ -3,6 +3,16 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
 
 
 
 
 
 
 
 
 
 
6
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
@@ -41,6 +51,163 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
41
  # 1. Instantiate Agent ( modify this part to create your agent)
42
  try:
43
  agent = BasicAgent()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  except Exception as e:
45
  print(f"Error instantiating agent: {e}")
46
  return f"Error initializing agent: {e}", None
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ from dotenv import load_dotenv
7
+ from typing import List
8
+ from langchain_community.tools import DuckDuckGoSearchRun
9
+ from langchain_experimental.tools import PythonREPLTool
10
+ from langchain_community.vectorstores import FAISS
11
+ from langchain_core.documents import Document
12
+ from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace, HuggingFaceEmbeddings
13
+ from langchain_core.messages import HumanMessage
14
+
15
+
16
 
17
  # (Keep Constants as is)
18
  # --- Constants ---
 
51
  # 1. Instantiate Agent ( modify this part to create your agent)
52
  try:
53
  agent = BasicAgent()
54
+ load_dotenv()
55
+
56
+ # -----------------------------
57
+ # LLM
58
+ # -----------------------------
59
+ #llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
60
+ #repo_id="deepseek-ai/DeepSeek-V4-Pro"
61
+ llm = ChatHuggingFace(
62
+ llm=HuggingFaceEndpoint(
63
+ repo_id="Qwen/Qwen2.5-Coder-32B-Instruct",
64
+ huggingfacehub_api_token=HF_KEY,
65
+ task="conversational", # Specify task for the conversational model
66
+ )
67
+ )
68
+
69
+ # -----------------------------
70
+ # Tools
71
+ # -----------------------------
72
+ search = DuckDuckGoSearchRun()
73
+ python_tool = PythonREPLTool()
74
+
75
+ TOOLS = {
76
+ "search": search.run,
77
+ "python": python_tool.run,
78
+ "llm": lambda x: llm.invoke([HumanMessage(content=x)]).content,
79
+ "summarize": lambda text: llm.invoke([HumanMessage(content=f"Summarize the following:\n{text}")]).content
80
+ }
81
+
82
+ # -----------------------------
83
+ # Memory (Vector DB)
84
+ # -----------------------------
85
+ embeddings = HuggingFaceEmbeddings()
86
+ # Initialize FAISS with a dummy document to prevent IndexError when trying to determine embedding dimension
87
+ vectorstore = FAISS.from_documents([Document(page_content="initialization_document_for_dimension_inference")], embeddings)
88
+
89
+ def store_memory(text: str):
90
+ vectorstore.add_documents([Document(page_content=text)])
91
+
92
+ def retrieve_memory(query: str):
93
+ docs = vectorstore.similarity_search(query, k=3)
94
+ return "\n".join([d.page_content for d in docs])
95
+
96
+ # -----------------------------
97
+ # Planner
98
+ # -----------------------------
99
+ def plan(goal, history):
100
+ prompt = f"""
101
+ You are an autonomous agent.
102
+
103
+ Goal: {goal}
104
+
105
+ Previous steps:
106
+ {history}
107
+
108
+ Decide the NEXT action:
109
+ - search(query)
110
+ - python(code)
111
+ - llm(prompt)
112
+ - summarize(text)
113
+ - finish(answer)
114
+
115
+ Respond ONLY in one line.
116
+ """
117
+ return llm.invoke([HumanMessage(content=prompt)]).content.strip()
118
+
119
+ # -----------------------------
120
+ # Executor
121
+ # -----------------------------
122
+ def execute(action: str):
123
+ try:
124
+ if action.startswith("search("):
125
+ query = action[len("search("):-1]
126
+ return TOOLS["search"](query)
127
+
128
+ elif action.startswith("python("):
129
+ code = action[len("python("):-1]
130
+ return TOOLS["python"](code)
131
+
132
+ elif action.startswith("llm("):
133
+ prompt = action[len("llm("):-1]
134
+ return TOOLS["llm"](prompt)
135
+
136
+ elif action.startswith("summarize("):
137
+ text_to_summarize = action[len("summarize("):-1]
138
+ return TOOLS["summarize"](text_to_summarize)
139
+
140
+ elif action.startswith("finish("):
141
+ return action[len("finish("):-1]
142
+
143
+ else:
144
+ return "Invalid action"
145
+
146
+ except Exception as e:
147
+ return f"Error: {str(e)}"
148
+
149
+ # -----------------------------
150
+ # Critic (loop control)
151
+ # -----------------------------
152
+ def critic(goal, last_result):
153
+ prompt = f"""
154
+ Goal: {goal}
155
+
156
+ Latest result:
157
+ {last_result}
158
+
159
+ Is the goal achieved? Answer YES or NO.
160
+ """
161
+ return "YES" in llm.invoke([HumanMessage(content=prompt)]).content.upper()
162
+
163
+ # -----------------------------
164
+ # Autonomous Loop
165
+ # -----------------------------
166
+ def autonomous_agent(goal: str, max_steps=15):
167
+
168
+ history = ""
169
+ print(f"\n🎯 Goal: {goal}\n")
170
+
171
+ for step in range(max_steps):
172
+ print(f"--- Step {step+1} ---")
173
+
174
+ # Retrieve memory
175
+ memory_context = retrieve_memory(goal)
176
+
177
+ action = plan(goal, history + "\nMemory:\n" + memory_context)
178
+ print(f"🧠 Plan: {action}")
179
+
180
+ result = execute(action)
181
+ print(f"⚙️ Result: {result[:300]}...\n")
182
+
183
+ # Store memory
184
+ store_memory(f"Action: {action}\nResult: {result}")
185
+
186
+ history += f"\nStep {step+1}: {action} → {result}"
187
+
188
+ # Finish condition
189
+ if action.startswith("finish("):
190
+ print("✅ Finished by agent")
191
+ return result
192
+
193
+ # Critic check
194
+ if critic(goal, result):
195
+ print("✅ Critic determined goal achieved")
196
+ return result
197
+
198
+ return "❌ Max steps reached without completion"
199
+
200
+ # -----------------------------
201
+ # Run
202
+ # -----------------------------
203
+ if __name__ == "__main__":
204
+ while True:
205
+ goal = input("\nEnter goal (or 'exit'): ")
206
+ if goal == "exit":
207
+ break
208
+
209
+ result = autonomous_agent(goal)
210
+ print(f"\n🤖 Final Output:\n{result}\n")
211
  except Exception as e:
212
  print(f"Error instantiating agent: {e}")
213
  return f"Error initializing agent: {e}", None