1
import json
import openai
# Converts OpenAI's AI History to a JSON file
def AIHistoryToJSON(AIHistory):
JSONarray = {}
for history_index in range(len(AIHistory)):
if AIHistory[history_index].__class__ == dict:
JSONarray[f"{history_index}"] = {
"role": AIHistory[history_index]["role"],
"content": AIHistory[history_index]["content"],
}
if "tool_call_id" in AIHistory[history_index]:
JSONarray[f"{history_index}"]["tool_call_id"] = AIHistory[
history_index
]["tool_call_id"]
else:
JSONarray[f"{history_index}"] = {
"role": AIHistory[history_index].role,
"content": AIHistory[history_index].content,
}
if hasattr(AIHistory[history_index], "tool_calls"):
tool_calls = {}
for tool_index in range(len(AIHistory[history_index].tool_calls)):
tool_call = AIHistory[history_index].tool_calls[tool_index]
tool_calls[f"{tool_index}"] = {
"id": tool_call.id,
"function": {
"arguments": tool_call.function.arguments,
"name": tool_call.function.name,
},
"type": tool_call.type,
"index": tool_call.index,
}
JSONarray[f"{history_index}"]["tool_calls"] = tool_calls
return json.dumps(JSONarray)
# Converts the dictionary to an array structure that OpenAI understands to be its history
def JSONToAIHistory(JSONfile):
AIHistory = []
for history_index in JSONfile:
if "tool_calls" not in JSONfile[history_index]:
AIHistory.append(
{
"role": JSONfile[history_index]["role"],
"content": JSONfile[history_index]["content"],
}
)
if "tool_call_id" in JSONfile[history_index]:
AIHistory[-1]["tool_call_id"] = JSONfile[history_index]["tool_call_id"]
else:
tool_calls = []
for tool_index in JSONfile[history_index]["tool_calls"]:
tool_call = JSONfile[history_index]["tool_calls"][tool_index]
tool_calls.append(
openai.types.chat.chat_completion_message_tool_call.ChatCompletionMessageToolCall(
id=tool_call["id"],
function=openai.types.chat.chat_completion_message_tool_call.Function(
arguments=tool_call["function"]["arguments"],
name=tool_call["function"]["name"],
),
type=tool_call["type"],
index=tool_call["index"],
)
)
AIHistory.append(
openai.types.chat.chat_completion_message.ChatCompletionMessage(
role=JSONfile[history_index]["role"],
content=JSONfile[history_index]["content"],
tool_calls=tool_calls,
)
)
return AIHistory
For immediate assistance, please email our customer support: [email protected]