Metadata-Version: 2.4
Name: call-context-lib
Version: 0.1.0
Summary: A context management library for Python applications with callback support
Project-URL: Homepage, https://github.com/jitokim/call-context-lib
Project-URL: Bug Tracker, https://github.com/jitokim/call-context-lib/issues
Project-URL: Repository, https://github.com/jitokim/call-context-lib
Project-URL: Documentation, https://jitokim.github.io/call-context-lib
Author-email: Jihoon Kim <pigberger70@gmail.com>
Maintainer-email: Jihoon Kim <pigberger70@gmail.com>
License: MIT
License-File: LICENSE
Keywords: callback,context,context-management,library,python
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Typing :: Typed
Requires-Python: >=3.9
Provides-Extra: dev
Requires-Dist: bandit>=1.7.0; extra == 'dev'
Requires-Dist: build>=0.10.0; extra == 'dev'
Requires-Dist: pip-audit>=2.7.0; extra == 'dev'
Requires-Dist: pre-commit>=3.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
Requires-Dist: pytest-mock>=3.10.0; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: ruff>=0.1.0; extra == 'dev'
Requires-Dist: setuptools>=78.1.1; extra == 'dev'
Requires-Dist: twine>=4.0.0; extra == 'dev'
Description-Content-Type: text/markdown

# Call Context Lib

[![CI](https://github.com/jitokim/call-context-lib/actions/workflows/ci.yml/badge.svg)](https://github.com/jitokim/call-context-lib/actions/workflows/ci.yml)
[![PyPI version](https://badge.fury.io/py/call-context-lib.svg)](https://badge.fury.io/py/call-context-lib)
[![Python](https://img.shields.io/pypi/pyversions/call-context-lib.svg)](https://pypi.org/project/call-context-lib/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

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

```bash
pip install call-context-lib
```

For development:

```bash
pip install call-context-lib[dev]
```

## Quick Start

### Basic Usage

```python
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

```python
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

```python
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

```python
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

```python
CallContext(user_id: str, turn_id: str, meta: dict = None, callbacks: list = None)
```

#### Methods

- `get_user_id() -> str`: Get the user ID
- `get_turn_id() -> str`: Get the turn ID  
- `get_meta(key: str, all_values: bool = False) -> Any`: Get metadata value(s)
- `set_meta(key: str, value: Any) -> None`: Set metadata value
- `ainvoke(fn: Callable, *args, **kwargs)`: Execute function with context
- `astream(fn: Callable, *args, **kwargs) -> AsyncGenerator`: Stream function output

### CallContextCallback

Abstract base class for implementing callbacks.

```python
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:

```bash
make run-examples
```

## Development

### Setting up development environment

```bash
# 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 package
- `make install-dev` - Install with development dependencies  
- `make test` - Run tests
- `make test-cov` - Run tests with coverage
- `make lint` - Run linting
- `make format` - Format code
- `make build` - Build package
- `make publish` - Publish to PyPI
- `make 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.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Changelog

See [CHANGELOG.md](CHANGELOG.md) for a list of changes and version history.

## Support

If you encounter any problems or have questions, please [open an issue](https://github.com/jitokim/call-context-lib/issues) on GitHub.