How to return HTTP Get request response from models class in Django project

33 Views Asked by At

I am trying to Get a response from the OpenAi assistants API using a Django project.

I implement a model class inside models.py as such:

from django.db import models
from typing_extensions import override
from openai import AssistantEventHandler
from django.http import HttpResponse

# Create your models here.

class Eventhandler(models.Model,AssistantEventHandler):
class meta:
 managed = False

 @override
 def on_text_created(self, text) -> None:
  print(f"\nassistant > ", end="", flush=True)
  
 @override
 def on_text_delta(self, delta, snapshot):
  print(delta.value, end="", flush=True)
  
def on_tool_call_created(self, tool_call):
 print(f"\nassistant > {tool_call.type}\n", flush=True)

def on_tool_call_delta(self, delta, snapshot):
 if delta.type == 'code_interpreter':
  if delta.code_interpreter.input:
    print(delta.code_interpreter.input, end="", flush=True)
  if delta.code_interpreter.outputs:
    print(f"\n\noutput >", flush=True)
    for output in delta.code_interpreter.outputs:
      if output.type == "logs":
        print(f"\n{output.logs}", flush=True)

Now, what is important is that the Eventhandler class sends the response back to the client! I am a getting an exception of type: ValueError: The view theassistantcallerapp.views.callerview didn't return an HttpResponse object. It returned None instead. Now, callerview is the view inside views.py. It maps to the URL that will start the GET request to the OpenAi Assistants API.

This implementation I am using is for streaming responses. Now, here is the view insides views.py and NOTICE HOW THE EVENTHANDLER CLASS IS USED

#inside views.py
# this is  callerview(request, paramm):

thread = client.beta.threads.create()

message = client.beta.threads.messages.create( thread_id=thread.id,role="user",
        content=otro)   

myeventhandler = Eventhandler() <-----------NOTICE HERE!!!!!!!!!!!!!

with client.beta.threads.runs.create_and_stream(
thread_id=thread.id,
assistant_id="asst_dddfffggg",
instructions="Please address the user as Donkey Kong. The user has a premium account.",
event_handler=myeventhandler,  <-----------NOTICE HERE!!!!!!!!!!!!!
   ) as stream:
  stream.until_done()

How can I make the class Eventhandler inside models.py return the response from the OpenAi Assistants API ?

0

There are 0 best solutions below