|
3 | 3 | from functools import partial |
4 | 4 | from typing import TYPE_CHECKING, Any, ClassVar, cast |
5 | 5 |
|
6 | | -from pydantic import BaseModel, Field |
| 6 | +from pydantic import BaseModel, Field, ValidationError |
7 | 7 |
|
8 | 8 | from aviary.message import MalformedMessageError, Message |
9 | 9 |
|
@@ -103,24 +103,32 @@ async def __call__( |
103 | 103 |
|
104 | 104 | if (num_choices := len(model_response.choices)) != 1: |
105 | 105 | raise MalformedMessageError( |
106 | | - f"Expected one choice in LiteLLM model response, got {num_choices}" |
| 106 | + f"Expected one choice in model response, got {num_choices}" |
107 | 107 | f" choices, full response was {model_response}." |
108 | 108 | ) |
109 | 109 | choice = model_response.choices[0] |
110 | 110 | if choice.finish_reason not in expected_finish_reason: |
111 | 111 | raise MalformedMessageError( |
112 | | - f"Expected a finish reason in {expected_finish_reason} in LiteLLM" |
| 112 | + f"Expected a finish reason in {expected_finish_reason} in" |
113 | 113 | f" model response, got finish reason {choice.finish_reason!r}, full" |
114 | | - f" response was {model_response} and tool choice was {tool_choice}." |
| 114 | + f" response was {model_response} and tool choice was {tool_choice!r}." |
115 | 115 | ) |
116 | 116 | usage = model_response.usage |
117 | | - selection = ToolRequestMessage( |
118 | | - **choice.message.model_dump(), |
119 | | - info={ |
120 | | - "usage": (usage.prompt_tokens, usage.completion_tokens), |
121 | | - "model": self._model_name, |
122 | | - }, |
123 | | - ) |
| 117 | + try: |
| 118 | + selection = ToolRequestMessage( |
| 119 | + **choice.message.model_dump(), |
| 120 | + info={ |
| 121 | + "usage": (usage.prompt_tokens, usage.completion_tokens), |
| 122 | + "model": self._model_name, |
| 123 | + }, |
| 124 | + ) |
| 125 | + except ValidationError as exc: |
| 126 | + raise MalformedMessageError( |
| 127 | + f"Failed to convert model response's message {choice.message}" |
| 128 | + f" into a tool request message." |
| 129 | + f" Got finish reason {choice.finish_reason!r}, full" |
| 130 | + f" response was {model_response} and tool choice was {tool_choice!r}." |
| 131 | + ) from exc |
124 | 132 | if self._ledger is not None: |
125 | 133 | self._ledger.messages.append(selection) |
126 | 134 | return selection |
|
0 commit comments