| 1 | import json |
| 2 | from collections.abc import Mapping |
| 3 | from dataclasses import dataclass |
| 4 | from pprint import pformat |
| 5 | |
| 6 | from openai.types.chat import ChatCompletionMessageToolCall |
| 7 | from openai.types.chat.chat_completion_message_tool_call import ( |
| 8 | Function as OpenaiFunction, |
| 9 | ) |
| 10 | |
| 11 | |
| 12 | @dataclass |
| 13 | class MethodId: |
| 14 | class_name: str |
| 15 | method_name: str |
| 16 | |
| 17 | def __str__(self): |
| 18 | if self.class_name: |
| 19 | return f"{self.class_name}.{self.method_name}" |
| 20 | return self.method_name |
| 21 | |
| 22 | def __hash__(self): |
| 23 | return hash((self.class_name, self.method_name)) |
| 24 | |
| 25 | |
| 26 | class FunctionCallIntent: |
| 27 | """An intent to call a tool function. |
| 28 | |
| 29 | This object created from OpenAI API response. |
| 30 | """ |
| 31 | |
| 32 | def __init__( |
| 33 | self, |
| 34 | func_name: str, |
| 35 | arguments: Mapping[str, str], |
| 36 | openai_func: OpenaiFunction | None, |
| 37 | ): |
| 38 | self.func_name = func_name |
| 39 | self.arg_values = dict() |
| 40 | self.arg_values.update(arguments) |
| 41 | # record the original openai function object, |
| 42 | # which is used when we want tell the model that it has |
| 43 | # previously called this function/tool |
| 44 | self.openai_func = openai_func or OpenaiFunction( |
| 45 | arguments=json.dumps(arguments), name=func_name |
| 46 | ) |
| 47 | |
| 48 | def __str__(self): |
| 49 | return f"Call function `{self.func_name}` with arguments {self.arg_values}." |
| 50 | |
| 51 | def to_dict(self): |
| 52 | return {"func_name": self.func_name, "arguments": self.arg_values} |
| 53 | |
| 54 | def to_dict_with_result(self, call_ok: bool): |
| 55 | return { |
| 56 | "func_name": self.func_name, |
| 57 | "arguments": self.arg_values, |
| 58 | "call_ok": call_ok, |
| 59 | } |
| 60 | |
| 61 | |
| 62 | class MessageThread: |
| 63 | """ |
| 64 | Represents a thread of conversation with the model. |
| 65 | Abstrated into a class so that we can dump this to a file at any point. |
| 66 | """ |
| 67 | |
| 68 | def __init__(self, messages=None): |
| 69 | self.messages: list[dict] = messages or [] |
| 70 | |
| 71 | def add(self, role: str, message: str): |
| 72 | """ |
| 73 | Add a new message to the thread. |
| 74 | Args: |
| 75 | message (str): The content of the new message. |
| 76 | role (str): The role of the new message. |
| 77 | """ |
| 78 | self.messages.append({"role": role, "content": message}) |
| 79 | |
| 80 | def add_system(self, message: str): |
| 81 | self.messages.append({"role": "system", "content": message}) |
| 82 | |
| 83 | def add_user(self, message: str): |
| 84 | self.messages.append({"role": "user", "content": message}) |
| 85 | |
| 86 | def add_tool(self, message: str, tool_call_id: str): |
| 87 | m = {"role": "tool", "content": message, "tool_call_id": tool_call_id} |
| 88 | self.messages.append(m) |
| 89 | |
| 90 | def add_model( |
| 91 | self, message: str | None, tools: list[ChatCompletionMessageToolCall] |
| 92 | ): |
| 93 | # let's serialize tools into json first |
| 94 | json_tools = [] |
| 95 | for tool in tools: |
| 96 | this_tool_dict = {} |
| 97 | this_tool_dict["id"] = tool.id |
| 98 | this_tool_dict["type"] = tool.type |
| 99 | # now serialize function as well |
| 100 | func_obj: OpenaiFunction = tool.function |
| 101 | func_args: str = func_obj.arguments |
| 102 | func_name: str = func_obj.name |
| 103 | this_tool_dict["function"] = {"name": func_name, "arguments": func_args} |
| 104 | json_tools.append(this_tool_dict) |
| 105 | |
| 106 | if json_tools == []: |
| 107 | # there is no tool calls from the model last time, |
| 108 | # the best we could do is to return the generated text |
| 109 | self.messages.append({"role": "assistant", "content": message}) |
| 110 | else: |
| 111 | self.messages.append( |
| 112 | {"role": "assistant", "content": None, "tool_calls": json_tools} |
| 113 | ) |
| 114 | |
| 115 | def to_msg(self) -> list[dict]: |
| 116 | """ |
| 117 | Convert to the format to be consumed by the model. |
| 118 | Returns: |
| 119 | List[Dict]: The message thread. |
| 120 | """ |
| 121 | return self.messages |
| 122 | |
| 123 | def __str__(self): |
| 124 | return pformat(self.messages, width=160, sort_dicts=False) |
| 125 | |
| 126 | def save_to_file(self, file_path: str): |
| 127 | """ |
| 128 | Save the current state of the message thread to a file. |
| 129 | Args: |
| 130 | file_path (str): The path to the file. |
| 131 | """ |
| 132 | with open(file_path, "w") as f: |
| 133 | json.dump(self.messages, f, indent=4) |
| 134 | |
| 135 | def get_round_number(self) -> int: |
| 136 | """ |
| 137 | From the current message history, decide how many rounds have been completed. |
| 138 | """ |
| 139 | completed_rounds = 0 |
| 140 | for message in self.messages: |
| 141 | if message["role"] == "assistant": |
| 142 | completed_rounds += 1 |
| 143 | return completed_rounds |
| 144 | |
| 145 | @classmethod |
| 146 | def load_from_file(cls, file_path: str): |
| 147 | """ |
| 148 | Load the message thread from a file. |
| 149 | Args: |
| 150 | file_path (str): The path to the file. |
| 151 | Returns: |
| 152 | MessageThread: The message thread. |
| 153 | """ |
| 154 | with open(file_path) as f: |
| 155 | messages = json.load(f) |
| 156 | return cls(messages) |