Files
dnd-helpers/src/llm/processor.py
T

186 lines
6.1 KiB
Python
Raw Normal View History

2026-05-26 21:07:58 -07:00
import logging
import os
2026-05-26 23:25:53 -07:00
from posix import system
from this import s
from typing import Any, Dict, Optional
from openai import OpenAI
from pydantic import ValidationError
2026-05-26 23:25:53 -07:00
from .models import ExtractionResult, FilterResult
2026-05-27 22:30:20 -07:00
from .prompts import (
EXTRACTION_SYSTEM_PROMPT,
NOISE_FILTER_SYSTEM_PROMPT,
QUERY_ANSWER_SYSTEM_PROMPT,
)
2026-05-26 21:07:58 -07:00
logger = logging.getLogger(__name__)
class LLMProcessor:
def __init__(
self,
api_key: Optional[str] = None,
base_url: Optional[str] = None,
2026-05-25 22:50:09 -07:00
model: Optional[str] = None,
):
"""
Initializes the LLMProcessor.
:param api_key: OpenAI API key. If None, it looks for OPENAI_API_KEY in environment variables.
:param base_url: OpenAI-compatible base URL (e.g., for vLLM).
2026-05-25 22:50:09 -07:00
:param model: The model to use for processing. If None, it looks for LLM_MODEL in environment variables.
"""
2026-05-26 19:51:48 -07:00
backend = os.environ.get("LLM_BACKEND", "openai").lower()
if backend == "ollama":
# Ollama's OpenAI-compatible API
final_base_url = base_url or "http://localhost:11434/v1"
final_api_key = api_key or "ollama"
elif backend == "vllm":
# Remote vLLM server
final_base_url = base_url or os.environ.get("OPENAI_BASE_URL")
final_api_key = api_key or os.environ.get("OPENAI_API_KEY")
else: # default to openai
final_base_url = base_url or os.environ.get("OPENAI_BASE_URL")
final_api_key = api_key or os.environ.get("OPENAI_API_KEY")
try:
self.client = OpenAI(
api_key=final_api_key,
base_url=final_base_url,
)
# Simple connectivity check for local backends
if backend == "ollama":
# We can't easily check connectivity without making a call,
# but we can ensure the client is initialized.
pass
except Exception as e:
2026-05-26 21:07:58 -07:00
logger.error(f"Error initializing LLM client for backend {backend}: {e}")
2026-05-26 19:51:48 -07:00
raise
2026-05-25 22:50:09 -07:00
self.model = model or os.environ.get("LLM_MODEL", "gpt-4o")
def _call_llm(
self,
system_prompt: str,
user_prompt: str,
2026-05-26 21:07:58 -07:00
context: Optional[str] = None,
response_format: Optional[Any] = None,
) -> str:
"""
Generic method to call the LLM.
"""
2026-05-26 21:07:58 -07:00
messages = [
{"role": "system", "content": system_prompt},
]
if context:
messages.append(
{
"role": "system",
"content": f"Context from previous conversation:\n{context}",
}
)
messages.append({"role": "user", "content": user_prompt})
try:
response = self.client.chat.completions.create(
model=self.model,
2026-05-26 21:07:58 -07:00
messages=messages,
response_format=response_format,
2026-05-26 21:48:30 -07:00
extra_body={"enable_thinking": False},
)
content = response.choices[0].message.content
# Strip markdown code blocks if present
if content.startswith("```"):
import re
content = re.sub(
r"^```(?:json)?\n?|```$", "", content, flags=re.MULTILINE
).strip()
return content
except Exception as e:
2026-05-26 21:07:58 -07:00
logger.error(f"LLM Error: {e}")
return ""
2026-05-27 22:30:20 -07:00
def generate_answer(self, query: str, context: str) -> str:
"""
Generates a natural language answer to a DM query.
"""
return self._call_llm(
QUERY_ANSWER_SYSTEM_PROMPT,
query,
context=context,
)
2026-05-26 23:25:53 -07:00
def filter_transcript(
self, text: str, context: Optional[str] = None
) -> FilterResult:
"""
Stage 1: Raw Transcript -> Filtered Text.
"""
2026-05-26 23:25:53 -07:00
result = self._call_llm(
NOISE_FILTER_SYSTEM_PROMPT,
text,
context=context,
response_format={"type": "json_object"},
)
2026-05-26 21:07:58 -07:00
logger.info(f"LLM Processor (Filter): {text} -> {result}")
2026-05-26 23:25:53 -07:00
import json
try:
data = json.loads(result)
return FilterResult(**data)
except (json.JSONDecodeError, ValidationError) as e:
logger.error(f"Filter Parsing Error: {e}")
return FilterResult(contextual_info="", filtered_text=result)
2026-05-26 21:07:58 -07:00
def extract_structured_data(
self, filtered_text: str, context: Optional[str] = None
) -> ExtractionResult:
"""
Stage 2: Filtered Text -> Structured Data.
"""
2026-05-26 21:07:58 -07:00
logger.info(f"LLM Processor (Extract): Calling extraction for: {filtered_text}")
try:
2026-05-25 22:50:09 -07:00
# Using standard chat.completions.create with JSON mode for better compatibility with vLLM
2026-05-26 21:07:58 -07:00
logger.info("LLM Processor (Extract): Sending request to backend...")
2026-05-26 23:25:53 -07:00
system_prompt = EXTRACTION_SYSTEM_PROMPT
if context:
system_prompt += f"\n{context}"
2026-05-26 21:07:58 -07:00
messages = [
2026-05-26 23:25:53 -07:00
{"role": "system", "content": system_prompt},
2026-05-26 21:07:58 -07:00
]
messages.append({"role": "user", "content": filtered_text})
2026-05-26 23:25:53 -07:00
for message in messages:
logger.info(f"LLM Processor (Extract): Message: {message}")
2026-05-25 22:50:09 -07:00
response = self.client.chat.completions.create(
model=self.model,
2026-05-26 21:07:58 -07:00
messages=messages,
2026-05-25 22:50:09 -07:00
response_format={"type": "json_object"},
2026-05-26 21:48:30 -07:00
extra_body={"enable_thinking": False},
)
2026-05-26 21:07:58 -07:00
logger.info("LLM Processor (Extract): Response received from backend.")
2026-05-25 22:50:09 -07:00
import json
content = response.choices[0].message.content
2026-05-26 21:07:58 -07:00
logger.info(f"LLM Processor (Extract): Raw JSON response: {content}")
2026-05-25 22:50:09 -07:00
data = json.loads(content)
# Map the JSON data to the Pydantic model
return ExtractionResult(**data)
except Exception as e:
2026-05-26 21:07:58 -07:00
logger.error(f"Extraction Error: {e}")
# Return an empty ExtractionResult if parsing fails
return ExtractionResult()