asyncdefthink(self) -> bool: """Process current state and decide next actions using tools""" # 处理下一步的提示词 if self.next_step_prompt: user_msg = Message.user_message(self.next_step_prompt) self.messages += [user_msg]
try: # Get response with tool options response = await self.llm.ask_tool( messages=self.messages, system_msgs=( [Message.system_message(self.system_prompt)] if self.system_prompt elseNone ), tools=self.available_tools.to_params(), tool_choice=self.tool_choices, ) except ValueError: raise except Exception as e: # Check if this is a RetryError containing TokenLimitExceeded ifhasattr(e, "__cause__") andisinstance(e.__cause__, TokenLimitExceeded): token_limit_error = e.__cause__ logger.error( f"🚨 Token limit error (from RetryError): {token_limit_error}" ) self.memory.add_message( Message.assistant_message( f"Maximum token limit reached, cannot continue execution: {str(token_limit_error)}" ) ) self.state = AgentState.FINISHED returnFalse raise self.tool_calls = tool_calls = ( response.tool_calls if response and response.tool_calls else [] ) content = response.content if response and response.content else"" # Log response info logger.info(f"✨ {self.name}'s thoughts: {content}") logger.info( f"🛠️ {self.name} selected {len(tool_calls) if tool_calls else0} tools to use" ) if tool_calls: logger.info( f"🧰 Tools being prepared: {[call.function.name for call in tool_calls]}" ) logger.info(f"🔧 Tool arguments: {tool_calls[0].function.arguments}") try: if response isNone: raise RuntimeError("No response received from the LLM") # Handle different tool_choices modes if self.tool_choices == ToolChoice.NONE: if tool_calls: logger.warning( f"🤔 Hmm, {self.name} tried to use tools when they weren't available!" ) if content: self.memory.add_message(Message.assistant_message(content)) returnTrue returnFalse # Create and add assistant message assistant_msg = ( Message.from_tool_calls(content=content, tool_calls=self.tool_calls) if self.tool_calls else Message.assistant_message(content) ) self.memory.add_message(assistant_msg) if self.tool_choices == ToolChoice.REQUIRED andnot self.tool_calls: returnTrue# Will be handled in act() # For 'auto' mode, continue with content if no commands but content exists if self.tool_choices == ToolChoice.AUTO and not self.tool_calls: returnbool(content) returnbool(self.tool_calls) except Exception as e: logger.error(f"🚨 Oops! The {self.name}'s thinking process hit a snag: {e}") self.memory.add_message( Message.assistant_message( f"Error encountered while processing: {str(e)}" ) ) returnFalse