I am trying to het a response from openai. This works fine when I run the file form the CLI.(see code below) Because it prints the response to the command line.
from django.views.decorators.csrf import csrf_exempt
from llama_index import GPTSimpleVectorIndex, SimpleDirectoryReader
import os
os.environ["OPENAI_API_KEY"] = "<MY_OPENAI_API_KEY>"
@csrf_exempt
def ask_ai( prompt ):
print( prompt )
documents = SimpleDirectoryReader("data").load_data()
index = GPTSimpleVectorIndex.from_documents( documents )
response = index.query( prompt )
print( response )
ask_ai("<my prompt>")
However, when I use Django to call the mostly the same but slightly modified file(see below) the response is always printed as "None" and returned as null.
from django.views.decorators.csrf import csrf_exempt
from llama_index import GPTSimpleVectorIndex, SimpleDirectoryReader
import os
os.environ["OPENAI_API_KEY"] = "<MY_OPENAI_API_KEY>"
@csrf_exempt
def ask_ai( prompt ):
print( prompt )
documents = SimpleDirectoryReader("data").load_data()
index = GPTSimpleVectorIndex.from_documents( documents )
response = index.query( prompt )
print( response )
return response.response
What can I do to make it print/return the response for the API call in the same way that it does for the CLI?
I have tried:
- async/await. This returns an error. TypeError: Object of type coroutine is not JSON serializable
- adding a second function with async await applied that returns the query response to ask_ai which then returns it to the requester but this results in the same type error
- printing/returning as string str(response)
- returning as json
I was hoping to have the code print and return the expected response to index.query(prompt)