Skip to content

fix(ollama): avoid UnboundLocalError on empty model stream#2823

Open
he-yufeng wants to merge 1 commit into
strands-agents:mainfrom
he-yufeng:fix/ollama-empty-stream
Open

fix(ollama): avoid UnboundLocalError on empty model stream#2823
he-yufeng wants to merge 1 commit into
strands-agents:mainfrom
he-yufeng:fix/ollama-empty-stream

Conversation

@he-yufeng

Copy link
Copy Markdown
Contributor

Description

OllamaModel.stream reads event after the async for event in response loop to build the message_stop and metadata chunks. When the model returns an empty stream (no chunks at all), event is never bound, so event.done_reason raises UnboundLocalError instead of closing the turn cleanly.

Repro against current main:

async def empty():
    if False:
        yield None

# client.chat returns an empty async iterator
[x async for x in model.stream(messages)]
# UnboundLocalError: cannot access local variable 'event'

Fix:

  • initialize event = None before the loop
  • fall back to None for the stop reason when there was no event (format_chunk already maps anything that is not tool_use/length to end_turn)
  • skip the metadata chunk when no event arrived, since there is no usage to report

This mirrors what GeminiModel.stream already does for the empty-stream case, so the providers stay consistent. An empty stream now ends with a normal messageStop(end_turn) and no metadata chunk.

Related Issues

None tracked; found while auditing the model providers for the empty-stream edge case.

Documentation PR

Not needed, no public API or behavior change beyond not raising.

Type of Change

Bug fix

Testing

Added test_stream_empty_response, which fails on main with the UnboundLocalError above and passes with the fix.

python -m pytest tests/strands/models/test_ollama.py
# 34 passed
ruff check / ruff format --check  # clean
mypy src/strands/models/ollama.py # Success: no issues found

Checklist

  • I have read the CONTRIBUTING document
  • I have reviewed and understand every line of code in this PR, including any generated by AI tools, and I can explain why it works
  • My change is focused and reasonably small; I have split unrelated work into separate PRs
  • I have added any necessary tests that prove my fix is effective or my feature works
  • My changes generate no new warnings

@github-actions github-actions Bot added size/s bug Something isn't working area-model Related to models or model providers python Pull requests that update python code labels Jun 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-model Related to models or model providers bug Something isn't working python Pull requests that update python code size/s

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant