message_util.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 += tool_call_delta.function.arguments
  34. else:
  35. tool_call = ChatCompletionMessageToolCall(
  36. id=tool_call_delta.id,
  37. function=Function(name=tool_call_delta.function.name, arguments=tool_call_delta.function.arguments),
  38. type=tool_call_delta.type,
  39. )
  40. tool_calls.append(tool_call)