# Code execution failed at line -- CodeAgents

**URL:** <https://discuss.huggingface.co/t/code-execution-failed-at-line-codeagents/155504>\
**Category:** Beginners\
**Created:** [May 16, 2025, 8:44am UTC](https://discuss.huggingface.co/t/code-execution-failed-at-line-codeagents/155504 "2025-05-16T08:44:43Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![ggeo](https://avatars.discourse-cdn.com/v4/letter/g/a88e4f/32.png) [@ggeo](https://discuss.huggingface.co/u/ggeo)\
**Post date:** [May 16, 2025, 8:44am UTC](https://discuss.huggingface.co/t/code-execution-failed-at-line-codeagents/155504/1 "2025-05-16T08:44:43Z")

</div>

Hello, I am trying to train a forecast model with a CodeAgent but it fails.

It shows `Code execution failed at line 'system` due to : InterpreterError: The variable ‘system’ is not defined`

or other times is shows `s` instead of `system`.

The code:

```auto
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import json
import os
import re
import traceback
from datetime import datetime, timedelta
from prophet import Prophet
from smolagents import CodeAgent, TransformersModel, LogLevel, tool
from transformers import AutoTokenizer

# Create output directories
os.makedirs('forecast_outputs', exist_ok=True)
os.makedirs('forecast_plots', exist_ok=True)

# Initialize the Qwen model (same as in your original code)
def setup_qwen_model():
    """Initialize the Qwen model for agents"""
    try:
        model_id = "cmarkea/Qwen2.5-Coder-7B-Instruct-4bit"
        tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
        
        # Fix the pad token issue
        if tokenizer.pad_token_id is None:
            tokenizer.pad_token_id = tokenizer.eos_token_id
        
        model = TransformersModel(
            model_id=model_id,
            device_map="auto",
            torch_dtype="auto", 
            max_new_tokens=512,
            temperature=0.2,
            trust_remote_code=True,
            tokenizer=tokenizer,
            pad_token_id=tokenizer.pad_token_id,
            eos_token_id=tokenizer.eos_token_id
        )
        
        return model
    
    except Exception as e:
        print(f"Error loading model: {str(e)}")
        print(traceback.format_exc())
        raise e

# Create a sample weather dataframe
def create_sample_weather_data():
    # Generate 30 days of hourly data
    start_date = datetime(2025, 4, 15)
    periods = 30 * 24 # 30 days of hourly data
    
    dates = [start_date + timedelta(hours=i) for i in range(periods)]
    
    # Generate synthetic temperature data with daily pattern and some trend
    temps = []
    for i in range(periods):
        hour = i % 24
        day = i // 24
        # Base temperature with seasonal and hourly variation
        base_temp = 20 + 5 * np.sin(np.pi * day / 15) 
        hourly_variation = 5 * np.sin(np.pi * hour / 12)
        random_factor = np.random.normal(0, 1)
        temps.append(base_temp + hourly_variation + random_factor)
    
    # Create DataFrame
    df = pd.DataFrame({
        'DateTime': dates,
        'Temperature': temps,
        'Humidity': [40 + 20 * np.sin(np.pi * i / 24) + np.random.normal(0, 5) for i in range(periods)],
        'Pressure': [1013 + 5 * np.sin(np.pi * i / 48) + np.random.normal(0, 1) for i in range(periods)]
    })
    
    # Save to CSV
    csv_path = 'forecast_outputs/sample_weather_data.csv'
    df.to_csv(csv_path, index=False)
    return csv_path

# Define required tools for the agent
@tool
def create_forecast_model(csv_path: str, date_column: str, target_column: str, periods: int = 30) -> str:
    """
    Create a Prophet forecast model and generate predictions.
    
    Args:
        csv_path: Path to the CSV file
        date_column: Name of the date column
        target_column: Name of the target column to forecast
        periods: Number of periods to forecast
        
    Returns:
        JSON string with forecast results
    """
    try:
        print(f"Creating forecast for {csv_path}, date: {date_column}, target: {target_column}")
        df = pd.read_csv(csv_path)
        
        # Prepare data for Prophet
        prophet_df = pd.DataFrame({
            'ds': pd.to_datetime(df[date_column]),
            'y': df[target_column]
        })
        
        # Remove any rows with missing values
        prophet_df = prophet_df.dropna()
        
        # Create and fit the model
        model = Prophet()
        model.fit(prophet_df)
        
        # Make future dataframe
        future = model.make_future_dataframe(periods=periods)
        
        # Generate forecast
        forecast = model.predict(future)
        
        # Save results
        forecast_path = 'forecast_outputs/forecast_results.csv'
        forecast.to_csv(forecast_path, index=False)
        
        # Generate plot
        plt.figure(figsize=(12, 6))
        model.plot(forecast)
        plt.title(f'Prophet Forecast of {target_column}')
        plt.tight_layout()
        plot_path = 'forecast_plots/forecast_plot.png'
        plt.savefig(plot_path)
        plt.close()
        
        # Return summary
        results = {
            "success": True,
            "periods_forecasted": periods,
            "forecast_path": forecast_path,
            "plot_path": plot_path,
            "original_data_points": len(prophet_df)
        }
        
        return json.dumps(results, indent=2)
    
    except Exception as e:
        import traceback
        error_msg = f"Error creating forecast: {str(e)}"
        print(error_msg)
        print(f"Traceback: {traceback.format_exc()}")
        return json.dumps({"error": error_msg})

# Create a forecasting agent with Qwen model
def create_forecasting_agent(model):
    agent = CodeAgent(
        model=model,
        tools=[create_forecast_model],
        additional_authorized_imports=["pandas", "numpy", "prophet", "matplotlib"],
        max_steps=3,
        verbosity_level=LogLevel.INFO,
        planning_interval=2
    )
    
    return agent

# Main function
def main():
    print("Setting up Weather Forecasting Agent Example with Qwen Model")
    
    # Create sample data
    csv_path = create_sample_weather_data()
    
    model = setup_qwen_model()
    
    # Create agent with the loaded model
    agent = create_forecasting_agent(model)
    print("Created forecasting agent with Qwen model")
    
    prompt = f"""
        You are a weather forecasting assistant. I need you to:
        
        1. Create a 7-day forecast for Temperature using the weather data in {csv_path}
        2. Use the create_forecast_model tool to generate the forecast
        3. Set the date_column to 'DateTime', the target_column to 'Temperature', and periods to 7
        
        Return the results of the forecast, including any statistics and where the output files are saved.
        """
    
    result = agent.run(prompt)
    
    print(result)
    
    # Try to parse any JSON in the result
    try:
        # Look for JSON content in the result
        json_pattern = r'\{.*\}'
        json_match = re.search(json_pattern, result, re.DOTALL)
        
        if json_match:
            forecast_result = json.loads(json_match.group())
            
            if 'success' in forecast_result and forecast_result['success']:
                print("\nForecast created successfully!")
                print(f"Forecast saved to: {forecast_result['forecast_path']}")
                print(f"Plot saved to: {forecast_result['plot_path']}")
                
                # Load and display some statistics from the forecast
                forecast_df = pd.read_csv(forecast_result['forecast_path'])
                print("\nForecast Statistics:")
                print(f"Total periods: {len(forecast_df)}")
                print(f"Forecast start: {forecast_df['ds'].min()}")
                print(f"Forecast end: {forecast_df['ds'].max()}")
                print(f"Average predicted value: {forecast_df['yhat'].mean():.2f}")
                print(f"Minimum predicted value: {forecast_df['yhat'].min():.2f}")
                print(f"Maximum predicted value: {forecast_df['yhat'].max():.2f}")
    except Exception as e:
        print(f"Error extracting forecast details: {str(e)}")
        print("Please check the agent's output for forecast information")

if __name__ == " __main__":
    main()

```

generally, i can see this error (code execution failed at line) at other cases I have created but sometimes it shwos that sometimes not and sometimes the whole execution goes well even though this error exists.

But now, it doesn’t proceed.

I am attaching some screenshots.

 ![Screenshot from 2025-05-16 11-36-59](https://us1.discourse-cdn.com/hellohellohello/original/3X/4/9/491c10a8cd35cca213e985838420fedf02812ccb.png)  
 ![Screenshot from 2025-05-16 11-37-12](https://us1.discourse-cdn.com/hellohellohello/original/3X/6/c/6c55c54a8068ec983cc918268e518783089704e0.png)  
 ![Screenshot from 2025-05-16 11-37-40](https://us1.discourse-cdn.com/hellohellohello/original/3X/5/c/5ce70480ef362918a54b37ef790108a0a0e6465d.png)  
 ![Screenshot from 2025-05-16 11-40-23](https://us1.discourse-cdn.com/hellohellohello/original/3X/9/c/9c819e1f146f3650f55fd66c8669cba2545c3200.png)

---

<div class="post-metadata">

**Author:** ![John6666](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/john6666/32/27664_2.png) [@John6666](https://discuss.huggingface.co/u/John6666)\
**Post date:** [May 16, 2025, 9:32am UTC](https://discuss.huggingface.co/t/code-execution-failed-at-line-codeagents/155504/2 "2025-05-16T09:32:43Z")

</div>

Perhaps this issue?

> <https://github.com/huggingface/smolagents/issues/640#issuecomment-2677327064>
>
> Hey,
> 
> I'm getting this error all the time:
> \*\*InterpreterError:It is not permitte…d to evaluate other functions than the provided tools or functions 
> defined/imported in previous code\*\*
> 
> In manager.run I'm trying to pass additional\_args=dict(source\_file="file.csv").
> 
> Example of agent:
> \`\`\`
> agent\_core = CodeAgent(
> model = model,
> tools = \[tool\_1, tool\_2\],
> additional\_authorized\_imports=\["pandas", "matplotlib", "seaborn"\],
> name="Data Analyst",
> description="""Analysis agent with a set of ready-to-use tools that parse, cleanse, and process the data provided."""
> )
> 
> \`\`\`
> 
> \`\`\`
> manager\_agent = CodeAgent(
> model=model,
> tools=\[\],
> managed\_agents=\[agent\_core\],
> additional\_authorized\_imports=\["pandas", "matplotlib", "seaborn"\],
> )
> 
> \`\`\`
> 
> It works normally when I try to call agent\_core.run directly, without manager\_agent. 
> 
> 
> Does anyone have a similar problem?

---

<div class="post-metadata">

**Author:** ![ggeo](https://avatars.discourse-cdn.com/v4/letter/g/a88e4f/32.png) [@ggeo](https://discuss.huggingface.co/u/ggeo)\
**Post date:** [May 16, 2025, 10:10am UTC](https://discuss.huggingface.co/t/code-execution-failed-at-line-codeagents/155504/3 "2025-05-16T10:10:28Z")

</div>

Unfortunately it doesn’t work..

Also, sometimes when i run it it gives:

````auto
Error in code parsing:
Your code snippet is invalid, because the regex pattern ```(?:py|python)?\s*\n(.*?)\n``` was not found in it.
            Here is your code snippet:

````

```auto
def create_forecasting_agent(model):
    forecast_agent = CodeAgent(
        name='forecast_agent',
        model=model,
        tools=[create_forecast_model],
        additional_authorized_imports=["pandas", "numpy", "prophet", "matplotlib"],
        max_steps=3,
        verbosity_level=LogLevel.INFO,
        planning_interval=1
    )
    
    return forecast_agent

```

 ![Screenshot from 2025-05-16 13-04-31](https://us1.discourse-cdn.com/hellohellohello/original/3X/c/6/c6e65f3f9d928dd3b1ab64145905105e23b83ddc.png)

---

<div class="post-metadata">

**Author:** ![John6666](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/john6666/32/27664_2.png) [@John6666](https://discuss.huggingface.co/u/John6666)\
**Post date:** [May 16, 2025, 11:16am UTC](https://discuss.huggingface.co/t/code-execution-failed-at-line-codeagents/155504/4 "2025-05-16T11:16:25Z")

</div>

Hmm… It seems to be happening frequently.

> <https://github.com/huggingface/smolagents/issues/201>
>
> I repeatedly get this error when using the Codeagent:
> 
> \`\`\`Error in code parsing:…
> The code blob is invalid, because the regex pattern \`\`\`(?:py|python)?\\n(.\*?)\\n\`\`\` was not found in code\_blob ...
> \`\`\`
> 
> I have tried to emphasize proper code block formatting in the agent.run() argument, to no avail.
> 
> The error occurs while using GPT-4o and Sonnet 3.5. 
> 
> How can I fix this or at least improve realiability?
> 
> Thanks for any help in this regard!
