coze_function_tools.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import types
  2. from typing import List, Dict
  3. import textwrap
  4. from pqai_agent.toolkit.function_tool import FunctionTool
  5. from pqai_agent.chat_service import Coze, TokenAuth, Message, CozeChat
  6. class FunctionToolFactory:
  7. @staticmethod
  8. def create_tool(bot_id: str, coze_client: CozeChat, func_name: str, func_desc: str) -> FunctionTool:
  9. """
  10. Create a FunctionTool for a specific Coze Bot.
  11. Args:
  12. bot_id (str): The ID of the Coze Bot.
  13. coze_client (CozeChat): The Coze client instance to interact with the bot.
  14. func_name (str): The name of the function to be used in the FunctionTool.
  15. func_desc (str): A description of the function to be used in the FunctionTool.
  16. Returns:
  17. FunctionTool: A FunctionTool wrapping the Coze Bot interaction.
  18. """
  19. func_doc = f"""
  20. {func_desc}
  21. Args:
  22. messages (List[Dict]): A list of messages to send to the bot.
  23. custom_variables (Dict): Custom variables for the bot.
  24. Returns:
  25. str: The final response from the bot.
  26. """
  27. func_doc = textwrap.dedent(func_doc).strip()
  28. def coze_func(messages: List[Dict], custom_variables: Dict = None) -> str:
  29. # ATTENTION:
  30. # custom_variables (Dict): Custom variables for the bot. THIS IS A TRICK.
  31. # THIS PARAMETER SHOULD NOT BE VISIBLE TO THE AGENT AND FILLED BY THE SYSTEM.
  32. # FIXME: Coze bot can return multimodal content.
  33. response = coze_client.create(
  34. bot_id=bot_id,
  35. user_id='agent_tool_call',
  36. messages=[Message.build_user_question_text(msg["text"]) for msg in messages],
  37. custom_variables=custom_variables
  38. )
  39. if not response:
  40. return 'Error in calling the function.'
  41. return response
  42. dynamic_function = types.FunctionType(
  43. coze_func.__code__,
  44. globals(),
  45. name=func_name,
  46. argdefs=coze_func.__defaults__,
  47. closure=coze_func.__closure__
  48. )
  49. dynamic_function.__doc__ = func_doc
  50. # Wrap the function in a FunctionTool
  51. return FunctionTool(dynamic_function)