mirascope.integrations.middleware
middleware_factory
Function middleware_factory
A factory method for creating middleware decorators.
Example:
from mirascope.core import openai, prompt_template
from mirascope.integrations import middleware_factory
def with_saving():
"""Saves some data after a Mirascope call."""
return middleware_factory(
custom_context_manager=custom_context_manager,
custom_decorator=custom_decorator,
handle_call_response=handle_call_response,
handle_call_response_async=handle_call_response_async,
handle_stream=handle_stream,
handle_stream_async=handle_stream_async,
handle_response_model=handle_response_model,
handle_response_model_async=handle_response_model_async,
handle_structured_stream=handle_structured_stream,
handle_structured_stream_async=handle_structured_stream_async,
handle_error_async=handle_error_async,
handle_error=handle_error,
)
@with_saving()
@openai.call("gpt-4o-mini")
def recommend_book(genre: str) -> str:
return f"Recommend a {genre} book"
response = recommend_book("fantasy") # `with_saving` automatically run
print(response.content)
Parameters
Name | Type | Description |
---|---|---|
custom_context_manager= default_context_manager | (SyncFunc | AsyncFunc) => AbstractContextManager[_T] | - |
custom_decorator= None | Callable | None | - |
handle_call_response= None | (BaseCallResponse, SyncFunc | AsyncFunc, _T | None) => None | None | - |
handle_call_response_async= None | (BaseCallResponse, SyncFunc | AsyncFunc, _T | None) => Awaitable[None] | None | - |
handle_stream= None | (BaseStream, SyncFunc | AsyncFunc, _T | None) => None | None | - |
handle_stream_async= None | (BaseStream, SyncFunc | AsyncFunc, _T | None) => Awaitable[None] | None | - |
handle_response_model= None | (ResponseModel, SyncFunc | AsyncFunc, _T | None) => None | None | - |
handle_response_model_async= None | (ResponseModel, SyncFunc | AsyncFunc, _T | None) => Awaitable[None] | None | - |
handle_structured_stream= None | (BaseStructuredStream, SyncFunc | AsyncFunc, _T | None) => None | None | - |
handle_structured_stream_async= None | (BaseStructuredStream, SyncFunc | AsyncFunc, _T | None) => Awaitable[None] | None | - |
handle_error= None | (Exception, SyncFunc | AsyncFunc, _T | None) => Any | None | - |
handle_error_async= None | (Exception, SyncFunc | AsyncFunc, _T | None) => Awaitable[Any] | None | - |
Returns
Type | Description |
---|---|
(() => _R) => () => _R | - |