How to Build an Advanced Agentic AI System with Planning, Tool Calling, Memory, and Self-Critique Using OpenAI API


TOOLS = {
   "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}



Source link

  • Related Posts

    Meet MemPrivacy: An Edge-Cloud Framework that Uses Local Reversible Pseudonymization to Protect User Data Without Breaking Memory Utility

    As LLM-powered agents move from research to production, one design tension is becoming harder to ignore: the more useful cloud-hosted memory becomes, the more private user data it exposes. Researchers…

    Stochastic Gradient Descent (SGD’s) Frequency Bias and How Adam Fixes It 

    BG = “#fafaf8” DARK = “#1a1a1a” # Color ramp: blue for common tokens, red for rare TOKEN_COLORS = [“#1a5276”, “#2471a3”, “#5dade2”, “#e67e22”, “#c0392b”, “#7d2a2a”] steps = np.arange(N_STEPS) fig = plt.figure(figsize=(16,…

    Leave a Reply

    Your email address will not be published. Required fields are marked *