Spaces:
Sleeping
Sleeping
File size: 6,718 Bytes
9381502 88c7275 9381502 88c7275 9381502 88c7275 9381502 88c7275 9381502 88c7275 9381502 88c7275 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | from __future__ import annotations
from functools import lru_cache
import hashlib
import time
from cert_study_app.chains.study_assistant_chain import build_ollama_llm, build_study_assistant_chain
from cert_study_app.models import Question
from cert_study_app.services.official_docs_service import LEGACY_AZURE_DOCS_COLLECTION, OFFICIAL_DOCS_COLLECTION
from cert_study_app.services.vector_service import QuestionVectorStore
_ANSWER_CACHE: dict[str, tuple[float, dict]] = {}
ANSWER_CACHE_TTL_SECONDS = 600
ANSWER_PROMPT_VERSION = "ko-summary-v2"
@lru_cache(maxsize=8)
def cached_ollama_llm(model: str, base_url: str, temperature: float, num_predict: int):
return build_ollama_llm(model=model, base_url=base_url, temperature=temperature, num_predict=num_predict)
@lru_cache(maxsize=8)
def cached_study_chain(model: str, base_url: str, temperature: float, num_predict: int):
llm = cached_ollama_llm(model, base_url, temperature, num_predict)
return build_study_assistant_chain(llm)
def _cache_key(
question: str,
model: str,
base_url: str,
k: int,
source: str | None,
max_context_chars: int,
embedding_model: str,
) -> str:
raw = "|".join(
[ANSWER_PROMPT_VERSION, question, model, base_url, str(k), source or "", str(max_context_chars), embedding_model]
)
return hashlib.sha1(raw.encode("utf-8")).hexdigest()
class StudyAssistantService:
def __init__(self, db, vector_store: QuestionVectorStore | None = None):
self.db = db
self.vector_store = vector_store or QuestionVectorStore()
self.docs_vector_store = QuestionVectorStore(
collection_name=OFFICIAL_DOCS_COLLECTION,
embedding_model=self.vector_store.embedding_model,
)
self.legacy_docs_vector_store = QuestionVectorStore(
collection_name=LEGACY_AZURE_DOCS_COLLECTION,
embedding_model=self.vector_store.embedding_model,
)
def index_questions(self) -> int:
questions = self.db.query(Question).order_by(Question.id.asc()).all()
payloads = []
for question in questions:
payloads.append(
{
"id": question.id,
"stem": question.stem,
"options": question.get_options(),
"answer": question.answer,
"explanation": question.explanation,
"category": question.category,
"subcategory": question.subcategory,
"source": question.source,
}
)
return self.vector_store.upsert_questions(payloads)
def ask(
self,
question: str,
model: str = "qwen2.5:14b",
base_url: str = "http://localhost:11434",
k: int = 2,
source: str | None = None,
max_context_chars: int = 2200,
use_cache: bool = True,
) -> dict:
key = _cache_key(question, model, base_url, k, source, max_context_chars, self.vector_store.embedding_model)
now = time.time()
if use_cache and key in _ANSWER_CACHE:
cached_at, cached = _ANSWER_CACHE[key]
if now - cached_at <= ANSWER_CACHE_TTL_SECONDS:
return {**cached, "cached": True}
doc_results = self._search_docs(question, k=min(3, max(1, k)))
question_results = self.vector_store.search(question, k=k, source=source)
results = [*doc_results, *question_results]
chain = cached_study_chain(model, base_url, 0.2, 320)
answer = chain.invoke(
{
"question": question,
"results": results,
"max_context_chars": max_context_chars,
}
)
payload = {
"answer": answer,
"sources": [
{
"id": item.id,
"score": item.score,
"text": item.text,
"metadata": item.metadata or {},
}
for item in results
],
"cached": False,
}
if use_cache:
_ANSWER_CACHE[key] = (now, payload)
return payload
def ask_stream(
self,
question: str,
model: str = "qwen2.5:14b",
base_url: str = "http://localhost:11434",
k: int = 2,
source: str | None = None,
max_context_chars: int = 2200,
use_cache: bool = True,
) -> dict:
key = _cache_key(question, model, base_url, k, source, max_context_chars, self.vector_store.embedding_model)
now = time.time()
if use_cache and key in _ANSWER_CACHE:
cached_at, cached = _ANSWER_CACHE[key]
if now - cached_at <= ANSWER_CACHE_TTL_SECONDS:
return {**cached, "cached": True, "stream": None}
doc_results = self._search_docs(question, k=min(3, max(1, k)))
question_results = self.vector_store.search(question, k=k, source=source)
results = [*doc_results, *question_results]
chain = cached_study_chain(model, base_url, 0.2, 320)
sources = [
{
"id": item.id,
"score": item.score,
"text": item.text,
"metadata": item.metadata or {},
}
for item in results
]
def stream_chunks():
chunks = []
try:
for chunk in chain.stream(
{
"question": question,
"results": results,
"max_context_chars": max_context_chars,
}
):
text = str(chunk or "")
if not text:
continue
chunks.append(text)
yield text
except Exception as exc:
error_msg = f"\n\n*(Ollama 응답 오류: {exc})*"
chunks.append(error_msg)
yield error_msg
return
if use_cache:
_ANSWER_CACHE[key] = (
time.time(),
{
"answer": "".join(chunks),
"sources": sources,
"cached": False,
},
)
return {"stream": stream_chunks(), "sources": sources, "cached": False}
def _search_docs(self, question: str, k: int):
official_results = self.docs_vector_store.search(question, k=k)
if official_results:
return official_results
return self.legacy_docs_vector_store.search(question, k=k)
|