-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlocal_agent.py
More file actions
336 lines (262 loc) · 9.17 KB
/
local_agent.py
File metadata and controls
336 lines (262 loc) · 9.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
from typing import TypedDict, List
import csv
import os
import chromadb
from chromadb.config import Settings
from PIL import Image
from sentence_transformers import SentenceTransformer
import uuid
from langchain_ollama import ChatOllama
from langchain.tools import tool
from langchain_core.messages import (
BaseMessage,
HumanMessage,
SystemMessage,
)
from langgraph.graph import StateGraph, END
from langgraph.prebuilt import ToolNode
# =========================
# Agent State
# =========================
class AgentState(TypedDict):
messages: List[BaseMessage]
# =========================
# Dataset
# =========================
def load_courses(path: str = "courses.csv"):
with open(path, newline="", encoding="utf-8") as f:
return list(csv.DictReader(f))
COURSES = load_courses()
# =========================
# Tools
# =========================
@tool
def search_courses(query: str) -> str:
"""Search the course dataset for relevant entries."""
query_tokens = query.lower().split()
scored = []
for course in COURSES:
text = " ".join(course.values()).lower()
score = sum(token in text for token in query_tokens)
if score > 0:
scored.append((score, course))
if not scored:
return "No relevant courses found in the dataset."
scored.sort(key=lambda x: x[0], reverse=True)
return "\n".join(
f"{c['code']}: {c['title']} ({c['level']}) - {c['description']}"
for _, c in scored
)
@tool
def calc(expression: str) -> str:
"""Evaluate a simple arithmetic expression."""
allowed = set("0123456789+-*/(). %")
if any(ch not in allowed for ch in expression):
return "Error: invalid characters"
try:
return str(eval(expression, {"__builtins__": {}}, {}))
except Exception as e:
return f"Error: {e}"
@tool
def write_text(path: str, content: str) -> str:
"""Write text content to a local file."""
try:
with open(path, "w", encoding="utf-8") as f:
f.write(content)
return f"Saved {len(content)} characters to {path}"
except Exception as e:
return f"Error: {e}"
# =========================
# Image Indexing (CLIP + ChromaDB)
# =========================
class ImageIndex:
def __init__(self, image_dir: str = "images"):
self.image_dir = image_dir
# Initialize ChromaDB (persistent)
self.client = chromadb.PersistentClient(path="./chroma_db")
self.collection = self.client.get_or_create_collection(
name="local_images",
metadata={"hnsw:space": "cosine"}
)
# Load CLIP model
print("Loading CLIP model...")
self.model = SentenceTransformer('clip-ViT-B-32')
self._index_images()
def _index_images(self):
if not os.path.exists(self.image_dir):
os.makedirs(self.image_dir)
# Get list of images on disk
valid_exts = {".jpg", ".jpeg", ".png", ".webp"}
image_files = [
f for f in os.listdir(self.image_dir)
if os.path.splitext(f)[1].lower() in valid_exts
]
if not image_files:
print(f"No images found in {self.image_dir}")
return
# Check what's already indexed to avoid re-embedding
existing_ids = set(self.collection.get()["ids"])
new_images = []
new_ids = []
new_metadatas = []
print("Checking for new images to index...")
for f in image_files:
file_id = f"img_{f}" # Simple ID scheme
if file_id not in existing_ids:
try:
# Open and validate image
img_path = os.path.join(self.image_dir, f)
image = Image.open(img_path)
new_images.append(image)
new_ids.append(file_id)
new_metadatas.append({"filename": f})
except Exception as e:
print(f"Skipping {f}: {e}")
if new_images:
print(f"Embedding and indexing {len(new_images)} new images...")
embeddings = self.model.encode(new_images, normalize_embeddings=True)
self.collection.add(
embeddings=embeddings.tolist(),
ids=new_ids,
metadatas=new_metadatas
)
print("Indexing complete.")
else:
print("Index is up to date.")
def search(self, query: str, k: int = 3):
# Embed query
query_emb = self.model.encode([query], normalize_embeddings=True)
# Query Chroma
results = self.collection.query(
query_embeddings=query_emb,
n_results=k
)
# Parse results
parsed = []
if results and results['metadatas']:
metas = results['metadatas'][0]
dists = results['distances'][0] # Chroma returns distances by default
for i, meta in enumerate(metas):
parsed.append((meta['filename'], dists[i]))
return parsed
# Initialize global index
image_index = ImageIndex()
@tool
def search_images(query: str) -> str:
"""Search for images/memes/photos locally using a description."""
results = image_index.search(query)
if not results:
return "No relevant images found."
return "\n".join(
f"Top K = 3 Images Found: {filename} (distance: {dist:.2f})"
for filename, dist in results
)
TOOLS = [search_courses, calc, write_text, search_images]
# =========================
# LLM
# =========================
llm = ChatOllama(
model="qwen3:0.6b-q4_K_M",
temperature=0,
).bind_tools(TOOLS)
# =========================
# System Prompt
# =========================
SYSTEM_PROMPT = SystemMessage(
content=(
"You are a careful assistant with access to tools.\n\n"
"Guidelines:\n"
"- Use calc for ANY arithmetic, even if it seems simple.\n"
"- Use write_text when the user asks to write text content to a local file.\n"
"- Use search_courses when the user asks about courses, degrees, or programs.\n"
"- When search_courses returns results, summarize or filter them to answer the user's question.\n"
"- Do NOT ask follow-up questions unless the request is ambiguous.\n"
"- If you answer without tools and the answer could be wrong, that is a failure.\n"
"- Prefer tools when accuracy matters."
)
)
# =========================
# Graph Nodes
# =========================
def agent_node(state: AgentState):
messages = state["messages"]
# Find the last human message (original question)
last_user_msg = None
for m in reversed(messages):
if isinstance(m, HumanMessage):
last_user_msg = m.content
break
if messages and messages[-1].type == "tool":
# Tool just ran → force final answer grounded in results
messages = messages + [
SystemMessage(
content=(
"You have received tool results.\n"
f"The original user question was:\n"
f"\"{last_user_msg}\"\n\n"
"Answer that question directly using the tool results.\n"
"Do NOT ask clarifying questions.\n"
"Do NOT call any more tools."
)
)
]
else:
messages = messages + [
SystemMessage(
content="Before answering, decide whether a tool would improve accuracy."
)
]
response = llm.invoke(messages)
return {"messages": state["messages"] + [response]}
tool_node = ToolNode(TOOLS)
def route_after_agent(state: AgentState):
last = state["messages"][-1]
if hasattr(last, "tool_calls") and last.tool_calls:
return "tools"
return END
def print_tool_usage(messages):
used_any = False
for m in messages:
if hasattr(m, "tool_calls") and m.tool_calls:
used_any = True
for call in m.tool_calls:
print(f"[TOOL CALL] {call['name']}({call['args']})")
if m.type == "tool":
print(f"[TOOL RESULT] {m.content}")
if not used_any:
print("[TOOLS] No tools were used.")
# =========================
# Build LangGraph
# =========================
graph = StateGraph(AgentState)
graph.add_node("agent", agent_node)
graph.add_node("tools", tool_node)
graph.set_entry_point("agent")
graph.add_conditional_edges(
"agent",
route_after_agent,
{
"tools": "tools",
END: END,
},
)
graph.add_edge("tools", "agent")
app = graph.compile()
# =========================
# Run loop
# =========================
if __name__ == "__main__":
print("\nMinimal LangGraph Agent ready. Type 'exit' to quit.")
while True:
user = input("\nYou: ").strip()
if user.lower() in {"exit", "quit"}:
break
result = app.invoke(
{
"messages": [
SYSTEM_PROMPT,
HumanMessage(content=user),
]
}
)
print(f"\nAgent: {result['messages'][-1].content}")