A context management library for Python applications with callback support
Project description
Call Context Lib
A Python context management library for applications with callback support, designed for managing execution context with metadata and callback functionality.
Features
- Context Management: Track user sessions, turns, and metadata across function calls
- Async Support: Full support for async/await patterns and async generators
- Callback System: Execute callbacks on context completion
- Metadata Handling: Store and retrieve metadata with support for multiple values per key
- Streaming Support: Built-in support for streaming responses with context preservation
- Type Safety: Fully typed with Python type hints
Installation
pip install call-context-lib
For development:
pip install call-context-lib[dev]
Quick Start
Basic Usage
from call_context_lib import CallContext
# Create a context
ctx = CallContext(user_id="user123", turn_id="turn456")
# Set metadata
ctx.set_meta("request_type", "chat")
ctx.set_meta("model", "gpt-4")
# Get metadata
model = ctx.get_meta("model") # Returns "gpt-4"
# Execute a function with context
async def my_function(context: CallContext):
context.set_meta("processed", True)
return "Hello World"
result = await ctx.ainvoke(my_function)
Streaming Support
async def streaming_function(context: CallContext):
for i in range(5):
yield f"Token {i} "
async for token in ctx.astream(streaming_function):
print(token, end="")
# Output: Token 0 Token 1 Token 2 Token 3 Token 4
Using Callbacks
from call_context_lib import CallContextCallback
class LoggingCallback(CallContextCallback):
async def call(self, ctx: CallContext) -> None:
print(f"Completed for user {ctx.get_user_id()}")
print(f"Final output: {ctx.get_meta('output')}")
# Add callback to context
ctx.callbacks.append(LoggingCallback())
# Callbacks are automatically executed on completion
await ctx.ainvoke(my_function)
Multiple Values for Same Key
ctx.set_meta("tag", "python")
ctx.set_meta("tag", "async")
ctx.set_meta("tag", "context")
# Get the most recent value
latest_tag = ctx.get_meta("tag") # Returns "context"
# Get all values
all_tags = ctx.get_meta("tag", all_values=True) # Returns ["python", "async", "context"]
API Reference
CallContext
The main context class that manages execution state and metadata.
Constructor
CallContext(user_id: str, turn_id: str, meta: dict = None, callbacks: list = None)
Methods
get_user_id() -> str: Get the user IDget_turn_id() -> str: Get the turn IDget_meta(key: str, all_values: bool = False) -> Any: Get metadata value(s)set_meta(key: str, value: Any) -> None: Set metadata valueainvoke(fn: Callable, *args, **kwargs): Execute function with contextastream(fn: Callable, *args, **kwargs) -> AsyncGenerator: Stream function output
CallContextCallback
Abstract base class for implementing callbacks.
class MyCallback(CallContextCallback):
async def call(self, ctx: CallContext) -> None:
# Your callback logic here
pass
Examples
The examples/ directory contains practical examples:
- FastAPI Integration: How to use the library with FastAPI applications
- Streaming Responses: Examples of streaming with context preservation
- Custom Callbacks: Implementing custom callback functionality
To run examples:
make run-examples
Development
Setting up development environment
# Clone the repository
git clone https://github.com/jitokim/call-context-lib.git
cd call-context-lib
# Install development dependencies
make install-dev
# Run tests
make test
# Run linting
make lint
# Format code
make format
Available Make Commands
make install- Install packagemake install-dev- Install with development dependenciesmake test- Run testsmake test-cov- Run tests with coveragemake lint- Run lintingmake format- Format codemake build- Build packagemake publish- Publish to PyPImake clean- Clean build artifacts
Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Changelog
See CHANGELOG.md for a list of changes and version history.
Support
If you encounter any problems or have questions, please open an issue on GitHub.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file call_context_lib-0.1.0.tar.gz.
File metadata
- Download URL: call_context_lib-0.1.0.tar.gz
- Upload date:
- Size: 8.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
32b8f3d577555cb6a68c641092c8144a4816ba91dd43e2f4d1a3e9ef8ff9f90d
|
|
| MD5 |
ee889988dc3bd690d6b8f92ff8009b57
|
|
| BLAKE2b-256 |
028c8527e7f9f8d213277d77350129c5a102f75e2e2bd13e898c229e04486d12
|
File details
Details for the file call_context_lib-0.1.0-py3-none-any.whl.
File metadata
- Download URL: call_context_lib-0.1.0-py3-none-any.whl
- Upload date:
- Size: 7.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0bad293ba620798b54fa613e5adf21e3d6713d827b33e5d7d494b3e2bd140378
|
|
| MD5 |
18f6f0a32fb117f43609c30f64997ec0
|
|
| BLAKE2b-256 |
9c383b8189f2fd7ab08689ce8515b89d5ac9651533ce4c012ce2138fe2459ecb
|