-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathagent.py
More file actions
140 lines (118 loc) · 4.97 KB
/
agent.py
File metadata and controls
140 lines (118 loc) · 4.97 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
import os
import json
import subprocess
import re
import glob
from openai import OpenAI
client = OpenAI(
api_key=os.environ.get("OPENAI_API_KEY"),
base_url=os.environ.get("OPENAI_BASE_URL")
)
# Skills
def parse_skill(path):
with open(path, "r") as f:
content = f.read()
match = re.match(r"^---\n(.*?)\n---\n(.*)$", content, re.DOTALL)
if not match:
return None
frontmatter, body = match.group(1), match.group(2).strip()
name = re.search(r"name:\s*(.+)", frontmatter)
desc = re.search(r"description:\s*(.+)", frontmatter)
if not name or not desc:
return None
return {"name": name.group(1).strip(), "description": desc.group(1).strip(), "body": body}
def discover_skills(directory):
if not os.path.exists(directory):
return []
skills = []
for path in glob.glob(os.path.join(directory, "**", "SKILL.md"), recursive=True):
skill = parse_skill(path)
if skill:
skills.append(skill)
return skills
def build_activate_tool(skills):
return {
"type": "function",
"function": {
"name": "activate_skill",
"description": "Activate a specialized skill",
"parameters": {
"type": "object",
"properties": {"name": {"type": "string", "enum": [s["name"] for s in skills]}},
"required": ["name"]
}
}
}
def activate_skill(name, skills):
skill = next((s for s in skills if s["name"] == name), None)
if not skill:
return f"Error: Skill '{name}' not found"
return f"<activated_skill name=\"{name}\">\n{skill['body']}\n</activated_skill>"
# Tools
tools = [
{"type": "function", "function": {"name": "execute_bash", "description": "Execute a bash command", "parameters": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}}},
{"type": "function", "function": {"name": "read_file", "description": "Read a file", "parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}},
{"type": "function", "function": {"name": "write_file", "description": "Write to a file", "parameters": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}}}
]
def execute_bash(command):
result = subprocess.run(command, shell=True, capture_output=True, text=True)
return result.stdout + result.stderr
def read_file(path):
with open(path, "r") as f:
return f.read()
def write_file(path, content):
with open(path, "w") as f:
f.write(content)
return f"Wrote to {path}"
functions = {"execute_bash": execute_bash, "read_file": read_file, "write_file": write_file}
def run_agent(user_message, skills_dir="./skills-fake", max_iterations=10):
skills = discover_skills(skills_dir)
agent_tools = tools.copy()
if skills:
agent_tools.append(build_activate_tool(skills))
skill_list = "\n".join([f"- {s['name']}: {s['description']}" for s in skills])
system_prompt = f"You are a helpful assistant. Be concise.\n\nAvailable skills:\n{skill_list}\n\nUse activate_skill when needed." if skills else "You are a helpful assistant. Be concise."
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_message}
]
for _ in range(max_iterations):
response = client.chat.completions.create(
model=os.environ.get("OPENAI_MODEL", "gpt-4o-mini"),
messages=messages,
tools=agent_tools
)
message = response.choices[0].message
messages.append(message)
if not message.tool_calls:
return message.content
for tool_call in message.tool_calls:
name = tool_call.function.name
args = json.loads(tool_call.function.arguments)
if name == "activate_skill":
print(f"[Activating] {args['name']}")
result = activate_skill(args["name"], skills)
elif name in functions:
print(f"[Tool] {name}({args})")
result = functions[name](**args)
else:
result = f"Error: Unknown tool '{name}'"
messages.append({"role": "tool", "tool_call_id": tool_call.id, "content": result})
return "Max iterations reached"
if __name__ == "__main__":
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("task", nargs="*", default=["Hello"])
parser.add_argument("--skills-dir", default=None)
parser.add_argument("--fake", action="store_true", help="Use fake skills (default)")
parser.add_argument("--real", action="store_true", help="Use real skills")
args = parser.parse_args()
if args.skills_dir:
skills_dir = args.skills_dir
elif args.real:
skills_dir = "./skills-real"
else:
skills_dir = "./skills-fake"
task = " ".join(args.task)
print(run_agent(task, skills_dir=skills_dir))