The `agent_run()` function is highly complex, handling multiple responsibilities such as response parsing, tool execution, context management, and response accumulation. Its length and nested logic make it difficult to read, maintain, and test.
The implementation involves extracting code blocks from `agent_run()` into these functions, passing necessary context as parameters, and replacing the original code with calls to these functions.
This modularization will significantly enhance the code quality and facilitate future extensions or modifications.