{"record":{"id":"ce48e343eb71e0c5","repo":"huggingface/smolagents","slug":"could-not-index-value-with-index-type-e","errorCode":null,"errorMessage":"Could not index {value} with '{index}': {type(e).__name__}: {e}","messagePattern":"Could not index (.+?) with '(.+?)': (.+?): (.+?)","errorType":"exception","errorClass":"InterpreterError","httpStatus":null,"severity":"error","filePath":"src/smolagents/local_python_executor.py","lineNumber":938,"sourceCode":"\ndef evaluate_subscript(\n    subscript: ast.Subscript,\n    state: dict[str, Any],\n    static_tools: dict[str, Callable],\n    custom_tools: dict[str, Callable],\n    authorized_imports: list[str],\n) -> Any:\n    index = evaluate_ast(subscript.slice, state, static_tools, custom_tools, authorized_imports)\n    value = evaluate_ast(subscript.value, state, static_tools, custom_tools, authorized_imports)\n    try:\n        return value[index]\n    except (KeyError, IndexError, TypeError) as e:\n        error_message = f\"Could not index {value} with '{index}': {type(e).__name__}: {e}\"\n        if isinstance(index, str) and isinstance(value, Mapping):\n            close_matches = difflib.get_close_matches(index, list(value.keys()))\n            if len(close_matches) > 0:\n                error_message += f\". Maybe you meant one of these indexes instead: {str(close_matches)}\"\n        raise InterpreterError(error_message) from e\n\n\ndef evaluate_name(\n    name: ast.Name,\n    state: dict[str, Any],\n    static_tools: dict[str, Callable],\n    custom_tools: dict[str, Callable],\n    authorized_imports: list[str],\n) -> Any:\n    if name.id in state:\n        return state[name.id]\n    elif name.id in static_tools:\n        return safer_func(static_tools[name.id], static_tools=static_tools, authorized_imports=authorized_imports)\n    elif name.id in custom_tools:\n        return custom_tools[name.id]\n    elif name.id in ERRORS:\n        return ERRORS[name.id]\n    close_matches = difflib.get_close_matches(name.id, list(state.keys()))","sourceCodeStart":920,"sourceCodeEnd":956,"githubUrl":"https://github.com/huggingface/smolagents/blob/30bb1161095dbae2271e6bc3cc4c219cc3897a57/src/smolagents/local_python_executor.py#L920-L956","documentation":"A subscript operation x[index] raised KeyError, IndexError, or TypeError inside the sandboxed interpreter; the message wraps the original exception and, for string keys on Mapping values, suggests close-match key names via difflib.","triggerScenarios":"dict['missing_key'], list[10] on a short list, indexing an int/None, or mixing types (e.g. d[0] on a dict with string keys).","commonSituations":"Agent code assumes keys exist (df['cloumn'] typo — the close-match hint fires); index computed from len arithmetic that is off by one; the value is None because a previous step failed.","solutions":["Read the appended 'Maybe you meant' suggestion and fix the key name","Guard with key in d / try-except KeyError / .get(key, default)","Check the container is not None and the index is within range before subscripting"],"exampleFix":"# before\nval = record['nam']\n# after\nval = record.get('name', None)\nif val is None:\n    raise KeyError('name missing')","handlingStrategy":"try-catch","validationCode":"if key not in mapping:\n    raise KeyError(f'{key!r} missing; available: {sorted(mapping)}')\nval = mapping[key]","typeGuard":"def can_index(obj, idx) -> bool:\n    if isinstance(obj, dict):\n        return idx in obj\n    if isinstance(obj, (list, tuple, str)):\n        return isinstance(idx, int) and -len(obj) <= idx < len(obj)\n    return False","tryCatchPattern":"try:\n    evaluate_python(code, ...)\nexcept InterpreterError as e:\n    if 'Could not index' in str(e):\n        # parse suggested close matches, fix key, retry","preventionTips":["Use .get() for optional dict keys","Check bounds before indexing lists","Watch for the 'Maybe you meant' hint on typos"],"tags":["python-executor","subscript","key-error","index-error","smolagents"],"backgroundTag":"container-subscript-out-of-range-or-key","analyzedSha":"30bb1161095dbae2271e6bc3cc4c219cc3897a57","analyzedAt":"2026-08-28T18:52:54.169Z","schemaVersion":2},"datasetVersion":"2026-08-28T21:17:43.275Z"}