nadim71 commited on
Commit
23c1892
·
verified ·
1 Parent(s): d4f728a

Update app.py

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