It seems that openhands (v0.59.0) CLI has this iss...
# questions
i
It seems that openhands (v0.59.0) CLI has this issue almost every session:
Copy code
12:56:12 - openhands:ERROR: agent_controller.py:373 - [Agent Controller b6fb72d1-bb47-48-cfa80424caf0bb9] Error while running the agent (session ID: b6fb72d1-bb47-48-cfa80424caf0bb9): litellm.BadRequestError: OpenAIException - litellm.BadRequestError: OpenAIException - max_tokens must be at least 1, got -221.. Received Model Group=mistralai/Mistral-Small-24B-Instruct-2501
Available Model Group Fallbacks=None
Can you please help me to debug this issue?
l
@nutritious-balloon-65098 It seems that the OpenHands CLI 0.59.0 is having issues when using the language model
mistralai/Mistral-Small-24B-Instruct-2501
. Explore the
All-Hands-AI/{agent-sdk,openhands}
codebases and better understand what might be causing the issue. I will provide you with a mistral API key so you can experiment.
n
I'm on it! Graham Neubig can track my progress here.
i
Thank you @limited-student-10747, I am using the local LLM that my company provides. Maybe, the error comes from some missing features of the local LLM?
l
Ah yes that could be it. BTW: if it’s a local llm, you might need to use the
openai/…
prefix instead of the
mistralai/...
prefix: https://docs.litellm.ai/docs/providers/openai_compatible
I also might suggest using
qwen3-coder-30b
instead of mistral small if you want a model that is approximately the same size but gets very good performance
n
Summary: Investigation of Mistral Model max_tokens Error I've completed an investigation of the
max_tokens must be at least 1, got -221
error you're experiencing with OpenHands CLI 0.59.0. Here are my findings: Root Cause Identified The model name
mistralai/Mistral-Small-24B-Instruct-2501
does not exist
- it's not a valid Mistral API model name. How the Error Occurs 1. When you specify an unrecognized model name, litellm cannot find it in its model registry 2. Without model registry information, the agent-sdk LLM class cannot determine proper context window sizes 3.
max_output_tokens
remains
None
or defaults to an incorrect value 4. During API calls, a calculation somewhere produces a negative max_tokens value (-221) 5. The Mistral API rejects this with the exact error you're seeing Testing Confirmed I tested with litellm directly and confirmed: •
mistralai/Mistral-Small-24B-Instruct-2501
→ "Invalid model" error from Mistral API •
mistral/mistral-small-latest
→ Works correctly with proper context windows • Sending negative
max_tokens
→ Produces the exact error message you reported Valid Mistral Model Names According to Mistral's documentation, valid small models include: •
mistral-small-2501
(Mistral Small 3, January 2025 release) •
mistral-small-2503
(Mistral Small 3.1, March 2025) •
mistral-small-2506
(Mistral Small 3.2, June 2025) •
mistral-small-latest
(currently points to
mistral-small-2506
) Note: There is no Mistral model with "24B" in its name. The "24" in model names refers to the year (2024), not the model size. Recommended Solution Change your model configuration to use a valid Mistral model name, such as: •
mistral-small-latest
(recommended - always points to the latest version) •
mistral-small-2501
(if you need the specific January 2025 version) Next Steps I did not implement any code fixes because: 1. The immediate solution is to use a valid model name 2. I would need the Mistral API key to test any potential defensive code changes 3. The core issue is configuration, not a bug in the OpenHands codebase If you'd like me to implement defensive improvements to the agent-sdk (such as better error messages for unrecognized models, or fallback context window values), please provide the Mistral API key and I can proceed with testing and implementing those changes. <sub>View full conversation</sub>
i
I think that I already used the prefix
openai/
in front of the model name
mistralai/Mistral-Small-24B-Instruct-2501
. This is the corresponding line of the
~/.openhands/settings.json
:
Copy code
"llm_model": "openai/mistralai/Mistral-Small-24B-Instruct-2501",
l
@nutritious-balloon-65098: see the above messages. this is on a self-hosted endpoint. I think that this “max_tokens” setting can be overridden with an environment variable or setting in
~/.openhands/settings.json
, can you give directions about how to do that?
n
I'm on it! Graham Neubig can continue tracking my progress here.
Summary: How to Fix the
max_tokens
Error for Self-Hosted Mistral Models
I've investigated the
max_tokens must be at least 1, got -221
error you're experiencing with OpenHands CLI 0.59.0 when using
mistralai/Mistral-Small-24B-Instruct-2501
on a self-hosted endpoint. Root Cause The error occurs because your custom model name (
mistralai/Mistral-Small-24B-Instruct-2501
) is not in litellm's model registry. When OpenHands encounters an unknown model: 1. It cannot determine the model's context window size 2. This results in
max_output_tokens
being
None
3. Token calculations fail, eventually producing a negative
max_tokens
value (-221) 4. The API rejects the request Solution: Override max_output_tokens You can fix this by explicitly setting
max_output_tokens
(and optionally
max_input_tokens
) using one of these methods: Option 1: Environment Variables (Recommended) Set these environment variables before running OpenHands:
Copy code
export LLM_MAX_OUTPUT_TOKENS=8192
export LLM_MAX_INPUT_TOKENS=32768
Then run your OpenHands CLI as usual. Option 2: Settings File (
~/.openhands/settings.json
)
This file doesn't directly support
max_output_tokens
, so use Option 1 or 3 instead. Option 3: Config File (
config.toml
)
Create or edit a
config.toml
file:
Copy code
[llm]
model = "mistralai/Mistral-Small-24B-Instruct-2501"
base_url = "https://your-self-hosted-endpoint.com/v1"
api_key = "your-api-key"
max_output_tokens = 8192
max_input_tokens = 32768
Then run OpenHands with:
Copy code
openhands --config-file config.toml
Recommended Values For a Mistral Small-like model (24B parameters): • `max_output_tokens`: 4096-8192 (depending on your use case) • `max_input_tokens`: 32768 (typical context window for Mistral Small) Adjust these based on your self-hosted model's actual capabilities. How Environment Variables Work OpenHands uses the pattern `LLM_`<FIELD_NAME> for LLM configuration: •
LLM_MODEL
→
model
•
LLM_BASE_URL
→
base_url
•
LLM_MAX_OUTPUT_TOKENS
→
max_output_tokens
•
LLM_MAX_INPUT_TOKENS
→
max_input_tokens
•
LLM_API_KEY
→
api_key
• etc. All environment variables are processed by
/workspace/project/openhands/openhands/core/config/utils.py
in the
load_from_env()
function. ------------------------- No code changes were made as this is a configuration issue, not a bug in the codebase. The solution is to properly configure your custom model's token limits. <sub>View full conversation</sub>
l
@icy-rocket-49995 I think those environment variables should probably fix your problem till we have a more permanent solution, please tell me if that works!
i
Thanks. I will give it a try.
I have setup such parameters in my ~/.openhands/settings.json but I still get the same error especially when I get a big output from my mcp server and litellm seems to tokenize the output. Does litellm not respect such environment in settings.json? Or maybe, they are not correct keywords?
Copy code
"max_output_tokens": 8192,
  "max_input_tokens": 32768,
l
Ah, you’ll see above that it said that ~/.openhands/settings.json doesn’t support these variables, so you should export them
i
Ah...
l
We can probably fix this, but currently it’s not supported
i
OK, thanks.
🫡 1
I used the following envs on the same terminal running `oh`:
Copy code
export LLM_MAX_OUTPUT_TOKENS=8192
export LLM_MAX_INPUT_TOKENS=32768
But I still get the same error. I get the 2216 function names from the MCP server but maybe 8192 or 32768 is not big enough?
l
Ohh, do you get the error if you remove the MCP?
i
I actually used openhands CLI to navigate my MCP outputs for now.
I can try to see if this kind of error occurs when it just works with the source trees that I want to navigate.
l
Yeah, if it happens sometimes but not other times, if you can figure out what causes the issue that’d be helpful for us to debug
i
How to pass the
max_tokens
or
max_completion_tokens
to the litellm's transformation.py (BaseConfig)? This is the part of openai.py in litellm
Copy code
class OpenAIConfig(BaseConfig):
    """
    Reference: https://platform.openai.com/docs/api-reference/chat/create

    The class `OpenAIConfig` provides configuration for the OpenAI's Chat API interface. Below are the parameters:

    - `frequency_penalty` (number or null): Defaults to 0. Allows a value between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, thereby minimizing repetition.

    - `function_call` (string or object): This optional parameter controls how the model calls functions.

    - `functions` (array): An optional parameter. It is a list of functions for which the model may generate JSON inputs.

    - `logit_bias` (map): This optional parameter modifies the likelihood of specified tokens appearing in the completion.

    - `max_tokens` (integer or null): This optional parameter helps to set the maximum number of tokens to generate in the chat completion. OpenAI has now deprecated in favor of max_completion_tokens, and is not compatible with o1 series models.
Is there a way to get the context length of the current request/response to the openhands agent?
@nutritious-balloon-65098, can you answer the above question again?
n
DongInn Kim is not authorized to send messages to this conversation.
DongInn Kim is not authorized to send messages to this conversation.
l
Hey @icy-rocket-49995, sorry I’m a bit tied up today, let me see if I can grab someone else to help
i
Thank you, @limited-student-10747!
c
@icy-rocket-49995 I have read through the thread, but not following what debugging step you are trying to take here. Do you always see the error with this model -- or only after the conversation has progressed to a certain point?
i
Thanks @curved-angle-80449, it seems that it happens only when a big chunk of data is read/processed to the LLM. Until then, everything seems to behave normal.
✅ 1
c
And is the big chunk of data coming from a tool call or an MCP call?
i
MCP side seems to be fine. It can respond with a big chunk data to the LLM and then the LLM (I am not sure who is responsible but it could be litellm, openhands, or actually our LLM) seems to have a problem with processing the big data. Today, I have not used any MCP request but I asked the agent to read through all the codes in my local source tree and to analyze them. I got the same error.
c
The following environment variables will allow you to log the actual LLM responses if you want to see the details of what you are getting back.
Copy code
# Enable completion logging
export LLM_LOG_COMPLETIONS=true

# Optional: Set custom log directory
export LLM_LOG_COMPLETIONS_FOLDER="/path/to/logs/completions"
Also the /status command inside the cli will tell you about tokens. When you set:
Copy code
export LLM_MAX_OUTPUT_TOKENS=8192
export LLM_MAX_INPUT_TOKENS=32768
And and ask for a big response -- you still see exactly this stack trace or another error?
Copy code
12:56:12 - openhands:ERROR: agent_controller.py:373 - [Agent Controller b6fb72d1-bb47-48-cfa80424caf0bb9] Error while running the agent (session ID: b6fb72d1-bb47-48-cfa80424caf0bb9): litellm.BadRequestError: OpenAIException - litellm.BadRequestError: OpenAIException - max_tokens must be at least 1, got -221.. Received Model Group=mistralai/Mistral-Small-24B-Instruct-2501
Available Model Group Fallbacks=None
i
Yes, I get the same error. This time, I could get the log files. One of them (latest one) has the following:
Copy code
"fncall_response": {"id": "chatcmpl-
8d6d2d92-2a05-4f12-bcc5-a7b7bb1d718e", "created": 1760460172, "model": "mistralai/Mistral-Small-24B-Instruct-2501", "object": "chat.completion", "
system_fingerprint": null, "choices": [{"finish_reason": "stop", "index": 0, "message": {"content": "I'll analyze the Java files in the /src direc
tory to understand their functionality. Let me start by examining the main files:\n\n1. First, let's look at the main plugin class:", "role": "ass
istant", "tool_calls": [{"index": 1, "function": {"arguments": "{\"command\": \"view\", \"path\":"...",, \"security_risk\": \"LOW\"}", "name": "str_replace_editor"}, "id": "toolu_07", "type": "function"}]
, "function_call": null}, "provider_specific_fields": {}}], "usage": {"completion_tokens": 105, "prompt_tokens": 12701, "total_tokens": 12806, "co
mpletion_tokens_details": null, "prompt_tokens_details": null}, "service_tier": null}}
c
Does same thing happen with
qwen3-coder-30b
?
i
I have not tested with qwen3 to get this kind of results because it takes too long. Lots of people in my company use qwen3 mostly. Its performance is very slow. I understand that its answer is so far very good though.
c
Unfortunately I am tied up next few hours but will check back.
👍 1
f
Hi @icy-rocket-49995, can you try adding
"llm_max_input_tokens":32768,"llm_max_output_tokens":8192
to your
settings.json
to see if it works?
Also did this "litellm.BadRequestError: OpenAIException - litellm.BadRequestError: OpenAIException - max_tokens must be at least 1, got -221.." error happen in the middle of the convo or at the beginning? I tried several times with the same model via OpenRouter but couldn't repro it
i
It happens in the middle of the conversation. It works smoothly at the beginning. I am just testing with your suggested settings.json now.
👍 1
OK, the same error occurs again when I asked like
Look through all the java files under src/ and tell what they do in detail.
.
f
Another hypothesis: Can you also try disabling the condenser via
"enable_default_condenser":false
? By default I think it will be
true
For some reasons I wasn't able to repro the same error with
Mistral-Small-24B-Instruct-2501
via OpenRouter with the same prompt above. I will try self-hosting a local model tmr and see if it makes any difference
c
I have been setting this up on my local with LM Studio as well
i
@full-greece-2387, I just tried to test with your suggestion but I got the following issue:
Copy code
oh
⠋ boto3==1.40.52                                                                                                                                  error: Failed to fetch: `https://files.pythonhosted.org/packages/0f/d2/879e9787c5263aefc5c88f0dd97cdea29ac01c480dd53c2421de77a493f7/boto3-1.40.52-py3-none-any.whl.metadata`
  Caused by: Request failed after 3 retries
  Caused by: error sending request for url (https://files.pythonhosted.org/packages/0f/d2/879e9787c5263aefc5c88f0dd97cdea29ac01c480dd53c2421de77a493f7/boto3-1.40.52-py3-none-any.whl.metadata)
  Caused by: client error (Connect)
  Caused by: dns error
  Caused by: failed to lookup address information: nodename nor servname provided, or not known
Does it have anything wrong with my side's network?
c
So you have oh as an alias to the command-line and it crashes while downloading dependencies? You should be able to dig or nslookup files.pythonhosted.org from your environment and if it isn't resolving, you have a network problem. BTW w/ the latest CLI can be downloaded as a binary. https://docs.all-hands.dev/openhands/usage/run-openhands/cli-mode#executable-binary-recommended
I have Mistral-Small-24B-Instruct-2501 running locally with LM Studio and the open hands cli now. I have context configured for 16384 and I have not been able to reproduce yet... I've got another idea to try...
i
I tried to test the downloadable binary and I got this error:
Copy code
> Auto-confirm LOW/MEDIUM risk, ask for HIGH risk

Security-based confirmation enabled. LOW/MEDIUM risk actions will auto-confirm, HIGH risk actions will ask for confirmation.
╭─────────────────────────────────────────────────────────────────────────────────────────────────────────────── Observation ────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│                                                                                                                                                                                                                                            │
│ Tool: repomix_pack_codebase                                                                                                                                                                                                                │
│ Result:                                                                                                                                                                                                                                    │
│ [MCP Tool 'repomix_pack_codebase' Observation]                                                                                                                                                                                             │
│ [Error during execution]                                                                                                                                                                                                                   │
│ Input validation error: Additional properties are not allowed ('kind' was unexpected)                                                                                                                                                      │
│                                                                                                                                                                                                                                            │
│                                                                                                                                                                                                                                            │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

Error: Missing required parameters for function 'execute_bash': {'security_risk'}
Traceback (most recent call last):
  File "openhands_cli/simple_main.py", line 45, in main
  File "openhands_cli/agent_chat.py", line 174, in run_cli_entry
  File "openhands_cli/runner.py", line 83, in process_message
  File "openhands_cli/runner.py", line 103, in _run_with_confirmation
  File "openhands/sdk/conversation/impl/local_conversation.py", line 245, in run
  File "openhands/sdk/agent/agent.py", line 209, in step
  File "openhands/sdk/agent/agent.py", line 187, in step
  File "openhands/sdk/llm/llm.py", line 476, in completion
  File "tenacity/__init__.py", line 338, in wrapped_f
  File "tenacity/__init__.py", line 477, in __call__
  File "tenacity/__init__.py", line 378, in iter
  File "tenacity/__init__.py", line 400, in <lambda>
  File "concurrent/futures/_base.py", line 449, in result
  File "concurrent/futures/_base.py", line 401, in __get_result
  File "tenacity/__init__.py", line 480, in __call__
  File "openhands/sdk/llm/llm.py", line 461, in _one_attempt
  File "openhands/sdk/llm/mixins/non_native_fc.py", line 82, in post_response_prompt_mock
  File "openhands/sdk/llm/mixins/fn_call_converter.py", line 957, in convert_non_fncall_messages_to_fncall_messages
  File "openhands/sdk/llm/mixins/fn_call_converter.py", line 739, in _extract_and_validate_params
openhands.sdk.llm.exceptions.FunctionCallValidationError: Missing required parameters for function 'execute_bash': {'security_risk'}
Traceback (most recent call last):
  File "openhands_cli/simple_main.py", line 59, in <module>
  File "openhands_cli/simple_main.py", line 45, in main
  File "openhands_cli/agent_chat.py", line 174, in run_cli_entry
  File "openhands_cli/runner.py", line 83, in process_message
  File "openhands_cli/runner.py", line 103, in _run_with_confirmation
  File "openhands/sdk/conversation/impl/local_conversation.py", line 245, in run
  File "openhands/sdk/agent/agent.py", line 209, in step
  File "openhands/sdk/agent/agent.py", line 187, in step
  File "openhands/sdk/llm/llm.py", line 476, in completion
  File "tenacity/__init__.py", line 338, in wrapped_f
  File "tenacity/__init__.py", line 477, in __call__
  File "tenacity/__init__.py", line 378, in iter
  File "tenacity/__init__.py", line 400, in <lambda>
  File "concurrent/futures/_base.py", line 449, in result
  File "concurrent/futures/_base.py", line 401, in __get_result
  File "tenacity/__init__.py", line 480, in __call__
  File "openhands/sdk/llm/llm.py", line 461, in _one_attempt
  File "openhands/sdk/llm/mixins/non_native_fc.py", line 82, in post_response_prompt_mock
  File "openhands/sdk/llm/mixins/fn_call_converter.py", line 957, in convert_non_fncall_messages_to_fncall_messages
  File "openhands/sdk/llm/mixins/fn_call_converter.py", line 739, in _extract_and_validate_params
openhands.sdk.llm.exceptions.FunctionCallValidationError: Missing required parameters for function 'execute_bash': {'security_risk'}
[PYI-32980:ERROR] Failed to execute script 'simple_main' due to unhandled exception!
c
Interesting. I just opened an issue that could be related. https://github.com/All-Hands-AI/OpenHands/issues/11377. Let me take a closer look at your stack trace...
l
I think the missing “security_risk” is an issue with weaker language models that don’t read the tool description carefully
I thought that might be fixed with the new version of the cli, but maybe not, let me check
c
ok -- this looks to be a related but distinct issue from the bug I just linked.
l
Thanks! Just FYI there may be a lot of similar issues posted already: https://github.com/All-Hands-AI/OpenHands/issues?q=is%3Aissue%20state%3Aopen%20security_risk
✅ 1
c
I'll raise with the team tomorrow.
l
Just to go full circle on this, we moved the discussion of the security_risk parameter here: https://openhands-ai.slack.com/archives/C06R25BT5B2/p1760490831617229
ty 1
👀 1
f
@icy-rocket-49995 I tried to repro your earlier error with the old CLI by hosting the model with vLLM and unfortunately I also wasn't able to repro it, the behavior on my side was the model ran until the message list hit the 32k context limit and then the CLI stopped. I guess your error is related to the specific hosting setup and it's a bit tricky to debug. Given we're transitioning to CLI V1, maybe you can try using the new version down the road and we can help with other errors you run into
👍 1