tinycodinglm / agentic /aiagent-0015.jsonl
winapiadmin's picture
Upload folder using huggingface_hub
1f3a244 verified
|
Raw History Blame Contribute Delete
2.46 kB
opencode trace
System You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing c...

You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing code, identify bugs, security issues, and performance problems. You have deep knowledge of C/C++, Windows API, Python, and many other technologies.

User

How should I define tools for an LLM agent securely in Python? Show JSON-schema tool definitions with allowlisting and sandboxed file execution, not raw exec. Include code examples.

Assistant

Define tools as JSON schemas + an allowlisted dispatcher. Never exec() model output.

python
import json
import pathlib

# Allowlist: only these files may be read
ALLOWED_DIR = pathlib.Path("./data").resolve()

def read_file(path: str) -> str:
    p = (ALLOWED_DIR / path).resolve()
    if ALLOWED_DIR not in p.parents and p != ALLOWED_DIR:
        raise ValueError("path escapes allowed dir")
    return p.read_text(encoding="utf-8")

def search_web(query: str) -> str:
    # stub: call your search API here with timeout + validation
    if not query or len(query) > 300:
        raise ValueError("bad query")
    return f"results for: {query}"

TOOLS = {
    "web_search": (  # (name, desc, props, required) for schema builder
        "web_search", "Search the web for information",
        {"query": {"type": "string"}}, ["query"],
    ),
    "read_file": (
        "read_file", "Read a file under ./data",
        {"path": {"type": "string"}}, ["path"],
    ),
}

DISPATCH = {"web_search": lambda a: search_web(a["query"]),
            "read_file": lambda a: read_file(a["path"])}

def execute_tool(name: str, arguments_json: str) -> str:
    if name not in DISPATCH:
        raise KeyError(f"unknown tool: {name}")
    args = json.loads(arguments_json or "{}")
    return str(DISPATCH[name](args))

Best practices:

  1. Clear descriptions so the model picks correctly
  2. Minimal tools - too many confuse routing
  3. Validate args, sandbox I/O, timeouts, no raw exec/eval
  4. Verify tool output before acting on it