# 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:
1. **build_request_json**: Handles request JSON creation.
2. **process_response_choice**: Handles parsing and processing of the response choice.
3. **check_incomplete_response**: Checks if the response indicates incomplete work.
4. **execute_tools**: Executes tools when called.
5. **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_run` with calls to these functions.
## Example:
```c
// 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.