-
Notifications
You must be signed in to change notification settings - Fork 47
Handle missing tiktoken encoding data in api token counting #266
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
2cbfcd6
Handle missing tiktoken encoding data in api token counting
bhavana-giri 38f0396
Tighten oversized message truncation
bhavana-giri 0ef76f6
Keep issue 237 fix narrowly scoped
bhavana-giri 2947bbc
Use lower-case names for tiktoken state
bhavana-giri 05d3c95
Address Copilot review cleanups
bhavana-giri 8447212
Simplify tiktoken encoding cache state
bhavana-giri 1acdc0e
Memoize failed tiktoken initialization
bhavana-giri e4dc8ff
Add tiktoken retry backoff
bhavana-giri 705e950
Refactor tiktoken retry window check
bhavana-giri d1bddbc
Update agent_memory_server/api.py
bsbodden File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| """Tests for GitHub issue #237: safe token counting when tiktoken is unavailable.""" | ||
|
|
||
| from unittest.mock import Mock, patch | ||
|
|
||
| import pytest | ||
|
|
||
| from agent_memory_server.api import ( | ||
| _calculate_messages_token_count, | ||
| _get_tiktoken_encoding, | ||
| ) | ||
| from agent_memory_server.models import MemoryMessage | ||
|
|
||
|
|
||
| class TestIssue237TiktokenFallback: | ||
| def test_calculate_messages_token_count_falls_back_when_tiktoken_unavailable( | ||
| self, | ||
| ): | ||
| """Token counting should degrade gracefully when the encoding cannot load.""" | ||
| messages = [MemoryMessage(role="user", content="Hello world")] | ||
|
|
||
| with ( | ||
| patch("agent_memory_server.api._tiktoken_encoding", None), | ||
| patch("agent_memory_server.api._tiktoken_encoding_last_failed_at", None), | ||
| patch( | ||
| "agent_memory_server.api.tiktoken.get_encoding", | ||
| side_effect=Exception("Could not download encoding data"), | ||
| ), | ||
| ): | ||
| token_count = _calculate_messages_token_count(messages) | ||
|
|
||
| assert token_count > 0 | ||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_get_working_memory_uses_fallback_when_tiktoken_unavailable( | ||
| self, client | ||
| ): | ||
| """GET should return session data instead of a 500 when tokenization fails.""" | ||
| session_id = "issue-237-api" | ||
|
|
||
| put_response = await client.put( | ||
| f"/v1/working-memory/{session_id}", | ||
| json={ | ||
| "messages": [{"role": "user", "content": "Hello from issue 237"}], | ||
| "user_id": "alice", | ||
| "namespace": "demo", | ||
| }, | ||
| ) | ||
| assert put_response.status_code == 200 | ||
|
|
||
| with ( | ||
| patch("agent_memory_server.api._tiktoken_encoding", None), | ||
| patch("agent_memory_server.api._tiktoken_encoding_last_failed_at", None), | ||
| patch( | ||
| "agent_memory_server.api.tiktoken.get_encoding", | ||
| side_effect=Exception("Could not download encoding data"), | ||
| ), | ||
| ): | ||
| get_response = await client.get( | ||
| f"/v1/working-memory/{session_id}?model_name=gpt-4o" | ||
| ) | ||
|
|
||
| assert get_response.status_code == 200, get_response.text | ||
| data = get_response.json() | ||
| assert data["session_id"] == session_id | ||
| assert len(data["messages"]) == 1 | ||
|
|
||
| def test_get_tiktoken_encoding_skips_retries_within_backoff_window(self): | ||
| """Repeated calls should not re-attempt loading within the retry interval.""" | ||
| mock_get_encoding = Mock(side_effect=Exception("Could not download encoding")) | ||
|
|
||
| with ( | ||
| patch("agent_memory_server.api._tiktoken_encoding", None), | ||
| patch("agent_memory_server.api._tiktoken_encoding_last_failed_at", None), | ||
| patch("agent_memory_server.api.time.monotonic", side_effect=[100.0, 101.0]), | ||
| patch("agent_memory_server.api.tiktoken.get_encoding", mock_get_encoding), | ||
| ): | ||
| assert _get_tiktoken_encoding() is None | ||
| assert _get_tiktoken_encoding() is None | ||
|
|
||
| assert mock_get_encoding.call_count == 1 | ||
|
|
||
| def test_get_tiktoken_encoding_retries_after_backoff_window(self): | ||
| """A later call should retry loading once the backoff window has passed.""" | ||
|
|
||
| class FakeEncoding: | ||
| def encode(self, text: str) -> list[int]: | ||
| return [1] * len(text) | ||
|
|
||
| mock_get_encoding = Mock( | ||
| side_effect=[Exception("temporary failure"), FakeEncoding()] | ||
| ) | ||
|
|
||
| with ( | ||
| patch("agent_memory_server.api._tiktoken_encoding", None), | ||
| patch("agent_memory_server.api._tiktoken_encoding_last_failed_at", None), | ||
| patch("agent_memory_server.api.time.monotonic", side_effect=[100.0, 401.0]), | ||
| patch("agent_memory_server.api.tiktoken.get_encoding", mock_get_encoding), | ||
| ): | ||
| assert _get_tiktoken_encoding() is None | ||
| assert _get_tiktoken_encoding() is not None | ||
|
|
||
| assert mock_get_encoding.call_count == 2 |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.