How to Accumulate Streamed Tokens into a Final String in Python
Accumulate a stream of tokens into a single final string by concatenating each token in sequence.
Python code
12 linesdef accumulate_tokens(tokens):
"""Accumulate a stream of tokens into a single final string."""
result = ""
for token in tokens:
result += token
return result
if __name__ == "__main__":
token_stream = ["Hello", ", ", "world", "!", " This ", "is ", "accumulated."]
final_string = accumulate_tokens(token_stream)
print(final_string)
Output
Hello, world! This is accumulated.
How it works
This function iterates over an iterable of tokens and appends each one to an accumulating result string. Because strings are immutable in Python, each += creates a new string and rebinds result, which is fine for small token counts. For very large streams, consider using ''.join(tokens) for better performance.
Common mistakes
- Assuming tokens arrive as a list, but they might be a generator – the loop handles both.
- Forgetting that strings are immutable, so repeated `+=` can be slow for huge token counts.
- Not handling non-string tokens, which would raise a TypeError.
Variations
- Use `functools.reduce(lambda a, b: a + b, tokens, '')` for a functional approach.
- Use `''.join(token for token in tokens)` to avoid intermediate string creation.
Real-world use cases
- Collecting streamed text chunks from an LLM API response into a complete answer.
- Aggregating log lines emitted by a streaming process into a single report.
- Combining partial web socket messages into a full payload before parsing.
Sponsored
More from AI & LLM integration patterns
- Cache LLM Completions by Hashing the Prompt in Python easy
- Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo easy
- Circuit Breaker Pattern in Python for LLM API Calls medium
- Cosine Similarity to Retrieve Top K Chunks in Python easy
- Demonstrate Prompt Injection Bypass in Python easy
- How to Append Few-Shot Examples to a Prompt in Python easy
Keep learning
Related tutorials and quizzes for this topic.