Files
2026-05-12 09:47:45 +03:30

64 lines
2.3 KiB
Python

from django.db import models
from account.models import User
import logging
logger = logging.getLogger(__name__)
from product.models import ProductModel
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, verbose_name='کاربر')
product = models.ForeignKey(ProductModel, on_delete=models.CASCADE, verbose_name='محصول')
thread = models.CharField(max_length=400, blank=True, null=True, verbose_name='ترد هوش مصنوعی')
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)
product_json = DynamicProductSerializer(instance=self.product, context={'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:
logger.error(f'error in chat class: {e}')
raise ValueError(f"Error creating OpenAI thread: {e}")
super().save(*args, **kwargs)