add chat
This commit is contained in:
0
prompt/__init__.py
Normal file
0
prompt/__init__.py
Normal file
15
prompt/admin.py
Normal file
15
prompt/admin.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from django.contrib import admin
|
||||
from .models import Conversation, Message
|
||||
|
||||
|
||||
class MessageInline(admin.TabularInline):
|
||||
model = Message
|
||||
extra = 0
|
||||
readonly_fields = ("role", "content", "code_html", "code_css", "code_js", "created")
|
||||
|
||||
|
||||
@admin.register(Conversation)
|
||||
class ConversationAdmin(admin.ModelAdmin):
|
||||
list_display = ("user", "task", "is_active", "created")
|
||||
list_filter = ("is_active",)
|
||||
inlines = [MessageInline]
|
||||
46
prompt/api.py
Normal file
46
prompt/api.py
Normal file
@@ -0,0 +1,46 @@
|
||||
from typing import List
|
||||
from uuid import UUID
|
||||
from ninja import Router
|
||||
from django.shortcuts import get_object_or_404
|
||||
from django.contrib.auth.decorators import login_required
|
||||
|
||||
from .models import Conversation, Message
|
||||
from .schemas import ConversationOut, MessageOut
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
@router.get("/conversations/", response=List[ConversationOut])
|
||||
@login_required
|
||||
def list_conversations(request, task_id: int = None, user_id: int = None):
|
||||
convs = Conversation.objects.select_related("user", "task")
|
||||
# Normal users can only see their own
|
||||
if request.user.role == "normal":
|
||||
convs = convs.filter(user=request.user)
|
||||
elif user_id:
|
||||
convs = convs.filter(user_id=user_id)
|
||||
if task_id:
|
||||
convs = convs.filter(task_id=task_id)
|
||||
return [ConversationOut.from_conv(c) for c in convs]
|
||||
|
||||
|
||||
@router.get("/conversations/{conversation_id}/messages/", response=List[MessageOut])
|
||||
@login_required
|
||||
def list_messages(request, conversation_id: UUID):
|
||||
conv = get_object_or_404(Conversation, id=conversation_id)
|
||||
# Normal users can only see their own
|
||||
if request.user.role == "normal" and conv.user != request.user:
|
||||
return []
|
||||
messages = conv.messages.all()
|
||||
return [
|
||||
{
|
||||
"id": m.id,
|
||||
"role": m.role,
|
||||
"content": m.content,
|
||||
"code_html": m.code_html,
|
||||
"code_css": m.code_css,
|
||||
"code_js": m.code_js,
|
||||
"created": m.created.isoformat(),
|
||||
}
|
||||
for m in messages
|
||||
]
|
||||
7
prompt/apps.py
Normal file
7
prompt/apps.py
Normal file
@@ -0,0 +1,7 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class PromptConfig(AppConfig):
|
||||
default_auto_field = "django.db.models.BigAutoField"
|
||||
name = "prompt"
|
||||
verbose_name = "Prompt"
|
||||
133
prompt/consumers.py
Normal file
133
prompt/consumers.py
Normal file
@@ -0,0 +1,133 @@
|
||||
import json
|
||||
from channels.generic.websocket import AsyncWebsocketConsumer
|
||||
from channels.db import database_sync_to_async
|
||||
from .models import Conversation, Message
|
||||
from .llm import stream_chat, extract_code
|
||||
|
||||
|
||||
class PromptConsumer(AsyncWebsocketConsumer):
|
||||
async def connect(self):
|
||||
self.user = self.scope["user"]
|
||||
if self.user.is_anonymous:
|
||||
await self.close()
|
||||
return
|
||||
|
||||
self.task_id = int(self.scope["url_route"]["kwargs"]["task_id"])
|
||||
await self.accept()
|
||||
|
||||
# Load or create conversation, send history
|
||||
self.conversation = await self.get_or_create_conversation()
|
||||
history = await self.get_history()
|
||||
await self.send(text_data=json.dumps({
|
||||
"type": "init",
|
||||
"conversation_id": str(self.conversation.id),
|
||||
"messages": history,
|
||||
}))
|
||||
|
||||
async def disconnect(self, close_code):
|
||||
pass
|
||||
|
||||
async def receive(self, text_data):
|
||||
data = json.loads(text_data)
|
||||
msg_type = data.get("type", "message")
|
||||
|
||||
if msg_type == "new_conversation":
|
||||
self.conversation = await self.create_conversation()
|
||||
await self.send(text_data=json.dumps({
|
||||
"type": "init",
|
||||
"conversation_id": str(self.conversation.id),
|
||||
"messages": [],
|
||||
}))
|
||||
return
|
||||
|
||||
prompt = data.get("content", "").strip()
|
||||
if not prompt:
|
||||
return
|
||||
|
||||
# Save user message
|
||||
await self.save_message("user", prompt)
|
||||
|
||||
# Build history for LLM
|
||||
history = await self.get_history_for_llm()
|
||||
task_content = await self.get_task_content()
|
||||
|
||||
# Stream AI response
|
||||
full_response = ""
|
||||
try:
|
||||
async for chunk in stream_chat(task_content, history):
|
||||
full_response += chunk
|
||||
await self.send(text_data=json.dumps({
|
||||
"type": "stream",
|
||||
"content": chunk,
|
||||
}))
|
||||
except Exception as e:
|
||||
await self.send(text_data=json.dumps({
|
||||
"type": "error",
|
||||
"content": f"AI 服务出错:{str(e)}",
|
||||
}))
|
||||
return
|
||||
|
||||
# Extract code and save assistant message
|
||||
code = extract_code(full_response)
|
||||
await self.save_message("assistant", full_response, code)
|
||||
|
||||
# Send completion with extracted code
|
||||
await self.send(text_data=json.dumps({
|
||||
"type": "complete",
|
||||
"code": code,
|
||||
}))
|
||||
|
||||
@database_sync_to_async
|
||||
def get_or_create_conversation(self):
|
||||
conv = Conversation.objects.filter(
|
||||
user=self.user, task_id=self.task_id, is_active=True
|
||||
).first()
|
||||
if not conv:
|
||||
conv = Conversation.objects.create(user=self.user, task_id=self.task_id)
|
||||
return conv
|
||||
|
||||
@database_sync_to_async
|
||||
def create_conversation(self):
|
||||
Conversation.objects.filter(
|
||||
user=self.user, task_id=self.task_id, is_active=True
|
||||
).update(is_active=False)
|
||||
return Conversation.objects.create(user=self.user, task_id=self.task_id)
|
||||
|
||||
@database_sync_to_async
|
||||
def save_message(self, role, content, code=None):
|
||||
return Message.objects.create(
|
||||
conversation=self.conversation,
|
||||
role=role,
|
||||
content=content,
|
||||
code_html=code.get("html") if code else None,
|
||||
code_css=code.get("css") if code else None,
|
||||
code_js=code.get("js") if code else None,
|
||||
)
|
||||
|
||||
@database_sync_to_async
|
||||
def get_history(self):
|
||||
messages = self.conversation.messages.all()
|
||||
return [
|
||||
{
|
||||
"role": m.role,
|
||||
"content": m.content,
|
||||
"code": {
|
||||
"html": m.code_html,
|
||||
"css": m.code_css,
|
||||
"js": m.code_js,
|
||||
} if m.role == "assistant" else None,
|
||||
"created": m.created.isoformat(),
|
||||
}
|
||||
for m in messages
|
||||
]
|
||||
|
||||
@database_sync_to_async
|
||||
def get_history_for_llm(self):
|
||||
messages = self.conversation.messages.all()
|
||||
return [{"role": m.role, "content": m.content} for m in messages]
|
||||
|
||||
@database_sync_to_async
|
||||
def get_task_content(self):
|
||||
from task.models import Task
|
||||
task = Task.objects.get(id=self.task_id)
|
||||
return task.content
|
||||
54
prompt/llm.py
Normal file
54
prompt/llm.py
Normal file
@@ -0,0 +1,54 @@
|
||||
import re
|
||||
from django.conf import settings
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
|
||||
client = AsyncOpenAI(
|
||||
api_key=settings.LLM_API_KEY,
|
||||
base_url=settings.LLM_BASE_URL,
|
||||
)
|
||||
|
||||
SYSTEM_PROMPT = """你是一个网页生成助手。根据用户的需求描述,生成 HTML、CSS 和 JavaScript 代码。
|
||||
|
||||
规则:
|
||||
1. 始终使用三个独立的代码块返回代码,分别用 ```html、```css、```js 标记
|
||||
2. HTML 代码只需要 body 内的内容,不需要完整的 HTML 文档结构
|
||||
3. CSS 和 JS 可以为空,但仍然需要返回空的代码块
|
||||
4. 用中文回复,先简要说明你做了什么,然后给出代码
|
||||
5. 在已有代码基础上修改时,返回完整的修改后代码,不要只返回片段"""
|
||||
|
||||
|
||||
def build_messages(task_content: str, history: list[dict]) -> list[dict]:
|
||||
"""Build the message list for the LLM API call."""
|
||||
system = SYSTEM_PROMPT + f"\n\n当前挑战任务要求:\n{task_content}"
|
||||
messages = [{"role": "system", "content": system}]
|
||||
messages.extend(history)
|
||||
return messages
|
||||
|
||||
|
||||
async def stream_chat(task_content: str, history: list[dict]):
|
||||
"""Stream chat completion from the LLM. Yields content chunks."""
|
||||
messages = build_messages(task_content, history)
|
||||
stream = await client.chat.completions.create(
|
||||
model=settings.LLM_MODEL,
|
||||
messages=messages,
|
||||
stream=True,
|
||||
)
|
||||
async for chunk in stream:
|
||||
delta = chunk.choices[0].delta
|
||||
if delta.content:
|
||||
yield delta.content
|
||||
|
||||
|
||||
def extract_code(text: str) -> dict:
|
||||
"""Extract HTML, CSS, JS code blocks from AI response text."""
|
||||
result = {"html": None, "css": None, "js": None}
|
||||
pattern = r"```(html|css|js|javascript)\s*\n(.*?)```"
|
||||
matches = re.findall(pattern, text, re.DOTALL)
|
||||
for lang, code in matches:
|
||||
lang = lang.lower()
|
||||
if lang == "javascript":
|
||||
lang = "js"
|
||||
if lang in result:
|
||||
result[lang] = code.strip()
|
||||
return result
|
||||
50
prompt/migrations/0001_initial.py
Normal file
50
prompt/migrations/0001_initial.py
Normal file
@@ -0,0 +1,50 @@
|
||||
# Generated by Django 6.0.1 on 2026-03-04 11:01
|
||||
|
||||
import django.db.models.deletion
|
||||
import django_extensions.db.fields
|
||||
import uuid
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
('task', '0005_alter_task_options_alter_task_display_and_more'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Conversation',
|
||||
fields=[
|
||||
('created', django_extensions.db.fields.CreationDateTimeField(auto_now_add=True, verbose_name='created')),
|
||||
('modified', django_extensions.db.fields.ModificationDateTimeField(auto_now=True, verbose_name='modified')),
|
||||
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
|
||||
('is_active', models.BooleanField(default=True, verbose_name='是否活跃')),
|
||||
('task', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='conversations', to='task.task')),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='conversations', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'ordering': ('-created',),
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='Message',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('role', models.CharField(max_length=10)),
|
||||
('content', models.TextField()),
|
||||
('code_html', models.TextField(blank=True, null=True)),
|
||||
('code_css', models.TextField(blank=True, null=True)),
|
||||
('code_js', models.TextField(blank=True, null=True)),
|
||||
('created', models.DateTimeField(auto_now_add=True)),
|
||||
('conversation', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='messages', to='prompt.conversation')),
|
||||
],
|
||||
options={
|
||||
'ordering': ('created',),
|
||||
},
|
||||
),
|
||||
]
|
||||
0
prompt/migrations/__init__.py
Normal file
0
prompt/migrations/__init__.py
Normal file
36
prompt/models.py
Normal file
36
prompt/models.py
Normal file
@@ -0,0 +1,36 @@
|
||||
import uuid
|
||||
from django.db import models
|
||||
from django_extensions.db.models import TimeStampedModel
|
||||
from account.models import User
|
||||
from task.models import Task
|
||||
|
||||
|
||||
class Conversation(TimeStampedModel):
|
||||
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
|
||||
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="conversations")
|
||||
task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name="conversations")
|
||||
is_active = models.BooleanField(default=True, verbose_name="是否活跃")
|
||||
|
||||
class Meta:
|
||||
ordering = ("-created",)
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.user.username} - {self.task.title}"
|
||||
|
||||
|
||||
class Message(models.Model):
|
||||
conversation = models.ForeignKey(
|
||||
Conversation, on_delete=models.CASCADE, related_name="messages"
|
||||
)
|
||||
role = models.CharField(max_length=10) # "user" or "assistant"
|
||||
content = models.TextField()
|
||||
code_html = models.TextField(null=True, blank=True)
|
||||
code_css = models.TextField(null=True, blank=True)
|
||||
code_js = models.TextField(null=True, blank=True)
|
||||
created = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ("created",)
|
||||
|
||||
def __str__(self):
|
||||
return f"[{self.role}] {self.content[:50]}"
|
||||
37
prompt/schemas.py
Normal file
37
prompt/schemas.py
Normal file
@@ -0,0 +1,37 @@
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
from ninja import Schema
|
||||
|
||||
|
||||
class MessageOut(Schema):
|
||||
id: int
|
||||
role: str
|
||||
content: str
|
||||
code_html: Optional[str] = None
|
||||
code_css: Optional[str] = None
|
||||
code_js: Optional[str] = None
|
||||
created: str
|
||||
|
||||
|
||||
class ConversationOut(Schema):
|
||||
id: UUID
|
||||
user_id: int
|
||||
username: str
|
||||
task_id: int
|
||||
task_title: str
|
||||
is_active: bool
|
||||
message_count: int
|
||||
created: str
|
||||
|
||||
@staticmethod
|
||||
def from_conv(conv):
|
||||
return {
|
||||
"id": conv.id,
|
||||
"user_id": conv.user_id,
|
||||
"username": conv.user.username,
|
||||
"task_id": conv.task_id,
|
||||
"task_title": conv.task.title,
|
||||
"is_active": conv.is_active,
|
||||
"message_count": conv.messages.count(),
|
||||
"created": conv.created.isoformat(),
|
||||
}
|
||||
6
prompt/url.py
Normal file
6
prompt/url.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from django.urls import path
|
||||
from .consumers import PromptConsumer
|
||||
|
||||
websocket_urlpatterns = [
|
||||
path("ws/prompt/<int:task_id>/", PromptConsumer.as_asgi()),
|
||||
]
|
||||
Reference in New Issue
Block a user