pythonadvanced

Manual OpenAI Agent Loop in Python

Implement a bare-metal AI agent loop with tool execution and conversation management without frameworks.

python
from openai import OpenAI
import json
from typing import Callable

client = OpenAI()

def calculator(expression: str) -> str:
    try:
        return str(eval(expression, {'__builtins__': {}}))
    except Exception as e:
        return f'Error: {e}'

TOOLS = [{'type':'function','function':{'name':'calculator','description':'Evaluate math expression','parameters':{'type':'object','properties':{'expression':{'type':'string'}},'required':['expression']}}}]
TOOL_FNS: dict[str, Callable] = {'calculator': calculator}

def run_agent(user_message: str, max_steps: int = 5) -> str:
    messages = [{'role': 'user', 'content': user_message}]
    for _ in range(max_steps):
        resp  = client.chat.completions.create(model='gpt-4o-mini', messages=messages, tools=TOOLS, tool_choice='auto')
        msg   = resp.choices[0].message
        messages.append(msg)
        if not msg.tool_calls:
            return msg.content
        for tc in msg.tool_calls:
            args   = json.loads(tc.function.arguments)
            result = TOOL_FNS[tc.function.name](**args)
            messages.append({'role': 'tool', 'tool_call_id': tc.id, 'content': result})
    return 'Max steps reached'

print(run_agent('What is 1337 * 42 + 7?'))

Use Cases

  • custom agents
  • bare-metal LLM loops
  • learning AI internals

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.