У меня Django проект. Celery, Python. Я создаю задачи "prompt" и делаю запрос с помощью groq_sdk к AI модели. Также я делаю вызываю эту задачу в shared_task "process_file", чтобы отправить текст для промпта (мой текст -- это транскрибация аудиофайла), подскажи, как мне отправить большой текст в промпт, если есть rate limits по использованию данной модели, а именно:
модель, которую я использую -- llama-3.1-70b-versatile;
кол-во запросов в минуту: 30;
кол-во токенов в минуту: 14 400;
запросов в день: 20 000;
кол-во токенов в день: 500 000;
Главный Вопрос:
Как мне передать большой текст на промпт, может, кусками (с помощью context window), чтобы не отругалась 429 ошибка на rate limits, ибо кол-во токенов в минуту 14 400;
Processing large texts with strict rate limits can be challenging, especially when dealing with both request and token limitations. Here's how you can modify your code to handle large texts by chunking them appropriately and ensuring you stay within the rate limits imposed by your AI model provider.
Understanding the Rate Limits
Firstly, let's break down the rate limits you've provided:
Requests per minute: 30
Tokens per minute: 14,400
Requests per day: 20,000
Tokens per day: 500,000
Note: The tokens per minute limit applies to the total tokens used in both the input (prompt) and the output (completion) across all requests in a minute. This means you need to ensure that the sum of the tokens in your prompts and the expected completions doesn't exceed 14,400 per minute.
Strategy to Handle Large Texts
To handle large texts without hitting the rate limits, you can:
Chunk the Text: Break down the large transcription text into smaller chunks that, when processed individually, do not exceed the token limit per request.
Sequential Processing with Rate Limiting: Process the chunks sequentially, ensuring that the cumulative tokens per minute stay within the allowed limit.
Cumulative Summarization: Summarize each chunk individually and then combine these summaries into a final summary. Optionally, you can further summarize the combined summaries if needed.
Implementation Steps
1. Calculate Token Usage
Estimate the number of tokens for both the input prompt and the expected completion for each chunk. You can use tokenization libraries like tiktoken to accurately calculate token counts.
Create a function to split the transcription text into chunks that ensure each request stays within a certain token limit.
python
def split_text_into_chunks(text, max_chunk_tokens, model_name):
encoding = tiktoken.encoding_for_model(model_name)
encoded_text = encoding.encode(text)
chunks = []
for i in range(0, len(encoded_text), max_chunk_tokens):
chunk = encoding.decode(encoded_text[i:i+max_chunk_tokens])
chunks.append(chunk)
return chunks
Example Usage:
python
# Assuming you reserve 1000 tokens for the completion and system/user messages
max_tokens_per_request = 6000 # As per your max_tokens parameter
reserved_tokens = 1000 # Adjust based on expected completion length and messages
max_chunk_tokens = max_tokens_per_request - reserved_tokens
chunks = split_text_into_chunks(transcription_text, max_chunk_tokens, "llama-3.1-70b-versatile")
3. Modify the prompt Function
Update your prompt function to accept a list of text chunks and process them sequentially.
python
@shared_task(name="prompt_queue", rate_limit="30/m")
def prompt(chunks, action_type_id, file_id, language_code, kit_id=None):
action_type = TranscriptionActionType.objects.get(id=action_type_id)
summaries = []
total_tokens_used = 0
for chunk in chunks:
# Prepare the messages
messages = [
{"role": "system", "content": action_type.system_content},
{
"role": "user",
"content": action_type.user_content.format(
text=chunk, language=language_code
),
},
]
# Estimate tokens for the request
input_tokens = sum(count_tokens(m['content'], "llama-3.1-70b-versatile") for m in messages)
max_completion_tokens = 1000 # Adjust based on your needs
total_tokens = input_tokens + max_completion_tokens
# Check if we are about to exceed the tokens per minute limit
# Implement a custom rate limiter if necessary
# Make the API call
completion = client.chat.completions.create(
model="llama-3.1-70b-versatile",
messages=messages,
temperature=0.1,
max_tokens=max_completion_tokens,
top_p=1,
stream=False,
stop=None,
)
content = completion.choices[0].message.content
summaries.append(content)
# Update the total tokens used
total_tokens_used += completion.usage.total_tokens # Assuming the SDK provides this
# If total_tokens_used approaches 14,400, you may need to wait until the next minute
# Implement sleep or a rate limiter as needed
# Combine the summaries
final_summary = " ".join(summaries)
# Optionally, summarize the combined summaries if too long
# You can call the model again with final_summary if needed
# Save the final summary
transcription_action = TranscriptionAction.objects.create(
file_id=file_id, action_type_id=action_type_id, content=final_summary, kit_id=kit_id
)
return transcription_action.id
4. Implement Rate Limiting
Since you have a tokens per minute limit, you need to ensure that your cumulative token usage per minute doesn't exceed this limit. You can implement a custom rate limiter.
python
import time
from threading import Lock
class TokenBucket:
def __init__(self, tokens_per_minute):
self.capacity = tokens_per_minute
self.tokens = tokens_per_minute
self.fill_rate = tokens_per_minute / 60.0 # tokens per second
self.timestamp = time.time()
self.lock = Lock()
def consume(self, tokens_needed):
with self.lock:
now = time.time()
elapsed = now - self.timestamp
self.timestamp = now
self.tokens += elapsed * self.fill_rate
if self.tokens > self.capacity:
self.tokens = self.capacity
if self.tokens >= tokens_needed:
self.tokens -= tokens_needed
return True
else:
return False
# Initialize the token bucket
token_bucket = TokenBucket(tokens_per_minute=14400)
def wait_for_tokens(tokens_needed):
while not token_bucket.consume(tokens_needed):
time.sleep(1)
Use wait_for_tokens before making each API call within your prompt function.
python
# Check and wait if necessary
tokens_needed = total_tokens # input_tokens + max_completion_tokens
wait_for_tokens(tokens_needed)
5. Adjust Your Celery Configuration
Your current rate_limit="30/m" in the Celery task decorator only limits the number of tasks per minute, not the tokens. Since we are implementing our own token-based rate limiter, you might want to adjust or remove this rate limit if it's conflicting.
Summary
By breaking down your large text into manageable chunks and implementing a custom rate limiter based on tokens, you can process the entire transcription without exceeding the rate limits. Make sure to:
Estimate tokens accurately to avoid surprises.
Implement a rate limiter to control the flow of tokens per minute.
Process the chunks sequentially to simplify rate limiting.
Be aware of the cumulative effect of multiple users or concurrent processes.
Additional Considerations
Error Handling: Ensure you have robust error handling around the API calls to retry or log failures as needed.
Concurrency: If multiple users are processing files simultaneously, you'll need to consider the cumulative token usage across all tasks. A centralized rate limiter or a distributed locking mechanism might be necessary.
Token Usage Reporting: If the SDK provides actual token usage in the response (e.g., completion.usage.total_tokens), use that to adjust your token counts more accurately.
Asynchronous Processing: If tasks are queuing up due to rate limiting, you might want to provide feedback to the user that there will be a delay in processing.
Final Notes
Adjust the token limits and chunk sizes based on empirical data from your usage patterns. You may need to iterate on the chunk size to find the optimal balance between performance and compliance with rate limits.
By carefully managing how you process and send data to the AI model, you can efficiently handle large texts without running into rate limit errors.