How can I execute all generated code even when final_answer is called in the middle?

Hi everyone,

I’m using smolagents with a QWEN 32B model (via CodeAgent) and have run into an issue with the generated code. Sometimes, the code produced by the agent includes multiple calls to final_answer, with one appearing in the middle of the script. Because final_answer is designed to signal the end of execution, any code following its first occurrence (for example, calls like task_to_do()) doesn’t get executed.

What I’ve tried:

  • I’ve attempted to “teach” the model to avoid placing final_answer in the middle of the code, but this approach has been unreliable.

My goal is:

  • To have an execution model or workaround in smolagents that ensures the complete code block executes, even if a premature final_answer is generated.

Question:
Is there an agent configuration, workaround, or best practice within smolagents that can allow all code to execute even if final_answer is called early? Any guidance or suggestions would be greatly appreciated.

Thanks in advance!

It seems that there are people who are having trouble with this, but there doesn’t seem to be a solution on the library side yet. You might want to raise an issue on github.:thinking: