-
Notifications
You must be signed in to change notification settings - Fork 38
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
Feature/user rate limits #1342
Open
jamesrichards4
wants to merge
9
commits into
main
Choose a base branch
from
feature/user-rate-limits
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Feature/user rate limits #1342
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
127bfcb
Basic rate limiter in place, simple tests added
jamesrichards4 52e38ec
Bringing in line with latest main
jamesrichards4 c555bd7
Merge branch 'main' into feature/user-rate-limits
jamesrichards4 b92513f
Added additional rate limiter test
jamesrichards4 8c167b3
Setting default rate limits for chatconsumer
jamesrichards4 3ad97e3
Ruff
jamesrichards4 2c7ee8c
Using db token counts rather than a credits based system for ratelimi…
jamesrichards4 96bd3e6
Merging latest main
jamesrichards4 f7cc60d
@pytest.mark.asyncio()
gecBurton 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 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 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 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,29 @@ | ||
from datetime import UTC, datetime, timedelta | ||
from uuid import UUID | ||
|
||
from asgiref.sync import sync_to_async | ||
|
||
from redbox.models.chain import RedboxState | ||
from redbox.models.settings import get_settings | ||
from redbox_app.redbox_core.models import ChatMessage, User | ||
|
||
_settings = get_settings() | ||
|
||
|
||
class UserRateLimiter: | ||
def __init__(self, token_ratelimit=_settings.user_token_ratelimit) -> None: | ||
self.token_ratelimit = token_ratelimit | ||
|
||
async def is_allowed(self, state: RedboxState): | ||
consumed_ratelimit = await sync_to_async(self.get_tokens_for_user_in_last_minute)(state.user_uuid) | ||
request_tokens = self.calculate_request_credits(state) | ||
return request_tokens < self.token_ratelimit - consumed_ratelimit | ||
|
||
def get_tokens_for_user_in_last_minute(self, user_uuid: UUID): | ||
user = User.objects.get(pk=user_uuid) | ||
since = datetime.now(UTC) - timedelta(minutes=1) | ||
recent_messages = ChatMessage.get_since(user, since) | ||
return sum(m.token_count for m in recent_messages) | ||
|
||
def calculate_request_credits(self, state: RedboxState) -> int: | ||
return int(sum(d.metadata.get("token_count", 0) for d in state.documents)) |
This file contains 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 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,55 @@ | ||
from dataclasses import dataclass | ||
from uuid import UUID, uuid4 | ||
|
||
import pytest | ||
from langchain_core.documents import Document | ||
|
||
from redbox.models.chain import RedboxState | ||
from redbox_app.redbox_core.ratelimit import UserRateLimiter | ||
|
||
test_user_uuid = uuid4() | ||
|
||
|
||
@dataclass | ||
class UserActivity: | ||
total_document_tokens: int | ||
number_documents: int | ||
|
||
|
||
def request_state(number_of_documents: int, total_document_tokens: int): | ||
return RedboxState( | ||
user_uuid=test_user_uuid, | ||
documents=[ | ||
Document("", metadata={"token_count": int(total_document_tokens / number_of_documents)}) | ||
for _ in range(number_of_documents) | ||
], | ||
) | ||
|
||
|
||
@pytest.mark.parametrize( | ||
("token_ratelimit", "users_consumed_tokens", "request_state", "expect_allowed"), | ||
[ | ||
(1000, {test_user_uuid: 100}, request_state(2, 200), True), | ||
(1000, {test_user_uuid: 100, uuid4(): 1000, uuid4(): 900}, request_state(1, 800), True), | ||
(1000, {test_user_uuid: 800}, request_state(2, 240), False), | ||
(1000, {test_user_uuid: 800}, request_state(8, 400), False), | ||
], | ||
) | ||
@pytest.mark.asyncio() | ||
async def test_ratelimiter( | ||
token_ratelimit: int, users_consumed_tokens: dict[UUID, int], request_state: RedboxState, expect_allowed: bool | ||
): | ||
ratelimiter = UserRateLimiter(token_ratelimit=token_ratelimit) | ||
|
||
def create_user_tokens_consumed_mock(tokens_per_user: dict[UUID, int]): | ||
def _impl(user_uuid: UUID): | ||
return tokens_per_user.get(user_uuid, 0) | ||
|
||
return _impl | ||
|
||
ratelimiter.get_tokens_for_user_in_last_minute = create_user_tokens_consumed_mock(users_consumed_tokens) | ||
request_allowed = await ratelimiter.is_allowed(request_state) | ||
if request_allowed != expect_allowed: | ||
pytest.fail( | ||
reason=f"Request allow status did not match: Expected [{expect_allowed}]. Received [{request_allowed}]" | ||
) |
This file contains 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 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 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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
you can get the database to do the sum here?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
and this could now be moved to be a method belonging to the
User
model?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
but i think that there is a bigger problem here... the
ChatMessage.tocken_count
only includes what the user has typed, and not the inlcuded files, I think we need to make this change first?