Hi!
After calling an agent (via .invoke()) with a bound middleware and structured output, I get an error:
Invalid response from “wrapModelCall” in middleware “MiddlewareName”: expected AIMessage, got object.
Because of this, I have to do something like this at the end of each middleware.
Maybe I’m doing something wrong? Please share your advice on how to avoid this.
Example middleware
....
if (AIMessage.isInstance(response)) {
return response;
}
if (response && typeof response === 'object') {
const messages = Array.isArray(
(response as { messages?: unknown }).messages
)
? (response as { messages: unknown[] }).messages
: undefined;
const lastMessage = messages?.at(-1);
if (lastMessage && AIMessage.isInstance(lastMessage)) {
if ('structuredResponse' in response) {
Object.assign(lastMessage, {
structuredResponse: (
response as { structuredResponse: unknown }
).structuredResponse,
messages,
});
}
return lastMessage;
}
}
....