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:
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.