refactor: improve error handling in knowledge query processing

This commit refactors the knowledge query handling in the Agent class by changing the order of checks for LLM compatibility. It now logs a warning and emits a failure event if the LLM is not an instance of BaseLLM before attempting to call the LLM. Additionally, the task_prompt attribute has been removed from the KnowledgeQueryFailedEvent, simplifying the event structure.
This commit is contained in:
lorenzejay
2025-05-06 20:42:23 -07:00
parent b9af25f434
commit 55ed9b366f
2 changed files with 40 additions and 31 deletions

View File

@@ -622,36 +622,46 @@ class Agent(BaseAgent):
task_prompt=task_prompt task_prompt=task_prompt
) )
rewriter_prompt = self.i18n.slice("knowledge_search_query_system_prompt") rewriter_prompt = self.i18n.slice("knowledge_search_query_system_prompt")
if isinstance(self.llm, BaseLLM): if not isinstance(self.llm, BaseLLM):
try: self._logger.log(
rewritten_query = self.llm.call( "warning",
[ f"Knowledge search query failed: LLM for agent '{self.role}' is not an instance of BaseLLM",
{ )
"role": "system", crewai_event_bus.emit(
"content": rewriter_prompt, self,
}, event=KnowledgeQueryFailedEvent(
{"role": "user", "content": query}, agent=self,
] error="LLM is not compatible with knowledge search queries",
) ),
crewai_event_bus.emit( )
self, return None
event=KnowledgeQueryCompletedEvent(
query=query, try:
agent=self, rewritten_query = self.llm.call(
), [
) {
return rewritten_query "role": "system",
except Exception as e: "content": rewriter_prompt,
crewai_event_bus.emit( },
self, {"role": "user", "content": query},
event=KnowledgeQueryFailedEvent( ]
task_prompt=task_prompt, )
agent=self, crewai_event_bus.emit(
error=str(e), self,
), event=KnowledgeQueryCompletedEvent(
) query=query,
return None agent=self,
else: ),
)
return rewritten_query
except Exception as e:
crewai_event_bus.emit(
self,
event=KnowledgeQueryFailedEvent(
agent=self,
error=str(e),
),
)
return None return None
def kickoff( def kickoff(

View File

@@ -34,7 +34,6 @@ class KnowledgeQueryStartedEvent(BaseEvent):
class KnowledgeQueryFailedEvent(BaseEvent): class KnowledgeQueryFailedEvent(BaseEvent):
"""Event emitted when a knowledge query fails.""" """Event emitted when a knowledge query fails."""
task_prompt: str
type: str = "knowledge_query_failed" type: str = "knowledge_query_failed"
agent: BaseAgent agent: BaseAgent
error: str error: str