1- import os
2- import json
3- import logging
4-
51from rest_framework .response import Response
62from rest_framework import viewsets , status
73from rest_framework .decorators import action
139import requests
1410from openai import OpenAI
1511import tiktoken
12+ import os
13+ import json
14+ import logging
1615from django .views .decorators .csrf import csrf_exempt
17-
1816from .models import Conversation , Message
1917from .serializers import ConversationSerializer
2018from ...services .tools .tools import tools , execute_tool
@@ -69,7 +67,6 @@ def get_tokens(string: str, encoding_name: str) -> str:
6967
7068class OpenAIAPIException (APIException ):
7169 """Custom exception for OpenAI API errors."""
72-
7370 status_code = status .HTTP_500_INTERNAL_SERVER_ERROR
7471 default_detail = "An error occurred while communicating with the OpenAI API."
7572 default_code = "openai_api_error"
@@ -98,29 +95,26 @@ def destroy(self, request, *args, **kwargs):
9895 self .perform_destroy (instance )
9996 return Response (status = status .HTTP_204_NO_CONTENT )
10097
101- @action (detail = True , methods = [" post" ])
98+ @action (detail = True , methods = [' post' ])
10299 def continue_conversation (self , request , pk = None ):
103100 conversation = self .get_object ()
104- user_message = request .data .get (" message" )
105- page_context = request .data .get (" page_context" )
101+ user_message = request .data .get (' message' )
102+ page_context = request .data .get (' page_context' )
106103
107104 if not user_message :
108105 return Response ({"error" : "Message is required" }, status = 400 )
109106
110107 # Save user message
111- Message .objects .create (
112- conversation = conversation , content = user_message , is_user = True
113- )
108+ Message .objects .create (conversation = conversation ,
109+ content = user_message , is_user = True )
114110
115111 # Get ChatGPT response
116112 chatgpt_response = self .get_chatgpt_response (
117- conversation , user_message , page_context
118- )
113+ conversation , user_message , page_context )
119114
120115 # Save ChatGPT response
121- Message .objects .create (
122- conversation = conversation , content = chatgpt_response , is_user = False
123- )
116+ Message .objects .create (conversation = conversation ,
117+ content = chatgpt_response , is_user = False )
124118
125119 # Generate or update title if it's the first message or empty
126120 if conversation .messages .count () <= 2 or not conversation .title :
@@ -129,31 +123,25 @@ def continue_conversation(self, request, pk=None):
129123
130124 return Response ({"response" : chatgpt_response , "title" : conversation .title })
131125
132- @action (detail = True , methods = [" patch" ])
126+ @action (detail = True , methods = [' patch' ])
133127 def update_title (self , request , pk = None ):
134128 conversation = self .get_object ()
135- new_title = request .data .get (" title" )
129+ new_title = request .data .get (' title' )
136130
137131 if not new_title :
138- return Response (
139- {"error" : "New title is required" }, status = status .HTTP_400_BAD_REQUEST
140- )
132+ return Response ({"error" : "New title is required" }, status = status .HTTP_400_BAD_REQUEST )
141133
142134 conversation .title = new_title
143135 conversation .save ()
144136
145- return Response (
146- {"status" : "Title updated successfully" , "title" : conversation .title }
147- )
137+ return Response ({"status" : "Title updated successfully" , "title" : conversation .title })
148138
149139 def get_chatgpt_response (self , conversation , user_message , page_context = None ):
150140 client = OpenAI (api_key = os .environ ["OPENAI_API_KEY" ])
151- messages = [
152- {
153- "role" : "system" ,
154- "content" : "You are a knowledgeable assistant. Balancer is a powerful tool for selecting bipolar medication for patients. We are open-source and available for free use. Your primary role is to assist licensed clinical professionals with information related to Balancer and bipolar medication selection. If applicable, use the supplied tools to assist the professional." ,
155- }
156- ]
141+ messages = [{
142+ "role" : "system" ,
143+ "content" : "You are a knowledgeable assistant. Balancer is a powerful tool for selecting bipolar medication for patients. We are open-source and available for free use. Your primary role is to assist licensed clinical professionals with information related to Balancer and bipolar medication selection. If applicable, use the supplied tools to assist the professional."
144+ }]
157145
158146 if page_context :
159147 context_message = f"If applicable, please use the following content to ask questions. If not applicable, please answer to the best of your ability: { page_context } "
@@ -169,7 +157,7 @@ def get_chatgpt_response(self, conversation, user_message, page_context=None):
169157 model = "gpt-3.5-turbo" ,
170158 messages = messages ,
171159 tools = tools ,
172- tool_choice = "auto" ,
160+ tool_choice = "auto"
173161 )
174162
175163 response_message = response .choices [0 ].message
@@ -178,41 +166,37 @@ def get_chatgpt_response(self, conversation, user_message, page_context=None):
178166 tool_calls = response_message .model_dump ().get ("tool_calls" , [])
179167
180168 if not tool_calls :
181- return response_message [" content" ]
169+ return response_message [' content' ]
182170
183171 # Handle tool calls
184172 # Add the assistant's message with tool calls to the conversation
185- messages .append (
186- {
187- "role" : "assistant" ,
188- "content" : response_message .content or "" ,
189- "tool_calls" : tool_calls ,
190- }
191- )
173+ messages .append ({
174+ "role" : "assistant" ,
175+ "content" : response_message .content or "" ,
176+ "tool_calls" : tool_calls
177+ })
192178
193179 # Process each tool call
194180 for tool_call in tool_calls :
195- tool_call_id = tool_call ["id" ]
196- tool_function_name = tool_call [" function" ][ " name" ]
181+ tool_call_id = tool_call ['id' ]
182+ tool_function_name = tool_call [' function' ][ ' name' ]
197183 tool_arguments = json .loads (
198- tool_call ["function" ].get ("arguments" , "{}" )
199- )
184+ tool_call ['function' ].get ('arguments' , '{}' ))
200185
201186 # Execute the tool
202187 results = execute_tool (tool_function_name , tool_arguments )
203188
204189 # Add the tool response message
205- messages .append (
206- {
207- "role" : "tool" ,
208- "content" : str (results ), # Convert results to string
209- "tool_call_id" : tool_call_id ,
210- }
211- )
190+ messages .append ({
191+ "role" : "tool" ,
192+ "content" : str (results ), # Convert results to string
193+ "tool_call_id" : tool_call_id
194+ })
212195
213196 # Final API call with tool results
214197 final_response = client .chat .completions .create (
215- model = "gpt-3.5-turbo" , messages = messages
198+ model = "gpt-3.5-turbo" ,
199+ messages = messages
216200 )
217201 return final_response .choices [0 ].message .content
218202 except OpenAI .error .OpenAIError as e :
@@ -231,12 +215,9 @@ def generate_title(self, conversation):
231215 response = client .chat .completions .create (
232216 model = "gpt-3.5-turbo" ,
233217 messages = [
234- {
235- "role" : "system" ,
236- "content" : "You are a helpful assistant that generates short, descriptive titles." ,
237- },
238- {"role" : "user" , "content" : prompt },
239- ],
218+ {"role" : "system" , "content" : "You are a helpful assistant that generates short, descriptive titles." },
219+ {"role" : "user" , "content" : prompt }
220+ ]
240221 )
241222
242223 return response .choices [0 ].message .content .strip ()
0 commit comments