---
id: cubepi-middleware
title: cubepi.middleware
sidebar_position: 4
hide_table_of_contents: false
---

# `cubepi.middleware`

### Middleware {#middleware}

_class_


[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/middleware/base.py#L23)


**Methods**

#### `transform_context` {#middleware-transform-context}

```python
transform_context(messages: list, *, signal = None) -> list
```

[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/middleware/base.py#L24)


#### `convert_to_llm` {#middleware-convert-to-llm}

```python
convert_to_llm(messages: list) -> list
```

[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/middleware/base.py#L27)


#### `before_tool_call` {#middleware-before-tool-call}

```python
before_tool_call(ctx: Any, *, signal = None) -> Any
```

[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/middleware/base.py#L30)


#### `after_tool_call` {#middleware-after-tool-call}

```python
after_tool_call(ctx: Any, *, signal = None) -> Any
```

[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/middleware/base.py#L33)


#### `transform_system_prompt` {#middleware-transform-system-prompt}

```python
transform_system_prompt(system_prompt: str, *, signal = None) -> str
```

[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/middleware/base.py#L36)


#### `should_stop_after_turn` {#middleware-should-stop-after-turn}

```python
should_stop_after_turn(ctx: Any) -> bool
```

[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/middleware/base.py#L44)


#### `after_model_response` {#middleware-after-model-response}

```python
after_model_response(response: AssistantMessage, ctx: Any, *, signal: Any = None) -> TurnAction | None
```

[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/middleware/base.py#L47)



### TurnAction {#turnaction}

_class_

```python
TurnAction(self, response: AssistantMessage | None = None, inject_messages: list[Message] = list(), decision: Literal['natural', 'stop', 'loop_to_model'] = 'natural')
```

Directs the agent loop's next step after a model response.

Composition (chain): each middleware sees previous middleware's
TurnAction. Last middleware's value wins for response and decision.
inject_messages concatenates across the chain.

[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/middleware/base.py#L9)


**Attributes**

- `response`: `AssistantMessage | None`
- `inject_messages`: `list[Message]`
- `decision`: `Literal['natural', 'stop', 'loop_to_model']`


### compose_middleware {#compose-middleware}

_function_

```python
compose_middleware(middlewares: list[Middleware]) -> dict[str, Callable]
```


[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/middleware/base.py#L63)



<!-- GENERATED by build_api_reference.py — DO NOT EDIT -->