| 45 | return e |
| 46 | |
| 47 | class ChatGPTFunction: |
| 48 | def __init__(self, model="gpt-3.5-turbo-16k-0613", openai_key=""): |
| 49 | self.model = model |
| 50 | self.conversation_history = [] |
| 51 | self.openai_key = openai_key |
| 52 | self.time = time.time() |
| 53 | self.TRY_TIME = 6 |
| 54 | |
| 55 | def add_message(self, message): |
| 56 | self.conversation_history.append(message) |
| 57 | |
| 58 | def change_messages(self,messages): |
| 59 | self.conversation_history = messages |
| 60 | |
| 61 | def display_conversation(self, detailed=False): |
| 62 | role_to_color = { |
| 63 | "system": "red", |
| 64 | "user": "green", |
| 65 | "assistant": "blue", |
| 66 | "function": "magenta", |
| 67 | } |
| 68 | print("before_print"+"*"*50) |
| 69 | for message in self.conversation_history: |
| 70 | print_obj = f"{message['role']}: {message['content']} " |
| 71 | if "function_call" in message.keys(): |
| 72 | print_obj = print_obj + f"function_call: {message['function_call']}" |
| 73 | print_obj += "" |
| 74 | print( |
| 75 | colored( |
| 76 | print_obj, |
| 77 | role_to_color[message["role"]], |
| 78 | ) |
| 79 | ) |
| 80 | print("end_print"+"*"*50) |
| 81 | |
| 82 | def parse(self,functions,process_id,key_pos=None,**args): |
| 83 | self.time = time.time() |
| 84 | conversation_history = self.conversation_history |
| 85 | for _ in range(self.TRY_TIME): |
| 86 | if _ != 0: |
| 87 | time.sleep(15) |
| 88 | if functions != []: |
| 89 | json_data = chat_completion_request( |
| 90 | self.openai_key, conversation_history, functions=functions,process_id=process_id, key_pos=key_pos,**args |
| 91 | ) |
| 92 | else: |
| 93 | json_data = chat_completion_request( |
| 94 | self.openai_key, conversation_history,process_id=process_id,key_pos=key_pos, **args |
| 95 | ) |
| 96 | try: |
| 97 | total_tokens = json_data['usage']['total_tokens'] |
| 98 | message = json_data["choices"][0]["message"] |
| 99 | if process_id == 0: |
| 100 | print(f"[process({process_id})]total tokens: {json_data['usage']['total_tokens']}") |
| 101 | |
| 102 | if "function_call" in message.keys() and "." in message["function_call"]["name"]: |
| 103 | message["function_call"]["name"] = message["function_call"]["name"].split(".")[-1] |
| 104 |
no outgoing calls
no test coverage detected