Skip to content

Python: [Bug]: Middleware type detection fails with from __future__ import annotations #8647

Description

@Aditya-XR

Description

_determine_middleware_type in _middleware.py detects the middleware type from the first parameter's annotation via annotation.__name__. When the module uses from __future__ import annotations (or the annotation is quoted), inspect.signature returns the annotation as a string, which has no __name__, so undecorated middleware that is correctly typed with ChatContext / AgentContext / FunctionInvocationContext is rejected.

Reproduction

from __future__ import annotations

from agent_framework import ChatContext
from agent_framework._middleware import categorize_middleware


async def my_mw(context: ChatContext, call_next) -> None:
    await call_next()


categorize_middleware([my_mw])

The same happens with Agent(client=..., middleware=[my_mw]).

Actual:

MiddlewareException: Cannot determine middleware type for function my_mw. Please either use @agent_middleware/@function_middleware/@chat_middleware decorators or specify parameter types (AgentContext, FunctionInvocationContext, or ChatContext).

Expected behavior

The middleware is categorized as chat middleware, same as without the __future__ import. The error message asks for exactly the annotation that is already there.

A side effect is that for decorated middleware in such modules, the decorator/annotation mismatch check is silently skipped.

This is similar to #8327, which fixed the same problem for @response_handler.

Environment

  • agent-framework-core: main (02bd1ba)
  • Python 3.13

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

agentsUsage: [Issues, PRs], Target: Single agentmiddlewareUsage: [Issues, PRs], Target: middleware related featurespythonUsage: [Issues, PRs], Target: PythonreproducedUsage: [Issues], Target: all issues that can be reproduced by the triage workflow

Type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions