# API Reference

Complete API documentation for OCLAWMA.

## Table of Contents

- [Providers](#providers)
- [Skills](#skills)
- [Tools](#tools)
- [Session](#session)
- [Context Budget](#context-budget)

## Providers

### BaseProvider

Abstract base class for all LLM providers.

```python
from oclawma.providers.base import BaseProvider, CompletionRequest, Message

class MyProvider(BaseProvider):
    async def complete(self, request: CompletionRequest) -> CompletionResponse:
        ...
```

#### Methods

##### `complete(request: CompletionRequest) -> CompletionResponse`

Generate a chat completion.

**Parameters:**
- `request` (`CompletionRequest`): The completion request

**Returns:**
- `CompletionResponse`: The completion response

**Raises:**
- `ConnectionError`: Unable to connect to provider
- `AuthenticationError`: Authentication failed
- `ModelNotFoundError`: Model not available
- `CompletionError`: Completion generation failed

##### `stream_complete(request: CompletionRequest) -> AsyncIterator[CompletionResponse]`

Generate a streaming chat completion.

**Parameters:**
- `request` (`CompletionRequest`): The completion request (must have `stream=True`)

**Yields:**
- `CompletionResponse`: Response chunks

##### `list_models() -> list[str]`

List available models.

**Returns:**
- `list[str]`: List of model names

##### `count_tokens(text: str, model: str | None = None) -> int`

Estimate token count for text.

**Parameters:**
- `text` (`str`): Text to count
- `model` (`str`, optional): Model name for accuracy

**Returns:**
- `int`: Estimated token count

### OllamaProvider

Local LLM provider using Ollama.

```python
from oclawma.providers.ollama import OllamaProvider

provider = OllamaProvider(base_url="http://localhost:11434")
```

#### Constructor

```python
OllamaProvider(base_url: str = "http://localhost:11434")
```

**Parameters:**
- `base_url` (`str`): Ollama server URL

### KimiProvider

Cloud provider for Kimi models.

```python
from oclawma.providers.kimi import KimiProvider

provider = KimiProvider(api_key="your-api-key")
```

#### Constructor

```python
KimiProvider(api_key: str, base_url: str = "https://api.kimi.com")
```

**Parameters:**
- `api_key` (`str`): Kimi API key
- `base_url` (`str`): API base URL

## Skills

### LazySkill

Base class for lazy-loaded skills.

```python
from oclawma.skills import LazySkill, SkillMetadata

class MySkill(LazySkill):
    def _load(self) -> None:
        self._tools = {"my_tool": self._my_tool}
        self._loaded = True
```

#### Methods

##### `load() -> None`

Explicitly load the skill.

##### `unload() -> None`

Unload the skill to free resources.

##### `execute_tool(tool_name: str, **params) -> Any`

Execute a tool by name.

**Parameters:**
- `tool_name` (`str`): Name of the tool
- `**params`: Tool parameters

**Returns:**
- Tool execution result

**Raises:**
- `SkillToolError`: Tool doesn't exist or failed

##### `list_tools() -> list[str]`

List available tool names.

**Returns:**
- `list[str]`: Tool names

### SkillRegistry

Registry for managing skills.

```python
from oclawma.skills import SkillRegistry

registry = SkillRegistry()
```

#### Methods

##### `discover_skills(path: str, recursive: bool = True) -> None`

Discover skills from a directory.

**Parameters:**
- `path` (`str`): Directory to search
- `recursive` (`bool`): Search recursively

##### `discover_entry_points() -> None`

Discover pip-installed skills.

##### `list_available() -> list[str]`

List all discovered skills.

**Returns:**
- `list[str]`: Skill names

##### `list_loaded() -> list[str]`

List currently loaded skills.

**Returns:**
- `list[str]`: Loaded skill names

##### `has_skill(name: str) -> bool`

Check if a skill exists.

**Parameters:**
- `name` (`str`): Skill name

**Returns:**
- `bool`: True if skill exists

##### `execute_tool(skill_name: str, tool_name: str, **params) -> Any`

Execute a tool.

**Parameters:**
- `skill_name` (`str`): Skill name
- `tool_name` (`str`): Tool name
- `**params`: Tool parameters

**Returns:**
- Tool execution result

### SkillMetadata

Metadata about a skill.

```python
from oclawma.skills import SkillMetadata

metadata = SkillMetadata(
    name="my_skill",
    version="1.0.0",
    description="My skill",
    author="Your Name",
    category="utilities",
    tags=["example"],
    entry_point="my_skill:MySkill",
)
```

#### Fields

| Field | Type | Description |
|-------|------|-------------|
| `name` | `str` | Skill identifier |
| `version` | `str` | Semantic version |
| `description` | `str` | Human-readable description |
| `author` | `str` | Author name |
| `category` | `str` | Category for grouping |
| `tags` | `list[str]` | Tags |
| `entry_point` | `str` | Module path to skill class |
| `estimated_tokens` | `int` | Estimated token count |
| `tool_count` | `int` | Number of tools |

## Tools

### BaseTool

Abstract base class for tools.

```python
from oclawma.tools.base import BaseTool

class MyTool(BaseTool):
    @property
    def name(self) -> str:
        return "my_tool"
    
    @property
    def description(self) -> str:
        return "Does something"
    
    async def execute(self, **params) -> ToolResult:
        ...
```

#### Properties

##### `name: str`

Tool identifier.

##### `description: str`

Human-readable description.

##### `schema: dict`

JSON schema for tool parameters.

#### Methods

##### `execute(**params) -> ToolResult`

Execute the tool.

**Parameters:**
- `**params`: Tool-specific parameters

**Returns:**
- `ToolResult`: Execution result

### ToolResult

Result of tool execution.

```python
from oclawma.tools.base import ToolResult

result = ToolResult(
    tool_name="my_tool",
    success=True,
    output="Result data",
    error_message=None,
)
```

#### Fields

| Field | Type | Description |
|-------|------|-------------|
| `tool_name` | `str` | Tool identifier |
| `success` | `bool` | Whether execution succeeded |
| `output` | `Any` | Result data |
| `error_message` | `str | None` | Error message if failed |

#### Methods

##### `to_llm_context() -> str`

Format result for LLM context.

**Returns:**
- `str`: Formatted result

### ToolRegistry

Registry for built-in tools.

```python
from oclawma.tools import ToolRegistry, create_default_tools

registry = create_default_tools()
```

#### Methods

##### `register(tool: BaseTool) -> None`

Register a tool.

**Parameters:**
- `tool` (`BaseTool`): Tool to register

##### `get(name: str) -> BaseTool`

Get a tool by name.

**Parameters:**
- `name` (`str`): Tool name

**Returns:**
- `BaseTool`: The tool

**Raises:**
- `KeyError`: Tool not found

##### `has(name: str) -> bool`

Check if a tool exists.

**Parameters:**
- `name` (`str`): Tool name

**Returns:**
- `bool`: True if tool exists

##### `list_tools() -> list[str]`

List all tool names.

**Returns:**
- `list[str]`: Tool names

##### `get_all_schemas() -> list[dict]`

Get schemas for all tools.

**Returns:**
- `list[dict]`: Tool schemas

##### `execute(name: str, **params) -> ToolResult`

Execute a tool.

**Parameters:**
- `name` (`str`): Tool name
- `**params`: Tool parameters

**Returns:**
- `ToolResult`: Execution result

## Session

### InteractiveSession

Interactive REPL session manager.

```python
from oclawma.session.runner import InteractiveSession

session = InteractiveSession(
    provider=OllamaProvider(),
    model="qwen2.5:3b",
)
stats = await session.run()
```

#### Constructor

```python
InteractiveSession(
    provider: BaseProvider | None = None,
    model: str = "qwen2.5:3b",
    budget: ContextBudget | None = None,
    tool_registry: ToolRegistry | None = None,
    summary_config: SummaryConfig | None = None,
    auto_summarize: bool = True,
)
```

**Parameters:**
- `provider` (`BaseProvider`, optional): LLM provider
- `model` (`str`): Model name
- `budget` (`ContextBudget`, optional): Token budget
- `tool_registry` (`ToolRegistry`, optional): Tool registry
- `summary_config` (`SummaryConfig`, optional): Summarization config
- `auto_summarize` (`bool`): Enable auto-summarization

#### Methods

##### `async run() -> SessionStats`

Run the interactive session.

**Returns:**
- `SessionStats`: Session statistics

##### `print_summary() -> None`

Print session summary.

### SessionStats

Statistics for a session.

```python
from oclawma.session import SessionStats

stats = SessionStats(start_time=datetime.now())
```

#### Fields

| Field | Type | Description |
|-------|------|-------------|
| `start_time` | `datetime` | Session start time |
| `end_time` | `datetime | None` | Session end time |
| `message_count` | `int` | Total messages |
| `user_messages` | `int` | User messages |
| `assistant_messages` | `int` | Assistant messages |
| `tool_calls` | `int` | Tool call count |
| `tokens_used` | `int` | Total tokens used |
| `tool_results` | `list[str]` | Tool result summaries |

### ConversationHistory

Manages conversation messages.

```python
from oclawma.session import ConversationHistory

history = ConversationHistory()
```

#### Methods

##### `add_message(role: str, content: str, metadata: dict | None = None) -> None`

Add a message to history.

**Parameters:**
- `role` (`str`): Message role (`"system"`, `"user"`, `"assistant"`)
- `content` (`str`): Message content
- `metadata` (`dict`, optional): Additional metadata

##### `get_messages() -> list[SessionMessage]`

Get all messages.

**Returns:**
- `list[SessionMessage]`: Messages

##### `clear() -> None`

Clear all messages.

##### `estimate_tokens() -> int`

Estimate total tokens.

**Returns:**
- `int`: Estimated token count

##### `set_system_message(content: str) -> None`

Set the system message.

**Parameters:**
- `content` (`str`): System prompt

### SessionMessage

A single conversation message.

```python
from oclawma.session import SessionMessage

message = SessionMessage(
    role="user",
    content="Hello",
    timestamp=datetime.now(),
)
```

#### Fields

| Field | Type | Description |
|-------|------|-------------|
| `role` | `str` | Message role |
| `content` | `str` | Message content |
| `timestamp` | `datetime` | Message timestamp |
| `metadata` | `dict | None` | Additional metadata |

## Context Budget

### ContextBudget

Token budget management.

```python
from oclawma.context.budget import ContextBudget

budget = ContextBudget(limit=8192)
```

#### Constructor

```python
ContextBudget(
    limit: int = 8192,
    warning_threshold: float = 0.75,
    critical_threshold: float = 0.87,
)
```

**Parameters:**
- `limit` (`int`): Token limit
- `warning_threshold` (`float`): Warning threshold (0-1)
- `critical_threshold` (`float`): Critical threshold (0-1)

#### Properties

##### `usage_percent: float`

Current usage as percentage (0-1).

##### `remaining: int`

Remaining tokens.

##### `is_warning: bool`

True if above warning threshold.

##### `is_critical: bool`

True if above critical threshold.

#### Methods

##### `can_allocate(tokens: int) -> bool`

Check if tokens can be allocated.

**Parameters:**
- `tokens` (`int`): Tokens to allocate

**Returns:**
- `bool`: True if allocation possible

##### `allocate(tokens: int, strict: bool = False) -> None`

Allocate tokens from budget.

**Parameters:**
- `tokens` (`int`): Tokens to allocate
- `strict` (`bool`): Raise error if over budget

**Raises:**
- `BudgetExceededError`: If over budget and strict=True

##### `release(tokens: int) -> None`

Release tokens back to budget.

**Parameters:**
- `tokens` (`int`): Tokens to release

##### `reset() -> None`

Reset budget to zero used.

##### `visualize() -> str`

Get visual representation of budget.

**Returns:**
- `str`: ASCII progress bar

### BudgetExceededError

Exception raised when budget is exceeded.

```python
from oclawma.context.budget import BudgetExceededError

try:
    budget.allocate(1000, strict=True)
except BudgetExceededError as e:
    print(e.message)
```

## Exceptions

### ProviderError

Base exception for provider errors.

```python
from oclawma.providers.base import ProviderError
```

#### Fields

| Field | Type | Description |
|-------|------|-------------|
| `message` | `str` | Error message |
| `cause` | `Exception | None` | Original exception |

### SkillError

Base exception for skill errors.

```python
from oclawma.skills.base import SkillError
```

#### Fields

| Field | Type | Description |
|-------|------|-------------|
| `message` | `str` | Error message |
| `skill_name` | `str` | Skill name |
| `cause` | `Exception | None` | Original exception |

### Subclasses

- `SkillNotFoundError`: Skill doesn't exist
- `SkillLoadError`: Failed to load skill
- `SkillToolError`: Tool execution failed

## Type Hints

### CompletionRequest

```python
from oclawma.providers.base import CompletionRequest, Message

request = CompletionRequest(
    messages=[
        Message(role="system", content="You are helpful"),
        Message(role="user", content="Hello"),
    ],
    model="qwen2.5:3b",
    temperature=0.7,
    max_tokens=2000,
    stream=False,
)
```

### CompletionResponse

```python
from oclawma.providers.base import CompletionResponse, UsageStats

response = CompletionResponse(
    content="Hello! How can I help?",
    model="qwen2.5:3b",
    usage=UsageStats(
        prompt_tokens=20,
        completion_tokens=10,
        total_tokens=30,
    ),
)
```

## Constants

### Default Values

```python
DEFAULT_MODEL = "qwen2.5:3b"
DEFAULT_PROVIDER = "ollama"
DEFAULT_CONTEXT_LIMIT = 8192
DEFAULT_TEMPERATURE = 0.7
DEFAULT_TIMEOUT = 30
```

### Safety Levels

```python
SAFETY_STRICT = "strict"
SAFETY_NORMAL = "normal"
SAFETY_PERMISSIVE = "permissive"
```
