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

157 lines
5.5 KiB
Python
Raw Normal View History

2026-05-26 21:07:58 -07:00
import logging
import os
from typing import Any, Dict, Optional
from openai import OpenAI
from pydantic import ValidationError
from .models import ExtractionResult
from .prompts import EXTRACTION_SYSTEM_PROMPT, NOISE_FILTER_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-25 22:50:09 -07:00
extra_body={"include_reasoning": False},
)
return response.choices[0].message.content
except Exception as e:
2026-05-26 21:07:58 -07:00
logger.error(f"LLM Error: {e}")
return ""
2026-05-26 21:07:58 -07:00
def filter_transcript(self, text: str, context: Optional[str] = None) -> str:
"""
Stage 1: Raw Transcript -> Filtered Text.
"""
2026-05-26 21:07:58 -07:00
result = self._call_llm(NOISE_FILTER_SYSTEM_PROMPT, text, context=context)
logger.info(f"LLM Processor (Filter): {text} -> {result}")
2026-05-25 22:50:09 -07:00
return 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...")
messages = [
{"role": "system", "content": EXTRACTION_SYSTEM_PROMPT},
]
if context:
messages.append(
{
"role": "system",
"content": f"Context from previous conversation:\n{context}",
}
)
messages.append({"role": "user", "content": filtered_text})
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"},
extra_body={"include_reasoning": 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()
2026-05-26 21:07:58 -07:00
def process_pipeline(
self, raw_text: str, context: Optional[str] = None
) -> ExtractionResult:
"""
Executes the two-stage pipeline: Raw Transcript -> Filtered Text -> Structured Data.
"""
2026-05-26 21:07:58 -07:00
filtered_text = self.filter_transcript(raw_text, context=context)
if not filtered_text:
return ExtractionResult()
2026-05-26 21:07:58 -07:00
return self.extract_structured_data(filtered_text, context=context)