63 lines
2.3 KiB
Python
63 lines
2.3 KiB
Python
from django.db import models
|
|
from account.models import User
|
|
from product.models import ProductModel, DollorModel
|
|
from django.conf import settings
|
|
import openai
|
|
from time import sleep
|
|
from product.serializers import DynamicProductSerializer
|
|
|
|
|
|
ASSISTANT_ID = 'asst_1wOnCKncEHkOfp0FjOIz4Xkp'
|
|
class ProductChatModel(models.Model):
|
|
user = models.ForeignKey(User, on_delete=models.CASCADE)
|
|
product = models.ForeignKey(ProductModel, on_delete=models.CASCADE)
|
|
thread = models.CharField(max_length=400, blank=True, null=True)
|
|
|
|
class Meta:
|
|
unique_together = ['user', 'product']
|
|
verbose_name = 'جت محصلول و کاربر'
|
|
verbose_name_plural = 'چت های محصلول کاربر'
|
|
|
|
def __str__(self):
|
|
return f'{self.user} - {self.product}'
|
|
|
|
def save(self, *args, **kwargs):
|
|
if not self.thread:
|
|
client = openai.OpenAI(api_key=settings.OPENAI_API_KEY)
|
|
dollor_object, _ = DollorModel.objects.get_or_create(unique_filed='unique')
|
|
dollor_price = dollor_object.price
|
|
product_json = DynamicProductSerializer(instance=self.product, context={'dollor_price': dollor_price, 'view_type': 'chat'}).data
|
|
try:
|
|
|
|
thread = client.beta.threads.create(
|
|
messages=[
|
|
{
|
|
"role": "user",
|
|
#TODO update first message
|
|
"content": f"this is the start of the chat greet the user this chat is about the product with given detail: {product_json}",
|
|
}
|
|
]
|
|
)
|
|
|
|
|
|
run = client.beta.threads.runs.create(
|
|
thread_id=thread.id,
|
|
assistant_id=ASSISTANT_ID
|
|
)
|
|
|
|
|
|
while run.status != "completed":
|
|
run = client.beta.threads.runs.retrieve(
|
|
thread_id=thread.id,
|
|
run_id=run.id
|
|
)
|
|
sleep(1)
|
|
|
|
|
|
self.thread = thread.id
|
|
|
|
except Exception as e:
|
|
print(f'error in chat class: {e}')
|
|
raise ValueError(f"Error creating OpenAI thread: {e}")
|
|
|
|
super().save(*args, **kwargs) |