77 lines
1.9 KiB
Go
77 lines
1.9 KiB
Go
package chat
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"resume-platform/internal/model"
|
|
"resume-platform/internal/prompt"
|
|
"resume-platform/internal/repository"
|
|
"resume-platform/internal/service/ai"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type ChatService interface {
|
|
Chat(ctx context.Context, userID string, question string) (string, error)
|
|
GetChatHistory(ctx context.Context, userID string) ([]*model.ChatHistory, error)
|
|
DeleteChatHistory(ctx context.Context, userID string) error
|
|
}
|
|
|
|
type chatService struct {
|
|
repo repository.ResumeRepository
|
|
ai *ai.AIService
|
|
}
|
|
|
|
func NewChatService(repo repository.ResumeRepository, ai *ai.AIService) ChatService {
|
|
return &chatService{repo: repo, ai: ai}
|
|
}
|
|
|
|
func (s *chatService) Chat(ctx context.Context, userID string, question string) (string, error) {
|
|
chunks, err := s.repo.GetDocumentChunksByUserID(userID)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
if len(chunks) == 0 {
|
|
return s.ai.Generate(ctx, question)
|
|
}
|
|
|
|
var chunkList []model.ChunkWithScore
|
|
for _, chunk := range chunks {
|
|
chunkList = append(chunkList, model.ChunkWithScore{
|
|
Content: chunk.Content,
|
|
Metadata: chunk.Embedding,
|
|
})
|
|
}
|
|
|
|
var contextStr string
|
|
for i, chunk := range chunkList[:min(5, len(chunkList))] {
|
|
contextStr += fmt.Sprintf("[文档片段%d]\n%s\n\n", i+1, chunk.Content)
|
|
}
|
|
|
|
promptText := prompt.BuildDocumentAnalysisPrompt(contextStr, question)
|
|
|
|
answer, err := s.ai.Generate(ctx, promptText)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
history := &model.ChatHistory{
|
|
ID: uuid.New().String(),
|
|
UserID: userID,
|
|
Question: question,
|
|
Answer: answer,
|
|
Context: contextStr,
|
|
}
|
|
s.repo.CreateChatHistory(history)
|
|
|
|
return answer, nil
|
|
}
|
|
|
|
func (s *chatService) GetChatHistory(ctx context.Context, userID string) ([]*model.ChatHistory, error) {
|
|
return s.repo.GetChatHistoryByUserID(userID)
|
|
}
|
|
|
|
func (s *chatService) DeleteChatHistory(ctx context.Context, userID string) error {
|
|
return nil
|
|
} |