How to Build an Advanced Agentic AI System with Planning, Tool Calling, Memory, and Self-Critique Using OpenAI API
“calc”: lambda expression: _safe_calc(expression),
“kb_search”: lambda query, k=3: _kb_search(query, int(k)),
“extract_json”: lambda text: _extract_json(text),
“write_file”: lambda path, content: _write_file(path, content),
}
TOOL_SCHEMAS = [
{“type”: “function”,”function”:{“name”:”calc”,”description”:”Safely compute a numeric expression.”,”parameters”:{“type”:”object”,”properties”:{“expression”:{“type”:”string”}},”required”:[“expression”]}}},
{“type”: “function”,”function”:{“name”:”kb_search”,”description”:”Search internal mini knowledge base.”,”parameters”:{“type”:”object”,”properties”:{“query”:{“type”:”string”},”k”:{“type”:”integer”,”default”:3}},”required”:[“query”]}}},
{“type”: “function”,”function”:{“name”:”extract_json”,”description”:”Extract and parse first JSON object from text.”,”parameters”:{“type”:”object”,”properties”:{“text”:{“type”:”string”}},”required”:[“text”]}}},
{“type”: “function”,”function”:{“name”:”write_file”,”description”:”Write content to a file path.”,”parameters”:{“type”:”object”,”properties”:{“path”:{“type”:”string”},”content”:{“type”:”string”}},”required”:[“path”,”content”]}}},
]
@dataclass
class AgentState:
goal: str
memory: List[str] = field(default_factory=list)
trace: List[Dict[str, Any]] = field(default_factory=list)
def chat(messages, tools=None, tool_choice=”auto”, temperature=0.2):
kwargs = dict(
model=MODEL,
messages=messages,
temperature=temperature,
)
if tools is not None:
kwargs[“tools”] = tools
kwargs[“tool_choice”] = tool_choice
return client.chat.completions.create(**kwargs)
def run_tool(name, args):
fn = TOOLS.get(name)
if not fn: return {“ok”: False, “error”: f”Unknown tool: {name}”}
try:
return fn(**args)
except Exception as e:
return {“ok”: False, “error”: str(e), “args”: args}
