Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ async def match_questions_to_sections(
messages = self._assignment_messages(sections_xml, question_chunk_xml)

response = await self.client.completion(
stage='assignment',
stats=stats,
messages=messages,
temperature=self.config.assignment.temperature,
Expand Down

This file was deleted.

32 changes: 23 additions & 9 deletions service/src/ai_document_plugin_service/ai/common/llm_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,21 @@
import logging
import time
import uuid
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, Literal

from openai import APIError, AsyncOpenAI
from openai.types.chat import ChatCompletion

from ai_document_plugin_service.ai.common.dynamic_semaphore import DynamicSemaphore
from ai_document_plugin_service.ai.common.execution_logging import log_llm_event
from ai_document_plugin_service.ai.common.llm_error import LLMError, llm_error_from_exception

if TYPE_CHECKING:
from ai_document_plugin_service.ai.common import AssignmentStats

logger = logging.getLogger(__name__)

type LLMStage = Literal['assignment', 'generation', 'polishing']

MAX_RETRIES = 3
RETRY_DELAY_S = 2.0

Expand Down Expand Up @@ -137,6 +138,7 @@ def get_model_name(self) -> str:
async def completion(
self,
*args: Any, # ruff: ignore[any-type]
stage: LLMStage,
stats: 'AssignmentStats | None' = None,
**kwargs: Any, # ruff: ignore[any-type]
) -> ChatCompletion:
Expand All @@ -147,17 +149,18 @@ async def completion(
"""
for _ in range(MAX_RETRIES - 1):
try:
return await self._completion(*args, stats=stats, **kwargs)
return await self._completion(*args, stage=stage, stats=stats, **kwargs)
except LLMError as error:
if not error.retryable:
raise
logger.warning('Error calling LLM, retrying: %s', error.__cause__ or error)
await asyncio.sleep(RETRY_DELAY_S)
return await self._completion(*args, stats=stats, **kwargs)
return await self._completion(*args, stage=stage, stats=stats, **kwargs)

async def _completion(
self,
*args: Any, # ruff: ignore[any-type]
stage: LLMStage,
stats: 'AssignmentStats | None' = None,
**kwargs: Any, # ruff: ignore[any-type]
) -> ChatCompletion:
Expand Down Expand Up @@ -188,9 +191,11 @@ async def _completion(
raise RuntimeError(msg)
req_id = uuid.uuid4().hex[:8]
wait_start = time.perf_counter()
log_llm_event(
{
logger.debug(
'Waiting for LLM semaphore',
extra={
'state': 'waiting_for_semaphore',
'stage': stage,
'req_id': req_id,
'tenant_uuid': str(self.tenant_uuid),
'model': self.model,
Expand All @@ -201,9 +206,11 @@ async def _completion(
)
async with self.semaphore:
wait_s = time.perf_counter() - wait_start
log_llm_event(
{
logger.debug(
'Waiting for LLM response',
extra={
'state': 'waiting_for_llm_response',
'stage': stage,
'req_id': req_id,
'tenant_uuid': str(self.tenant_uuid),
'model': self.model,
Expand All @@ -222,6 +229,7 @@ async def _completion(
_add_timing(stats, wait_s, duration_s)
self._log_llm_completion(
req_id=req_id,
stage=stage,
status='error',
wait_s=wait_s,
duration_s=duration_s,
Expand All @@ -236,6 +244,7 @@ async def _completion(
_add_timing(stats, wait_s, duration_s)
self._log_llm_completion(
req_id=req_id,
stage=stage,
status='success',
wait_s=wait_s,
duration_s=duration_s,
Expand All @@ -256,6 +265,7 @@ def _log_llm_completion(
self,
*,
req_id: str,
stage: LLMStage,
status: str,
wait_s: float,
duration_s: float,
Expand All @@ -265,6 +275,7 @@ def _log_llm_completion(
) -> None:
payload = {
'state': 'completed' if status == 'success' else 'failed',
'stage': stage,
'status': status,
'req_id': req_id,
'tenant_uuid': str(self.tenant_uuid),
Expand Down Expand Up @@ -292,7 +303,10 @@ def _log_llm_completion(
'error_message': str(error),
},
)
log_llm_event(payload)
if error is None:
logger.info('LLM call completed', extra=payload)
else:
logger.error('LLM call failed', extra=payload)


def _count_messages(messages: object) -> int | None:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,40 @@
import logging
from dataclasses import asdict
from typing import override
from uuid import UUID

from ai_document_plugin_service.ai.common.run_context import get_run_log_context
from ai_document_plugin_service.ai.common.trace_context import get_trace_uuid

LOG_FORMAT = '%(asctime)s | %(levelname)8s | %(name)s: [T:%(traceId)s] %(message)s'
_ORIGINAL_LOG_RECORD_FACTORY = logging.getLogRecordFactory()
_STANDARD_LOG_RECORD_FIELDS = frozenset(logging.makeLogRecord({}).__dict__) | {'asctime', 'message', 'traceId'}


class RunContextFilter(logging.Filter):
"""Adds the identifiers of the pipeline run in progress to every log record under ``context``.

A ``context`` a log call passes explicitly through ``extra`` is kept as it is.
"""

@override
def filter(self, record: logging.LogRecord) -> bool:
context = get_run_log_context()
if context is not None and not hasattr(record, 'context'):
record.context = {field: str(value) for field, value in asdict(context).items() if value is not None}
return True


class ExtraFormatter(logging.Formatter):
"""Appends application fields supplied through ``extra`` to text logs."""

def format(self, record: logging.LogRecord) -> str:
formatted = super().format(record)
extra = {key: value for key, value in record.__dict__.items() if key not in _STANDARD_LOG_RECORD_FIELDS}
extra = {
key: str(value) if isinstance(value, UUID) else value
for key, value in record.__dict__.items()
if key not in _STANDARD_LOG_RECORD_FIELDS
}
return f'{formatted} | extra={extra!r}' if extra else formatted


Expand Down Expand Up @@ -46,6 +68,8 @@ def _configure_root_stdout_logging(level: int) -> None:
for handler in root_logger.handlers:
handler.setLevel(level)
handler.setFormatter(ExtraFormatter(LOG_FORMAT))
if not any(isinstance(log_filter, RunContextFilter) for log_filter in handler.filters):
handler.addFilter(RunContextFilter())


def _configure_library_log_levels() -> None:
Expand Down
33 changes: 33 additions & 0 deletions service/src/ai_document_plugin_service/ai/common/run_context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from collections.abc import Iterator
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
from uuid import UUID

_RUN_CONTEXT: ContextVar['RunLogContext | None'] = ContextVar('run_log_context', default=None)


@dataclass(frozen=True)
class RunLogContext:
"""Identifiers of the pipeline run in progress; the logging filter adds them to every log record."""

run_id: UUID
questionnaire_uuid: UUID | None = None
template_uuid: UUID | None = None
template_title: str | None = None
knowledge_model_uuid: UUID | None = None
user_uuid: UUID | None = None
tenant_uuid: UUID | None = None


def get_run_log_context() -> RunLogContext | None:
return _RUN_CONTEXT.get()


@contextmanager
def run_log_context(context: RunLogContext) -> Iterator[None]:
token = _RUN_CONTEXT.set(context)
try:
yield
finally:
_RUN_CONTEXT.reset(token)
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ async def section_from_qa(
_ = previously_generated
messages = self._section_from_qa_messages(prompt)
response = await self.client.completion(
stage='generation',
stats=stats,
messages=messages,
temperature=self.config.dmp_generation.temperature,
Expand Down
Loading