message_util.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """
  2. This module provides utility functions for working with messages in the OpenAI API.
  3. Functions:
  4. - new_message(role: str, content: str) -> dict: Creates a new message with the specified role and content.
  5. - system_message(content: str) -> dict: Creates a system message with the specified content.
  6. - user_message(content: str) -> dict: Creates a user message with the specified content.
  7. - assistant_message(content: str) -> dict: Creates an assistant message with the specified content.
  8. - tool_calls(tool_calls) -> dict: Creates a message with assistant tool calls.
  9. - tool_call_result(id, content) -> dict: Creates a tool call result message with the specified ID and content.
  10. - is_tool_call(message: ChatCompletionMessage) -> bool: Checks if a message is a tool call.
  11. """
  12. from openai.types.chat import ChatCompletionMessage, ChatCompletionMessageToolCall
  13. from openai.types.chat.chat_completion_message_tool_call import Function
  14. def new_message(role: str, content: str):
  15. if role != "user" and role != "system" and role != "assistant":
  16. raise ValueError(f"Invalid role {role}")
  17. return {"role": role, "content": content}
  18. def system_message(content: str):
  19. return new_message("system", content)
  20. def user_message(content: str):
  21. return new_message("user", content)
  22. def assistant_message(content: str):
  23. return new_message("assistant", content)
  24. def tool_calls(tool_calls):
  25. return {"role": "assistant", "tool_calls": tool_calls}
  26. def tool_call_result(id, content):
  27. return {"role": "tool", "tool_call_id": id, "content": content}
  28. def is_tool_call(message: ChatCompletionMessage) -> bool:
  29. return bool(message.tool_calls)
  30. def merge_tool_call_delta(tool_calls, tool_call_delta):
  31. if len(tool_calls) - 1 >= tool_call_delta.index:
  32. tool_call = tool_calls[tool_call_delta.index]
  33. tool_call.function.arguments += (
  34. ""
  35. if tool_call_delta.function.arguments is None
  36. else tool_call_delta.function.arguments
  37. )
  38. else:
  39. tool_call = ChatCompletionMessageToolCall(
  40. id=tool_call_delta.id,
  41. function=Function(
  42. name=tool_call_delta.function.name,
  43. arguments=tool_call_delta.function.arguments,
  44. ),
  45. type=tool_call_delta.type,
  46. )
  47. tool_calls.append(tool_call)
  48. print(
  49. "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaatttttttttttttttttttttttttttttmmmmmmmmmmmmmmmmmmmmmmmmmm"
  50. )
  51. print(tool_calls)