Lesson 18 of 23 · Part 3: Advanced Agents

Terminal Assistant

A fully autonomous agent that can run commands, read, and write files.

Last time: StudyBuddy Pro used a dictionary to map seven tool names to real Python functions.
Today: An assistant that runs real commands and reads and writes files, with two loops working together.
Source Code
1# terminal_assistant.py
2import json
3import subprocess
4from openai import OpenAI
5client = OpenAI()
6
7# --- Tool functions ---
8def run_command(command):
9    try:
10        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
11        output = result.stdout + result.stderr
12        return output if output.strip() else "(command ran successfully with no output)"
13    except Exception as e:
14        return f"Error running command: {e}"
15
16def read_file(path):
17    with open(path, "r") as f:
18        return f.read()
19
20def write_file(path, content):
21    with open(path, "w") as f:
22        f.write(content)
23    return f"Successfully wrote to {path}"
24
25# --- Tools list (the menu for the AI; {...} = parameters shortened) ---
26tools = [
27    {"type": "function", "function": {"name": "run_command", "description": "Run a shell command in the terminal (e.g. ls, pwd, mkdir) and return the output.", "parameters": {...}}},
28    {"type": "function", "function": {"name": "read_file", "description": "Read the contents of a file at the given path.", "parameters": {...}}},
29    {"type": "function", "function": {"name": "write_file", "description": "Write content to a file. Creates or overwrites it.", "parameters": {...}}},
30]
31
32# --- Map function names to actual Python functions ---
33available_functions = {
34    "run_command": run_command,
35    "read_file": read_file,
36    "write_file": write_file,
37}
38
39system_prompt = """You are a friendly terminal assistant.
40You can run shell commands, read files, and write files.
41If a command could be destructive (like rm), confirm with the user first."""
42messages = [{"role": "system", "content": system_prompt}]
43
44# --- Main chat loop ---
45while True:
46    user_input = input("You: ")
47    if user_input.strip().lower() == "exit":
48        print("Goodbye!")
49        break
50    if not user_input.strip():
51        continue
52    messages.append({"role": "user", "content": user_input})
53
54    # --- Agent loop: keep going until the AI gives a final text answer ---
55    while True:
56        response = client.chat.completions.create(
57            model="gpt-4o-mini", messages=messages, tools=tools
58        )
59        message = response.choices[0].message
60        messages.append(message)
61
62        if not message.tool_calls:
63            print(f"Assistant: {message.content}")
64            break
65
66        for tool_call in message.tool_calls:
67            function_name = tool_call.function.name
68            arguments = json.loads(tool_call.function.arguments)
69            print(f"  [Using tool: {function_name}]")
70
71            function_to_call = available_functions[function_name]
72            result = function_to_call(**arguments)
73
74            messages.append({
75                "role": "tool",
76                "tool_call_id": tool_call.id,
77                "content": result,
78            })

No output yet...

← Prev
1/0
Next: Why Teams? →