Refactor Suggestion for agent_run Function in src/agent.c
Current State:
The agent_run function is lengthy and handles multiple responsibilities, including request building, response processing, tool execution, and completion logic.
Proposed Refactor:
Break down agent_run into smaller, focused functions:
- build_request_json: Handles request JSON creation.
- process_response_choice: Handles parsing and processing of the response choice.
- check_incomplete_response: Checks if the response indicates incomplete work.
- execute_tools: Executes tools when called.
- handle_completion: Checks for completion conditions.
Benefits:
- Improved readability and maintainability.
- Easier testing and debugging.
- Clear separation of concerns.
Implementation:
- Extract code segments into dedicated functions.
- Replace inline code in
agent_runwith calls to these functions.
Example:
// Inside agent.c
static struct json_object *build_request_json(agent_handle agent, const char *role, const char *message) {
// Implementation
}
static struct json_object *process_response_choice(agent_handle agent, struct json_object *choice) {
// Implementation
}
// ... other helper functions ...
char *agent_run(agent_handle agent, const char *user_message) {
// Main loop
// Use helper functions for each responsibility
}
Conclusion:
This refactor will make the agent_run function more modular, easier to understand, and maintainable.
Further detailed code snippets and refactoring steps are documented here for implementation.