콘텐츠로 이동

spakky-llm

spakky-llm은 spakky-agent의 IAgentModel을 OpenAI Chat Completions, Anthropic Messages, Gemini Developer API, Vertex AI에 연결하고 explicit Google text embedding adapter를 제공하는 model catalog 플러그인입니다.

호출자는 ModelSelection(model_ref=...)로 논리 모델 하나만 선택합니다. 운영자가 LlmModelRoute에서 실제 provider model과 capability를, LlmProfile에서 endpoint/auth/backend를 소유합니다. 기본 catalog는 공식 OpenAI Python SDK가 http://127.0.0.1:8000/v1의 로컬 vLLM OpenAI-compatible API를 호출하도록 구성됩니다.

설치와 로드

pip install spakky-llm
import spakky.agent
import spakky.plugins.llm
from spakky.agent import IAgentModel
from spakky.core.application.application import SpakkyApplication
from spakky.core.application.application_context import ApplicationContext

app = (
    SpakkyApplication(ApplicationContext())
    .load_plugins(
        include={
            spakky.agent.PLUGIN_NAME,
            spakky.plugins.llm.PLUGIN_NAME,
        }
    )
    .start()
)
model = app.container.get(type_=IAgentModel)

플러그인은 LlmConfig, OpenAIChatProvider, AnthropicMessagesProvider, 두 Google backend를 구현하는 GoogleGenerateContentProvider, LlmAgentModel을 등록하고 IAgentModel -> LlmAgentModel binding을 설정합니다. Adapter가 도구를 실행하지는 않습니다. 모델이 낸 ModelToolCall 후보를 검증해 반환하고, spakky-agent runner가 candidate batch 전체를 다시 검증·승인한 뒤 순서대로 dispatch합니다. Runner는 assistant tool-call turn과 TOOL result를 다음 ModelRequest에 넣어 model/tool loop를 이어가고, tool call이 없는 step에서 final을 한 번 방출합니다.

GoogleTextEmbedding은 자동 등록하지 않습니다. Retrieval에 필요한 애플리케이션만 별도 operator embedding config로 직접 만들고 factory를 통해 주입합니다.

Model catalog와 profile 설정

LlmConfig는 Spring Boot-style replaceability를 위해 선택과 연결을 분리합니다. 바로 실행 가능한 local 기본값이 있지만, 운영자는 typed configuration으로 catalog 전체를 교체할 수 있습니다. Catalog 내부 정합성과 unknown field는 LlmConfig 생성·startup에서 거부하고, standard OpenAI/Anthropic API key와 vLLM base_url 같은 provider-client 전용 필수값은 첫 client 생성 전에 fail closed합니다. 어느 경로도 SDK ambient inference로 조용히 우회하지 않습니다.

LlmConfig

필드 타입 기본값 의미
default_model str "assistant/default" 선택이 없을 때 사용할 opaque model ref
profiles dict[str, LlmProfile] local vLLM 연결 endpoint/auth/backend catalog
models dict[str, LlmModelRoute] assistant/default route logical ref에서 실제 target으로 가는 catalog

기본 route는 assistant/default -> vllm-local / default입니다. vllm-local profile은 provider="vllm", api="openai-chat-completions", base_url="http://127.0.0.1:8000/v1", api_key="EMPTY", openai_dialect="vllm"이고, route는 tools와 structured output capability를 선언합니다.

LlmProfile

필드 타입 기본값 의미
provider str 필수 routing metadata에 남길 운영자 소유 식별자
api LlmProviderApi 필수 사용할 공식 SDK API family
base_url str \| None None SDK endpoint override
api_key SecretStr \| None None SDK client 생성 경계에서만 꺼내는 secret
credential_provider str \| None None 호출 시점 token을 돌려주는 ILLMCredentialProvider 이름; openai-chat-completions와 openai-responses 전용, api_key와 배타
headers dict[str, str] {} SDK client의 default headers
request_timeout_seconds float \| None None non-streaming 요청 timeout; None이면 제한 없음, 지정 시 양수
stream_timeout_seconds float \| None None streaming 요청 timeout; None이면 제한 없음, 지정 시 양수
max_retries int 0 공식 SDK retry 횟수, 음수 불가
stream_enabled bool true 해당 profile의 streaming 허용 여부
resilience LlmResiliencePolicy 모두 disabled orchestration retry/concurrency/rate/circuit policy
openai_dialect OpenAICompatibleDialect "standard" OpenAI 표준, vLLM extension 또는 ChatGPT 로그인 경로 선택
google_credential_strategy GoogleCredentialStrategy \| None None Google API key, ADC, service-account-file 중 명시 선택
google_project str \| None None Vertex AI project
google_location str \| None None Vertex AI location
google_service_account_file Path \| None None 명시적으로 mount한 service-account JSON 경로

Profile은 connection/backend/auth만 담습니다. 실제 model ID와 capability는 profile에 호환 alias로 남아 있지 않습니다. openai_dialect="vllm"은 api="openai-chat-completions"에서만, openai_dialect="chatgpt"는 api="openai-responses"에서만 사용할 수 있습니다. provider, non-null base_url, Google project/location은 trim되고 빈 문자열이면 거부됩니다.

request_timeout_seconds와 stream_timeout_seconds는 생략하거나 None으로 지정하면 profile timeout을 적용하지 않습니다. 이는 AgentExecutionLimits.timeout_seconds의 runner deadline과 독립적입니다. 명시적으로 timeout을 설정하는 예제는 Profile timeout과 실행 제한을 참고하세요.

LlmModelRoute

필드 타입 기본값 의미
profile str 필수 profiles의 exact key
model str 필수 provider SDK에 전달할 physical model ID
capability ModelCapability text-only 기본 capability 선택 모델의 정확한 기능 선언
chat_template_kwargs dict[str, LlmScalar] {} vLLM route 전용 model option
reasoning_effort LlmReasoningEffort \| None None openai-responses route의 reasoning effort; None이면 provider 기본값
extra_body dict[str, JsonValue] {} vLLM route 전용 추가 request body; chat_template_kwargs, structured_outputs key 금지
fallbacks tuple[str, ...] () ordered logical fallback refs
fallback_on frozenset[LlmFailureClass] empty 이 route가 fallback할 failure allowlist
cache LlmCachePolicy DISABLED complete-response cache mode/TTL/namespace

chat_template_kwargs의 문자열 true/false는 boolean으로 정규화되며 vLLM dialect profile을 가리키는 route에서만 허용됩니다. extra_body도 같습니다. 실제 model ID는 /를 포함해도 분해하지 않습니다.

요청마다 route 덮기 (LlmRequestOptions)

LlmRequestOptions는 AgentRunExtension입니다. ModelRequest.extensions에 실으면 LlmAgentModel이 model_selection으로 고른 route 하나를 그 요청에서만 덮습니다.

Field 기본값 덮는 방식
model None route.model 대신 쓸 provider model 이름; None이면 route 값
chat_template_kwargs {} route.chat_template_kwargs 위에 key마다 덮음 (vLLM dialect 전용)
reasoning_effort None route.reasoning_effort 대신 씀; None이면 route 값 (openai-responses 전용)
extra_body {} route.extra_body 위에 key마다 덮음 (vLLM dialect 전용)
from spakky.agent import ModelMessage, ModelMessageRole, ModelRequest, ModelSelection
from spakky.plugins.llm.provider import LlmRequestOptions

request = ModelRequest(
    messages=(ModelMessage(ModelMessageRole.USER, "요약해 줘"),),
    model_selection=ModelSelection("local/chat"),
    extensions=(
        LlmRequestOptions(
            chat_template_kwargs={"enable_thinking": False},
            extra_body={"add_generation_prompt": False, "continue_final_message": True},
        ),
    ),
)
  • 덮은 값은 LlmModelRoute 검증을 다시 거칩니다(model strip, 문자열 "true"/"false"의 boolean 정규화). 그래서 adapter, response cache key, 응답의 routing metadata가 모두 덮은 route를 봅니다. Capability는 원래 route의 것을 그대로 씁니다.
  • fallbacks의 route는 다른 model이므로 덮지 않습니다.
  • vLLM dialect가 아닌 profile에 chat_template_kwargs나 extra_body를, openai-responses가 아닌 profile에 reasoning_effort를 주면 LlmUnsupportedFeatureError입니다. Streaming에서는 llm_feature_unsupported error event로 끝납니다.
  • 빈 model, extra_body의 framework 예약 key(chat_template_kwargs, structured_outputs), template scalar나 JSON이 아닌 값은 LlmRequestOptionsError(LlmModelSelectionError의 하위 타입)입니다.
  • 요청마다 다른 token은 이 extension이 아니라 credential_provider로 줍니다. LlmCredentialRequest.request에 요청 전체가 들어오므로 application은 자기 AgentRunExtension을 거기서 읽어 token을 고를 수 있습니다.

LlmRequestOptions를 싣지 않은 요청은 이전과 같습니다.

Route capability

필드 기본값 검증/의미
supports_reasoning false reasoning channel 지원 선언
context_window_tokens None 값이 있으면 양수여야 함
supports_token_counting false 호출 전 token counting 지원 선언
input_modalities / output_modalities text only 둘 다 비어 있을 수 없음
supports_tools false tool calling 지원 선언
supports_structured_output false structured output 지원 선언

Capability는 provider나 model 문자열에서 추론하지 않습니다. LlmAgentModel.capability은 default route의 값을, capability_for(selection)은 선택 primary route의 값을 반환합니다. 실제 ModelRequest는 text/image/audio/video/document parts에서 required input modalities를 계산하고 fallback-aware validate_request()가 explicitly reachable candidate 중 하나라도 충족하는지 provider I/O 전에 확인합니다. Provider MIME/source encoding은 route descriptor보다 더 좁을 수 있으며 이때 LlmUnsupportedFeatureError입니다. 공통 output은 현재 text입니다.

연결 설정의 fail-closed 경계

Environment source를 사용하는 field가 하나라도 있으면 SPAKKY_LLM__로 시작하지만 default_model, profiles, models가 아닌 top-level 환경변수를 LlmConfig 생성 시 거부합니다. 따라서 legacy SPAKKY_LLM__DEFAULT_PROFILE이나 SPAKKY_LLM__PROFILSE__... 같은 오타가 기본 연결로 조용히 우회하지 않습니다. Profile과 route 내부의 알 수 없는 필드도 extra="forbid" 검증에 실패합니다.

Profile/model ref는 trim 이후 nonblank·unique여야 하고 catalog는 각각 하나 이상의 항목을 가져야 합니다. default_model이 models에 없거나 route의 profile이 profiles에 없으면 시작할 수 없습니다. Key는 trim 이외의 canonicalization을 하지 않는 case-sensitive opaque 문자열이며 /를 parsing하지 않습니다.

Explicit constructor field는 같은 field의 environment 값을 JSON decode 전에 mask합니다. 세 field를 모두 직접 주면 environment catalog와 unrelated prefixed key를 읽거나 감사하지 않습니다. 일부만 직접 주면 그 field만 mask하고 나머지 environment field와 unknown top-level key 검사를 계속 수행합니다. Raw PROFILES/MODELS JSON은 object key 중복을 nested object까지 거부하며 standard JSON last-key-wins를 사용하지 않습니다.

Nested environment variable의 map segment는 case-insensitive source에서 소문자로 정규화됩니다. 예를 들어 PROFILES__MANAGED_TEXT__...는 managed_text key입니다. Case를 보존해야 하는 opaque key는 전체 JSON object나 direct Python mapping으로 전달합니다.

Standard API profile에서 base_url=None이면 adapter가 아래 공식 endpoint 또는 명시 backend mode를 SDK에 전달합니다. OPENAI_BASE_URL과 ANTHROPIC_BASE_URL 같은 SDK ambient 환경변수는 이 선택을 바꾸지 못합니다. Google backend도 API family와 credential strategy에서 명시적으로 정해집니다.

API family base_url=None일 때 endpoint 추가 경계
OpenAI Chat Completions https://api.openai.com/v1 standard/OpenRouter는 profile API key 필수; vLLM은 명시 base_url 필수
Anthropic Messages https://api.anthropic.com profile API key 필수
Gemini Developer API https://generativelanguage.googleapis.com/ explicit API-key strategy와 SDK Developer API mode
Vertex AI global: https://aiplatform.googleapis.com/; us/eu: https://aiplatform.{location}.rep.googleapis.com/; 그 밖의 region: https://{location}-aiplatform.googleapis.com/ explicit ADC 또는 service-account-file과 SDK enterprise mode

Gemini Developer API는 Google의 공식 제품명이며 개발 환경을 뜻하지 않습니다. 운영 서비스도 이 backend를 선택할 수 있지만 API key는 배포 runtime secret으로 profile에 주입해야 합니다. Vertex AI는 별도 google-vertex API family이며 project와 location을 항상 명시합니다. ADC를 선택하면 google.auth.default()에서 credential만 발견하고, service-account-file을 선택하면 지정 파일만 읽으며 ADC로 fallback하지 않습니다. GOOGLE_GENAI_USE_VERTEXAI, GOOGLE_GENAI_USE_ENTERPRISE, ambient project/location/API key가 이 선택을 바꾸지 못합니다. Vertex adapter도 official regional/global URL을 HttpOptions.base_url에 명시하므로 GOOGLE_VERTEX_BASE_URL과 GOOGLE_GEMINI_BASE_URL은 적용되지 않습니다. Operator가 LlmProfile.base_url을 직접 설정한 경우에만 official Vertex endpoint를 override합니다. google_location은 lowercase endpoint-safe identifier여야 합니다.

Profile 이름은 접근 경계가 아닙니다. adc를 선택하면 개발자 workstation의 ADC identity도 IAM 권한이 있는 project에 접근할 수 있습니다. Credential source를 지정 파일에 고정하려면 service-account-file을 사용하며 이 전략은 ADC로 fallback하지 않습니다. -prod 같은 이름은 framework가 특별하게 해석하지 않습니다.

Operator가 추가하는 custom header의 유일한 입력은 LlmProfile.headers입니다. OPENAI_CUSTOM_HEADERS나 ANTHROPIC_CUSTOM_HEADERS가 process 환경에 존재하면 해당 adapter는 ambient header를 섞지 않고 LlmConfigurationError로 거부합니다. 요청의 RunAgentInput.metadata나 ModelRequest.metadata도 endpoint, credential, physical model, header 설정에는 사용되지 않습니다.

중첩 환경 변수 예시

다음은 Anthropic 연결을 support/primary logical ref 뒤에 두는 예입니다. Profile은 환경변수 중첩 key로, /가 들어간 model catalog는 JSON object로 전달합니다.

export SPAKKY_LLM__DEFAULT_MODEL='support/primary'
export SPAKKY_LLM__PROFILES__MANAGED_TEXT__PROVIDER='anthropic'
export SPAKKY_LLM__PROFILES__MANAGED_TEXT__API='anthropic-messages'
export SPAKKY_LLM__PROFILES__MANAGED_TEXT__API_KEY="$ANTHROPIC_API_KEY"
export SPAKKY_LLM__PROFILES__MANAGED_TEXT__MAX_RETRIES='2'
export SPAKKY_LLM__MODELS='{"support/primary":{"profile":"managed_text","model":"claude-opus-4-1","capability":{"supports_reasoning":true,"supports_tools":true,"supports_structured_output":true}}}'

같은 catalog를 Python에서 직접 생성할 때의 full example과 Google/OpenRouter/vLLM recipe는 LLM 모델 라우팅을 확인하세요.

Google credential 환경 설정

아래 명령은 credential별 profile fragment입니다. 독립적인 설정으로 사용할 때는 앞 절처럼 matching DEFAULT_MODEL과 MODELS route도 함께 선언해야 합니다. Gemini Developer API는 API key와 전략을 함께 선언합니다.

export SPAKKY_LLM__PROFILES__PUBLIC_GOOGLE_API__PROVIDER='google'
export SPAKKY_LLM__PROFILES__PUBLIC_GOOGLE_API__API='google-gemini-developer'
export SPAKKY_LLM__PROFILES__PUBLIC_GOOGLE_API__API_KEY="$GEMINI_API_KEY"
export SPAKKY_LLM__PROFILES__PUBLIC_GOOGLE_API__GOOGLE_CREDENTIAL_STRATEGY='api-key'

Vertex AI에서 ADC를 명시적으로 선택하는 경우 project와 location도 profile에 둡니다.

export SPAKKY_LLM__PROFILES__CLOUD_ENTERPRISE__PROVIDER='google'
export SPAKKY_LLM__PROFILES__CLOUD_ENTERPRISE__API='google-vertex'
export SPAKKY_LLM__PROFILES__CLOUD_ENTERPRISE__GOOGLE_CREDENTIAL_STRATEGY='adc'
export SPAKKY_LLM__PROFILES__CLOUD_ENTERPRISE__GOOGLE_PROJECT='my-google-cloud-project'
export SPAKKY_LLM__PROFILES__CLOUD_ENTERPRISE__GOOGLE_LOCATION='us-central1'

Service-account-file 전략은 GOOGLE_SERVICE_ACCOUNT_FILE field도 함께 요구합니다.

export SPAKKY_LLM__PROFILES__CLOUD_ENTERPRISE__GOOGLE_CREDENTIAL_STRATEGY='service-account-file'
export SPAKKY_LLM__PROFILES__CLOUD_ENTERPRISE__GOOGLE_SERVICE_ACCOUNT_FILE='/var/run/secrets/google/service-account.json'

Production credential은 배포 runtime secret 또는 workload identity가 공급합니다. Local/CI acceptance는 공식 SDK client를 deterministic fake로 대체할 수 있으므로 상용 provider 계정 없이 model ref, credential mode, project/location, routing metadata를 검증할 수 있습니다.

요청별 모델 선택

ModelSelection의 공개 필드는 필수 model_ref: str 하나뿐입니다. 활성 model이 LlmAgentModel일 때 선택을 생략하면 그 router의 default_model이 사용됩니다. 다른 IAgentModel 구현에는 자체 selection/default 정책이 있을 수 있습니다.

from spakky.agent import ModelSelection, RunAgentInput

run_input = RunAgentInput(
    state_id="run-42",
    instruction="변경 사항을 요약해 주세요.",
    model_selection=ModelSelection(model_ref="support/primary"),
)

Blank ref는 core에서 거부됩니다. Unknown ref는 direct complete()에서 LlmModelSelectionError지만 stream()에서는 llm_model_selection_invalid ERROR와 terminal DONE으로 표면화됩니다. Protocol shape parser exception은 아닙니다. Slash는 provider/ref 구분자로 parsing되지 않으며 case-sensitive exact key로 lookup합니다. provider, profile, raw model, selection metadata를 받던 legacy 생성 형태는 지원되지 않습니다. Generic request metadata에 같은 이름의 값을 넣어도 catalog routing authority가 되지 않습니다.

Resolved direct response와 terminal model stream event에는 공통으로 model_ref, profile, provider, model이 들어갑니다. Provider가 finish reason이나 response ID를 추가할 수 있지만 credential, endpoint, header는 포함하지 않습니다. Unknown ref의 stream error는 선택되지 않은 default target을 꾸며 내지 않고 요청받은 model_ref만 metadata에 남깁니다.

Provider 경계와 기능

API family 공식 SDK adapter dialect 또는 특징
openai-chat-completions AsyncOpenAI OpenAI standard와 vLLM extension
openai-responses AsyncOpenAI Responses SSE stream; standard와 ChatGPT 로그인 dialect
anthropic-messages AsyncAnthropic native Messages, tool-use block, JSON output format
google-gemini-developer google.genai.Client API key 기반 Developer API mode
google-vertex google.genai.Client ADC/service-account 기반 enterprise mode

OpenRouter는 openai-chat-completions와 standard dialect를 사용하는 명시적 custom endpoint입니다. Provider-specific semantics가 없는 현재 surface에는 별도 OpenRouter dialect를 만들지 않습니다. OpenAI official/compatible standard profile은 API key가 필수입니다. vLLM만 OpenAICompatibleDialect.VLLM을 선택하며, 이 dialect에서 key를 생략한 경우에만 SDK용 non-secret not-required sentinel을 사용합니다.

OpenAI Responses API와 ChatGPT 로그인

api=openai-responses는 OpenAIResponsesProvider가 OpenAI Responses API(/v1/responses)를 SSE streaming으로 호출합니다. complete()도 같은 stream을 끝까지 읽어 하나의 ModelResponse로 합칩니다. 요청은 항상 stream=true, store=false이며 대화 history 전체를 input으로 보냅니다. previous_response_id와 metadata는 사용하지 않습니다.

기능 Responses 매핑
Function tool tools[].type="function", tool_choice는 auto/none/required
Structured output text.format.type="json_schema"; strict이면 모든 object를 required-all과 additionalProperties=false로 변환하고, 응답은 LlmJsonCodec이 다시 검증
Usage terminal event의 input_tokens, output_tokens, total_tokens, cached_tokens, cache_write_tokens
Reasoning route의 reasoning_effort가 reasoning.effort로 전달됨; supports_reasoning=True이면 reasoning.summary="auto"를 요청하고 summary delta를 REASONING_DELTA로 전달
Multimodal input user message의 text, image(URI 또는 inline), document(inline + filename); audio와 video는 LlmUnsupportedFeatureError

openai_dialect가 접근 경로를 고릅니다.

openai_dialect 인증 요청 차이
standard api_key 또는 credential_provider system role, temperature/top_p 전달
chatgpt 보통 credential_provider (token이 만료되므로) system message를 developer role로 전송, temperature/top_p 제거

chatgpt dialect는 Sign in with ChatGPT로 받은 token으로 ChatGPT 플랜 사용량을 쓰는 경로입니다. chatgpt는 openai-responses에서만, vllm은 openai-chat-completions에서만 허용됩니다. max_output_tokens와 function tool은 두 dialect에서 같은 모양으로 전달됩니다.

2026-11-13에 실제 ChatGPT 계정(gpt-6.1-sol)으로 확인한 범위입니다.

항목 결과
Text 응답과 usage 동작
Function tool 호출과 tool 결과 왕복 동작
Structured output strict=true / strict=false 둘 다 동작
temperature, top_p HTTP 400 Unsupported parameter로 거절됨
max_output_tokens, system role 받아들여짐
Reasoning summary delta reasoning.summary="auto"를 보내도 delta가 오지 않음

Quota 소진 code, HTTP 401 뒤 credential 재시도와 stream 중단은 실제 경로에서 재현하지 못했고 가짜 SSE 전송 테스트로만 검증했습니다.

from spakky.agent import ModelCapability
from spakky.plugins.llm.config import (
    LlmConfig,
    LlmModelRoute,
    LlmProfile,
    LlmProviderApi,
    LlmReasoningEffort,
    OpenAICompatibleDialect,
)

config = LlmConfig(
    default_model="builder/primary",
    profiles={
        "chatgpt": LlmProfile(
            provider="openai",
            api=LlmProviderApi.OPENAI_RESPONSES,
            openai_dialect=OpenAICompatibleDialect.CHATGPT,
            credential_provider="chatgpt",
        ),
    },
    models={
        "builder/primary": LlmModelRoute(
            profile="chatgpt",
            model="gpt-6.1-sol",
            reasoning_effort=LlmReasoningEffort.LOW,
            capability=ModelCapability(
                supports_tools=True,
                supports_structured_output=True,
            ),
        ),
    },
)

model 값은 예시입니다. 로그인한 계정에서 실제로 쓸 수 있는 model ID를 넣습니다.

Call-time credential

credential_provider는 고정 api_key 대신 호출 시점에 bearer token을 돌려주는 ILLMCredentialProvider Pod의 name입니다. api_key와 함께 쓸 수 없고 openai-chat-completions와 openai-responses profile에서 허용됩니다.

from typing import override

from spakky.core.pod.annotations.pod import Pod
from spakky.plugins.llm.provider import (
    ILLMCredentialProvider,
    LlmAccessToken,
    LlmCredentialRequest,
)


@Pod()
class ChatGptCredentialProvider(ILLMCredentialProvider):
    @property
    @override
    def name(self) -> str:
        return "chatgpt"

    @override
    async def access_token(self, credential: LlmCredentialRequest) -> LlmAccessToken:
        # credential.request로 호출 주체를 식별하고, 만료가 가까우면 갱신한 token을 돌려줍니다.
        # credential.rejected_token이 있으면 provider가 그 token을 401로 거절한 직후입니다.
        return await self._tokens.current(credential)

Adapter는 attempt마다 access_token()을 한 번 호출합니다. Provider가 HTTP 401로 거절하면 거절된 token을 rejected_token에 담아 한 번 더 호출하고 요청을 정확히 한 번 재시도합니다. 두 번째도 401이면 LlmAuthenticationError입니다. 이미 열린 stream은 재시도하지 않습니다. Chat Completions adapter도 credential_provider profile에서 같은 방식으로 동작합니다. 고정 api_key profile의 401은 이전처럼 한 번만 시도하고 LlmResponseError로 정규화합니다. OAuth 로그인, token 저장과 갱신은 이 plugin에 없습니다. Application이 구현합니다.

Quota와 stream 중단

상황 에러 failure class retryable
계정·플랜 사용량 소진 (insufficient_quota, subscription_sharing_usage_limit_exceeded, subscription_sharing_usage_unavailable) LlmQuotaExhaustedError quota false
일시적 요청 속도 제한 (HTTP 429, rate_limit_exceeded) LlmRateLimitError rate_limit true
Terminal event 없이 stream 종료 또는 stream 중 연결 끊김 LlmStreamInterruptedError transport true
Credential 거절 (HTTP 401) LlmAuthenticationError authentication false

Quota 소진은 기다려도 풀리지 않으므로 rate limit과 다른 failure class입니다. Retry policy의 rate_limit에 걸리지 않고, 필요하면 route fallback_on에 quota를 명시해 다른 model로 넘깁니다. response.incomplete는 max_output_tokens 사유만 finish_reason="length"인 성공으로 처리하고 그 밖의 사유는 LlmModelRefusalError입니다. 잘린 turn에 structured output을 요청했다면 불완전한 JSON이므로 LlmResponseError입니다. Terminal event를 받은 뒤의 연결 종료 오류는 무시합니다.

Provider registry와 custom adapter

ILLMProvider.is_default는 first-party default와 application replacement를 구분합니다. 공식 OpenAI, Anthropic, Google adapter는 True, custom provider의 기본값은 False입니다. LlmAgentModel 생성 시 API family별로 exactly one custom implementation이 있으면 같은 API의 default를 교체합니다. Custom이 둘 이상이면 ambiguous configuration이며, custom이 없을 때 default가 정확히 하나가 아니어도 LlmConfigurationError입니다. Configured profile이 요구하는 API가 최종 registry에 없을 때도 bootstrap이 실패합니다. 일반 plugin lifecycle에서는 이 검증이 app.start()에서 발생합니다.

Field/catalog reference는 그보다 앞선 LlmConfig 생성 시 Pydantic이 검증합니다. 반면 standard OpenAI/Anthropic API key, vLLM explicit base URL, Google credential load와 client endpoint 구성은 선택 route의 complete()/stream() client construction에서 LlmConfigurationError로 검증됩니다.

Ordered fallback과 resilience

LlmModelRoute.fallbacks와 fallback_on은 함께 비어 있거나 함께 선언되어야 합니다. Unknown/self/duplicate/cyclic ref는 LlmConfig 생성에서 거부됩니다. 한 route의 profile retry가 끝난 뒤 현재 failure class가 allowlist에 있을 때만 ordered fallback으로 이동합니다. Capability, cache, timeout, transport도 자동 fallback하지 않고 각각 enum을 명시해야 합니다.

LlmProfile.resilience의 retry/concurrency/rate/circuit은 모두 default disabled입니다. Orchestration retry를 켜면 failure class와 attempt bound가 필요하며 SDK max_retries>0와 동시에 켤 수 없습니다. Streaming은 provider event 방출 전 failure만 retry/fallback하고, partial stream 뒤에는 추가 billable attempt를 시작하지 않습니다.

Attempted/selected route, attempt ordinal, failure class, retry delay/count, fallback source, circuit state는 response/error metadata에 남습니다. Runner는 nested attempts와 cache selection을 durable evidence에, scalar summary만 telemetry attributes에 보존합니다.

Complete-response cache와 media URI policy

LlmCachePolicy.mode는 DISABLED, EXACT, SEMANTIC이고 default는 disabled입니다. Enabled mode마다 같은 mode의 ILLMResponseCache exactly one과 trusted ILLMCacheScopeResolver가 필요합니다. Scope resolver의 tenant/safety partition만 authority이며 arbitrary request metadata가 cache partition을 선택하지 않습니다.

Cache는 complete() tool-free response 전용입니다. Stream과 tool-call response를 lookup/store/replay하지 않습니다. Media URI는 cache lookup 전에도 default PublicLlmMediaUriPolicy가 async DNS timeout/public-address 검증을 수행합니다. ILLMMediaUriPolicy로 교체할 수 있고 part의 explicit allowed_uri_hosts는 operator authority로 DNS lookup을 생략합니다.

Lookup failure는 current route가 LlmFailureClass.CACHE fallback edge를 명시한 경우에만 다음 route로 갑니다. Provider success 뒤 store failure는 fallback을 금지하고 AbstractAgentModelError receipt에 usage/routing을 붙입니다. Runner가 billable token/cost와 evidence를 보존한 뒤 terminal error로 끝냅니다. Cache hit은 current usage 0과 saved-usage metadata를 반환합니다.

Optional platform ports

ILLMBatchProvider, ILLMFileProvider, ILLMNativeToolProvider는 interactive ILLMProvider.complete/stream과 별개입니다. Batch submit/status/results, explicit file upload/delete, provider-native WEB_SEARCH/FILE_SEARCH를 application이 직접 호출할 때만 사용합니다. 자동 batching/upload/prompt injection/native-tool execution은 없으며 malformed payload는 LlmPlatformBoundaryError입니다.

공식 SDK가 인증, retry, typed response, provider stream parsing을 소유합니다. Spakky는 ModelRequest mapping, ModelResponse와 ModelStreamEvent 정규화, portable JSON Schema 검증, 오류 분류를 소유합니다. 이 패키지는 raw HTTP request나 SSE parser를 httpx로 만들지 않습니다. httpx 직접 사용 범위는 Google 공식 SDK에 async transport를 주입하고, 그 transport가 노출하는 configuration/timeout/transport 예외를 공통 LLM error로 정규화하는 경계로 제한됩니다.

세 adapter 모두 complete/stream, portable sampling, function tools, structured JSON output, usage mapping 경계를 구현합니다. 실제 논리 모델별 지원 범위는 route의 ModelCapability가 선언합니다. supports_reasoning은 OpenAI/Anthropic에서 반환된 reasoning channel을 노출하고 Google에서는 ThinkingConfig(include_thoughts=True)를 요청합니다. vLLM dialect만 route의 extra_body, chat_template_kwargs와 structured_outputs.json을 extra_body에 추가하며, OpenAI standard에는 표준 response_format만 사용합니다. vLLM route가 supports_reasoning=True이면 assistant history의 metadata["reasoning"](문자열)을 요청의 assistant message reasoning_content로 다시 싣습니다. 응답이 reasoning을 돌려주는 key와 같으므로 응답 metadata를 history에 그대로 옮기면 reasoning_content를 읽는 chat template이 지난 reasoning을 다시 렌더링할 수 있습니다. 값이 문자열이 아니면 LlmResponseError입니다. Standard dialect나 supports_reasoning=False route에서는 싣지 않습니다.

API family complete / stream tools structured output
OpenAI Chat Completions 지원 / 지원 function tool과 choice; stream delta framing 표준 response_format; vLLM은 structured_outputs.json도 추가
Anthropic Messages 지원 / 지원 native tool-use block과 choice; stream delta framing native JSON output format
Google GenerateContent 지원 / 지원 native function declaration과 choice; stream candidate response_json_schema와 JSON MIME type
API family reasoning usage stream tool event
OpenAI Chat Completions capability가 켜지면 complete metadata와 stream delta complete 및 요청 시 stream terminal usage start, args delta, end, candidate
Anthropic Messages 반환된 thinking event를 capability가 켜진 경우에만 stream delta로 전달 complete 및 요청 시 final-message usage start, args delta, end, candidate
Google GenerateContent route reasoning capability가 켜지면 thought stream delta complete 및 요청 시 chunk usage 완성된 candidate

ModelUsage는 total/input/output에 더해 cache-aware input과 optional cache-write TTL breakdown을 보존합니다.

Provider usage cached input total cache write TTL breakdown
OpenAI prompt_tokens_details cached_tokens cache_write_tokens None
Anthropic Usage cache_read_input_tokens cache_creation_input_tokens cache_creation.ephemeral_5m_input_tokens / cache_creation.ephemeral_1h_input_tokens
Google usage metadata cached_content_token_count None None

Anthropic의 input_tokens는 uncached input, cache creation, cache read를 합한 inclusive input입니다. OpenAI와 Google도 provider의 total input counter를 그대로 input_tokens로 보존합니다. Anthropic TTL breakdown이 있으면 5-minute + 1-hour 합이 cache_creation_input_tokens와 정확히 같아야 합니다. Nonzero cache creation에 breakdown이 없거나 합이 다르면 LlmResponseError입니다. Adapter는 가격을 추론하지 않으며 core ModelPricingCatalog가 operator rate와 logical model ref로 cost를 계산합니다. Pricing과 cost budget은 Agent Memory, Evaluation, Cost와 Telemetry를 확인하세요.

Google adapter는 SDK의 automatic function calling을 명시적으로 끕니다. 따라서 세 adapter 모두 tool을 실행하지 않고 검증된 후보만 runner에 전달합니다.

Multimodal provider encoding

Portable media는 user message input에서만 native SDK shape로 변환됩니다. System, assistant와 tool history는 text-only입니다.

Adapter Image Audio / Video Document
OpenAI Chat Completions URI 또는 inline audio inline / video 미지원 inline + filename, MIME allowlist
OpenAI Responses URI 또는 inline 둘 다 미지원 inline + filename, OpenAI File inputs 가이드의 MIME 목록(PDF, docx·xlsx·pptx 등 Office 문서, csv, 글과 코드)
Anthropic Messages URI 또는 inline 둘 다 미지원 PDF URI/inline, UTF-8 text inline
Google GenerateContent URI 또는 inline URI 또는 inline URI 또는 inline

이 표는 adapter encoding surface이고 physical model support를 대신하지 않습니다. Route input_modalities가 먼저 모든 part를 허용해야 하며 adapter MIME/source 제약까지 통과하지 못하면 LlmUnsupportedFeatureError입니다. Generated non-text output은 공통 contract가 없습니다.

Anthropic adapter는 messages.create()나 messages.stream()에 SDK thinking 요청 파라미터를 보내지 않습니다. Provider stream에 thinking event가 들어온 경우에만 route가 supports_reasoning=true를 선언한 경우 REASONING_DELTA로 통과시키며, non-streaming response의 thinking/redacted-thinking block은 visible content에 포함하지 않습니다. Google은 같은 route capability가 켜진 경우 SDK ThinkingConfig(include_thoughts=True)를 전송합니다.

Tool 호출 권한과 원자적 stream 경계

ModelRequest.tool_calling의 tool catalog가 provider tool call의 유일한 권한 목록입니다. 요청에 catalog가 없거나 choice=NONE인데 provider가 tool call을 반환하면 LlmResponseError입니다. 반환된 tool 이름이 ToolCallingSpec.tools에 없거나 arguments가 그 tool의 portable JSON Schema를 통과하지 못해도 같은 오류로 거부합니다. choice=REQUIRED는 terminal response에 하나 이상의 유효한 tool call을 요구합니다. AUTO는 catalog 안에서 0개 이상을 허용하고, NONE이나 catalog가 없는 요청은 0개만 허용합니다. Native SDK에 전달한 tool_choice만 신뢰하지 않고 adapter가 response를 다시 검증합니다.

API family terminal reason과 tool batch의 일관성
OpenAI Chat Completions tool call 존재 여부와 finish_reason="tool_calls" 여부가 정확히 같아야 함
Anthropic Messages tool call 존재 여부와 stop_reason="tool_use" 여부가 정확히 같아야 함
Google GenerateContent 허용된 terminal finish reason을 먼저 확인한 뒤 catalog/schema와 NONE/REQUIRED를 검증

Streaming에서는 text/reasoning delta와 provider별 tool framing event가 먼저 보일 수 있습니다. 특히 OpenAI는 TOOL_CALL_START와 TOOL_CALL_ARGS_DELTA를 terminal보다 먼저 내보낼 수 있지만, 이 event들은 tool 실행 권한이 아닙니다. 세 adapter 모두 TOOL_CALL_CANDIDATE는 다음 검증이 전부 끝날 때까지 보류합니다.

  • terminal reason이 존재하고 허용된 값인지 확인합니다. OpenAI와 Anthropic은 위 표의 reason-tool 일관성도 확인합니다.
  • 전체 tool batch의 이름, arguments, catalog 등록 여부를 검증하고 NONE/REQUIRED 제약을 확인합니다.
  • Structured output 요청이 있으면 누적된 terminal JSON의 decode와 schema 검증까지 완료합니다.

모든 검증을 통과한 뒤에만 이미 전체가 검증된 batch의 candidate event를 순서대로 방출합니다. 따라서 side effect 권한은 candidate 경계에서 검증 전 0개, 검증 후 유효한 batch로 열립니다. 앞선 token이나 framing delta가 있었더라도 terminal 검증이 실패하면 candidate는 하나도 방출되지 않습니다. 표준 AgentRunner는 이 candidate를 whole-batch catalog/binding/authority gate로 다시 검증합니다. Gate를 모두 통과하면 실제 tool은 순차 dispatch되고 result는 TOOL history로 다음 model step에 전달됩니다. Batch 사전검증은 0-dispatch 원자성을 제공하지만 여러 tool의 side effect를 하나의 transaction으로 묶지는 않습니다.

OpenAI와 Anthropic terminal reason

OpenAI와 Anthropic SDK의 response type이 표현할 수 있는 terminal 값 전체를 성공으로 간주하지 않습니다. Adapter가 아래 allowlist와 refusal 조건을 complete와 stream에 동일하게 적용하고, nullable·legacy·미인식 terminal 값은 fail closed합니다.

API family 성공 allowlist 모델 거부 LlmResponseError
OpenAI Chat Completions stop, length, tool_calls content_filter 또는 non-empty refusal field terminal null, legacy function_call, 그 밖의 미인식 값
Anthropic Messages end_turn, max_tokens, stop_sequence, tool_use, model_context_window_exceeded refusal 또는 non-null stop_details terminal null, pause_turn, 그 밖의 미인식 값

성공 allowlist를 통과한 뒤에도 앞 절의 reason-tool 일관성, tool batch, structured output 검증이 이어집니다. 따라서 SDK가 HTTP 200 payload를 loose terminal 값으로 decode했더라도 이 표의 성공 조건과 후속 검증을 모두 통과하기 전에는 candidate나 terminal success를 방출하지 않습니다.

Google finish reason과 thought opt-in

Google adapter는 typed candidate의 terminal finish reason을 명시적인 allowlist로 분류합니다. HTTP 성공이나 candidate 존재만으로 성공 처리하지 않습니다.

분류 Google finish reason 또는 조건 결과
성공 STOP, MAX_TOKENS terminal reason 수용 후 tool/structured output 검증 계속
모델 거부 SAFETY, RECITATION, LANGUAGE, BLOCKLIST, PROHIBITED_CONTENT, SPII, IMAGE_SAFETY, IMAGE_PROHIBITED_CONTENT, NO_IMAGE, IMAGE_RECITATION, prompt feedback block LlmModelRefusalError
잘못된 response reason 누락·미지정, OTHER, IMAGE_OTHER, MALFORMED_FUNCTION_CALL, UNEXPECTED_TOOL_CALL, 그 밖의 미인식 값 LlmResponseError

MAX_TOKENS는 terminal reason 분류만 통과시킵니다. Structured output JSON이 잘려 decode 또는 schema 검증에 실패하면 최종 결과는 여전히 LlmResponseError이고 STRUCTURED_OUTPUT이나 tool candidate를 방출하지 않습니다.

Route의 supports_reasoning 기본값은 false이며 이때 Google 요청에 thinking_config를 보내지 않습니다. 선택한 Google route가 supports_reasoning=true를 선언한 경우에만 ThinkingConfig(include_thoughts=True)를 보내고 반환된 thought part를 REASONING_DELTA로 노출합니다. Automatic function calling은 이 설정과 무관하게 항상 꺼져 있으며 adapter가 tool을 직접 실행하지 않습니다.

SDK success payload와 OpenAI usage opt-out

세 공식 SDK가 HTTP 200을 반환해도 payload가 typed response 계약을 충족하지 않으면 semantic success로 취급하지 않습니다. SDK decode/mapping 실패뿐 아니라 adapter가 요구하는 candidate, terminal reason, content shape가 빠진 경우도 LlmResponseError로 정규화합니다.

SDK adapter 잘못된 success payload의 예
OpenAI APIResponseValidationError, JSON/typed mapping 실패, choice 누락, null·legacy·unknown terminal reason
Anthropic APIResponseValidationError, JSON/content block mapping 실패, null·pause_turn·unknown stop_reason
Google UnknownApiResponseError, JSON/typed model decode 실패, candidate 누락, missing·other·malformed finish reason

OpenAI stream에서 StreamingOptions(include_usage=False)를 선택하면 adapter는 SDK method에 omit sentinel을 전달해 serialized 요청의 stream_options를 생략하고, response에 usage chunk가 들어와도 사용하지 않습니다. 따라서 terminal DONE에도 usage를 싣지 않습니다. include_usage=True일 때만 stream_options={"include_usage": True}를 보내고 terminal usage를 매핑합니다.

Google async transport와 오류 경계

spakky-llm은 google-genai>=2.19.0을 사용하며 현재 lock과 검증 runtime은 2.19.0입니다. 이 runtime에서 환경에 따라 선택될 수 있는 aiohttp async backend의 예외가 provider-neutral 경계 밖으로 노출되지 않도록, types.HttpOptions.async_client_args에 httpx.AsyncHTTPTransport를 명시합니다. google.genai.Client가 이 transport로 request, retry, typed response와 stream parsing을 계속 소유하며 Spakky가 raw request나 SSE parsing을 수행하는 것은 아닙니다.

Complete와 stream setup/iteration은 같은 오류 경계를 사용합니다.

SDK/transport 실패 공통 오류 의미
httpx.InvalidURL, httpx.UnsupportedProtocol LlmConfigurationError allowlisted endpoint 형식 또는 protocol 오류
httpx.TimeoutException, Google API 408/504 LlmTimeoutError 요청 또는 stream timeout
httpx.TransportError, Google API 429 또는 5xx(504 제외) LlmTransportError 연결 또는 재시도 가능한 provider 실패
그 밖의 Google API 오류 LlmResponseError provider가 요청이나 response를 수용하지 못함

Google text embedding

GoogleTextEmbedding은 core ITextEmbedding의 explicit adapter이며 chat LlmAgentModel과 별도 객체입니다. 실제 import 경로는 다음과 같습니다.

from spakky.plugins.llm.providers.google import GoogleTextEmbedding

권장 생성 경계는 GoogleTextEmbedding.from_config(config, model_ref, *, output_dimensionality=None)입니다. 이 factory는 LlmConfig.models[model_ref]와 연결 profile을 snapshot하므로 이후 caller가 catalog dictionary를 바꾸어도 이미 만들어진 embedding target은 바뀌지 않습니다. Chat selection의 default_model을 추론하지 않고 embedding용 logical ref를 항상 명시합니다.

LlmProviderApi.GOOGLE_GEMINI_DEVELOPER와 GOOGLE_VERTEX만 허용합니다. 전자는 API key, 후자는 project/location과 ADC 또는 service-account-file을 요구하며 installed official Google Gen AI SDK의 models.embed_content()를 사용합니다. Custom base_url이 없으면 chat adapter와 동일한 official Developer 또는 regional/global Vertex endpoint를 사용합니다.

embed(texts, purpose)는 입력 순서를 보존하며 input마다 vector 하나를 요구합니다. output_dimensionality를 주면 각 vector가 그 positive dimension과 정확히 같아야 합니다. SDK가 truncation을 보고하거나 vector count/dimension이 다르거나 non-finite/잘못된 payload를 반환하면 silent 보정 없이 LlmResponseError입니다. Empty batch, blank text, 잘못된 purpose, non-positive dimension과 Google이 아닌 route는 LlmConfigurationError; timeout과 transport 실패는 기존 LlmTimeoutError/LlmTransportError 경계를 그대로 사용합니다.

이 adapter는 vector search나 index write를 제공하지 않습니다. IVectorSearch 구현과 기존 knowledge/index lifecycle은 application/vendor가 소유하며, core VectorRetriever가 query embedding과 검색을 합성합니다. 별도 구성 예는 AI Agent 심화를 확인하세요.

JSON Schema 2020-12 검증

Tool argument와 structured output은 provider가 JSON을 생성한 뒤에도 LlmJsonCodec이 JSON Schema 2020-12 전체로 다시 검증합니다. 검증은 jsonschema-rs가 하며, 공식 JSON-Schema-Test-Suite의 2020-12 필수 테스트를 모두 통과합니다. 선택과 근거는 ADR-0026에 있습니다.

  • 2020-12의 모든 keyword를 검증합니다. 예: const, oneOf, allOf, not, if/then/else, $ref/$defs, patternProperties, unevaluatedProperties, dependentRequired, 문자열·숫자·배열·객체의 제약 keyword, 하위 schema 자리의 true/false.
  • format은 2020-12 기본대로 annotation이며 값을 검증하지 않습니다.
  • 원격 $ref는 가져오지 않습니다. 외부 schema는 LlmJsonCodec(external_schemas=...)로 retrieval URI에 미리 등록할 때만 풀립니다. Provider adapter는 외부 schema를 등록하지 않으므로, provider 경로에서는 $defs에 넣은 schema만 참조할 수 있습니다.
  • Schema가 2020-12 meta-schema를 어기거나 reference를 풀 수 없으면 provider 호출 전에 LlmResponseError가 납니다. Provider 값이 schema를 어겨도 같은 오류입니다.
  • 오류의 details는 {"schema_keyword": ..., "reason": ...}입니다. reason은 invalid_schema, unresolvable_reference, value_mismatch 중 하나입니다. properties·$defs 같은 이름 지도의 키(사용자가 정한 이름), schema의 값, provider 값은 싣지 않습니다.
  • JSON text나 SDK value의 NaN, Infinity, -Infinity는 JSON number로 취급하지 않습니다.

Provider wire 사본

Provider의 strict structured output은 JSON Schema의 일부만 받습니다. Adapter는 원래 schema를 바꾸지 않고 provider가 문서에서 받는 범위의 wire 사본을 만듭니다. 사본은 원래 schema와 뜻이 같거나 더 넓고, 넓힌 만큼은 codec이 출력에서 검증합니다.

Provider Strict wire Strict로 보낼 수 없을 때
OpenAI Chat·Responses not, dependentRequired를 빼고 oneOf를 anyOf로 씁니다. 모든 object를 닫고 모든 property를 required에 넣습니다. allOf, if/then/else, dependentSchemas, additionalProperties schema, object가 아닌 root, root anyOf, properties 옆에서 닫으면 그 property를 막게 되는 object anyOf branch, $defs 한 항목보다 깊은 $ref: 원래 schema를 strict: false로 보냅니다.
Anthropic 숫자·문자열 길이 제약, minItems 0·1 밖의 배열 제약, not, scalar가 아닌 enum·const를 빼고 minItems는 1로 줄입니다. oneOf는 anyOf로, type·properties 옆의 anyOf는 각 branch로 옮깁니다. 모든 object를 닫습니다. 재귀 schema, additionalProperties schema, 옮길 수 없는 anyOf, 닫으면 뜻이 좁아지는 allOf·if/then/else·dependentSchemas, $defs 한 항목보다 깊은 $ref: tool은 strict: false로, structured output은 output_config 없이 schema를 담은 system 지시문으로 요청합니다.
Google Gemini 문서의 keyword와 anyOf·$ref·$defs만 남기고 나머지를 뺍니다. const는 값 하나의 enum으로, oneOf는 anyOf로, null이 아닌 type이 둘 이상인 type 배열은 anyOf로 씁니다. 없음
vLLM 원래 schema를 structured_outputs.json으로 보냅니다. —

Structured stream은 provider가 보고한 finish reason이 truncation이어도 누적한 terminal JSON을 decode하고 schema 검증합니다. 따라서 앞선 TOKEN_DELTA가 이미 방출됐더라도 유효한 전체 JSON이 아니면 STRUCTURED_OUTPUT event를 내지 않고 LlmResponseError로 종료합니다.

Agent output_type과 OpenAI strict wire

AgentExecutionSpec.output_type이 있으면 runner가 만든 strict schema가 selected provider의 ModelRequest.structured_output으로 전달됩니다. OpenAI strict JSON Schema wire는 모든 object property를 recursive하게 required에 넣고 additionalProperties=false로 닫아야 합니다. OpenAIChatProvider는 core schema를 mutate하지 않고 wire copy에만 이 normalization을 적용합니다. {"type": ["object", "null"]}처럼 type 배열에 object가 있는 schema도 같은 규칙으로 닫습니다.

따라서 default가 있는 BaseModel/dataclass field는 core materializer에서 생략 가능하지만 OpenAI strict wire 응답에는 포함됩니다. Arbitrary-key mapping처럼 additionalProperties 자체가 nested schema인 open-ended object는 strict wire로 닫을 수 없으므로 원래 schema를 strict: false로 보내고, 출력은 codec이 원래 schema로 검증합니다. Non-strict low-level request는 이 required-all normalization을 적용하지 않습니다.

Provider JSON은 adapter codec 검증 뒤 runner에서 다시 declared class로 exact materialization됩니다. OpenAI/Anthropic/Google 어느 경로도 text JSON을 structured payload로 추측하지 않습니다.

Tool history

표준 AgentRunner는 각 round의 assistant tool-call turn과 TOOL result history를 자동으로 조립합니다. IAgentModel을 runner 없이 직접 호출해 이전 tool turn을 ModelMessage로 조립한다면 TOOL message metadata에는 call_id와 tool_name을 넣습니다. 앞선 ASSISTANT message metadata의 tool_calls는 id, name, arguments를 가진 entry 목록입니다.

from spakky.agent import ModelMessage, ModelMessageRole

history = (
    ModelMessage(
        role=ModelMessageRole.ASSISTANT,
        content="",
        metadata={
            "tool_calls": (
                {
                    "id": "call-1",
                    "name": "lookup_weather",
                    "arguments": {"city": "Seoul"},
                },
            )
        },
    ),
    ModelMessage(
        role=ModelMessageRole.TOOL,
        content='{"temperature": 23}',
        metadata={"call_id": "call-1", "tool_name": "lookup_weather"},
    ),
)

Gemini가 thought_signature를 반환한 tool-call turn은 다음 요청에서 그 signature도 함께 재생해야 할 수 있습니다. Google adapter는 event/tool-call metadata에 제공된 signature를 보존하고 assistant history의 top-level 또는 각 tool_calls entry에서 읽지만, provider-neutral text transcript만으로는 이 provider 전용 값이 복원되지 않습니다.

Streaming과 오류

Streaming adapter는 provider SDK stream을 순회해 text, reasoning, tool-call start, argument delta, tool candidate, structured output, usage, terminal event를 ModelStreamEvent로 변환합니다. Router 단계에서 생긴 AbstractLlmError는 ERROR 뒤 DONE으로 끝나는 public stream으로 정규화됩니다. Non-streaming complete()는 typed AbstractLlmError를 호출자에게 그대로 전달합니다.

에러별 stream code는 에러 계층 구조에서 확인할 수 있습니다.

함께 보기

  • LLM 모델 라우팅: logical ref, profile, route, Google credential recipe를 확인합니다.
  • AI Agent 개발: multimodal input, bounded runner와 선언형 tool 사용법을 확인합니다.
  • AI Agent 심화: tool dispatch, approval, evidence 흐름을 확인합니다.
  • IAgentModel 용어: core outbound port와 provider plugin 관계를 확인합니다.

공개 package

Root package는 플러그인 발견에 필요한 PLUGIN_NAME만 공개합니다. 구현 타입을 root alias로 재노출하지 않으므로 아래 실제 모듈에서 import합니다.

spakky.plugins.llm

Multi-provider LLM adapter plugin for Spakky Agent.

PLUGIN_NAME = Plugin(name='spakky-llm') module-attribute

Plugin identifier for the multi-provider LLM adapter package.

설정과 라우터

Configuration for the operator-owned multi-provider LLM catalog.

LLM_RESERVED_EXTRA_BODY_KEYS = frozenset({'chat_template_kwargs', 'structured_outputs'}) module-attribute

Request body keys the chat-completions adapter owns and extra_body cannot set.

LlmProviderApi

Bases: StrEnum

Native SDK surface used to reach one configured profile.

GoogleCredentialStrategy

Bases: StrEnum

Explicit credential source for one Google connection profile.

OpenAICompatibleDialect

Bases: StrEnum

Known access paths layered on the OpenAI chat and Responses protocols.

LlmReasoningEffort

Bases: StrEnum

Reasoning effort requested from one OpenAI Responses model route.

LlmProfile

Bases: BaseModel

Operator-owned connection, backend, and authentication configuration.

api_key_value()

Return the secret only at the provider client construction boundary.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/config.py
def api_key_value(self) -> str | None:
    """Return the secret only at the provider client construction boundary."""
    if self.api_key is None:
        return None
    return self.api_key.get_secret_value()

LlmModelRoute

Bases: BaseModel

Strict mapping from one opaque model ref to one provider model target.

LlmConfig(*, default_model=_UNSET, profiles=_UNSET, models=_UNSET)

Bases: BaseSettings

Operator-owned connection profiles and opaque logical model catalog.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/config.py
def __init__(
    self,
    *,
    default_model: str | _Unset = _UNSET,
    profiles: Mapping[str, LlmProfile] | _Unset = _UNSET,
    models: Mapping[str, LlmModelRoute] | _Unset = _UNSET,
) -> None:
    values: _LlmConfigValues = {}
    if not isinstance(default_model, _Unset):
        values["default_model"] = default_model
    if not isinstance(profiles, _Unset):
        values["profiles"] = profiles
    if not isinstance(models, _Unset):
        values["models"] = models
    if len(values) != len(self.__class__.model_fields):
        _reject_unknown_prefixed_environment_fields(
            frozenset(field.casefold() for field in self.__class__.model_fields)
        )
    super().__init__(**values)

settings_customise_sources(settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings) classmethod

Mask explicit fields before strict environment catalog decoding.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/config.py
@classmethod
@override
def settings_customise_sources(
    cls,
    settings_cls: type[BaseSettings],
    init_settings: PydanticBaseSettingsSource,
    env_settings: PydanticBaseSettingsSource,
    dotenv_settings: PydanticBaseSettingsSource,
    file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]:
    """Mask explicit fields before strict environment catalog decoding."""
    if (
        not isinstance(init_settings, InitSettingsSource)
        or not isinstance(env_settings, EnvSettingsSource)
        or not isinstance(dotenv_settings, DotEnvSettingsSource)
    ):
        raise LlmConfigurationError
    explicit_fields = frozenset(init_settings.init_kwargs)
    if explicit_fields == frozenset(cls.model_fields):
        return (init_settings,)
    return (
        init_settings,
        _LlmEnvSettingsSource(settings_cls, env_settings, explicit_fields),
        _LlmDotEnvSettingsSource(
            settings_cls,
            dotenv_settings,
            explicit_fields,
        ),
        file_secret_settings,
    )

Resilient operator-catalog implementation of the Agent model port.

LlmAgentModel(config, providers, response_caches=(), cache_scope_resolver=None, clock=None, media_uri_policy=None)

Bases: IAgentModel

Resolve opaque routes with explicit cache, retry, and fallback policies.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/model.py
def __init__(
    self,
    config: LlmConfig,
    providers: tuple[ILLMProvider, ...],
    response_caches: tuple[ILLMResponseCache, ...] = (),
    cache_scope_resolver: ILLMCacheScopeResolver | None = None,
    clock: ILLMClock | None = None,
    media_uri_policy: ILLMMediaUriPolicy | None = None,
) -> None:
    self.__default_model = config.default_model
    self.__models = {
        model_ref: route.model_copy(deep=True)
        for model_ref, route in config.models.items()
    }
    self.__profiles = {
        name: profile.model_copy(deep=True)
        for name, profile in config.profiles.items()
    }
    self.__providers = self._provider_registry(providers)
    configured_apis = {profile.api for profile in self.__profiles.values()}
    if not configured_apis.issubset(self.__providers):
        raise LlmConfigurationError
    self.__cache_backends = self._cache_registry(response_caches)
    self.__cache_scope_resolver = cache_scope_resolver
    self._validate_cache_dependencies()
    self.__resilience = LlmResilienceController(clock)
    self.__media_uri_policy = (
        media_uri_policy
        if media_uri_policy is not None
        else PublicLlmMediaUriPolicy()
    )

capability property

Return the configured default route capability.

capability_for(selection=None)

Return the exact selected primary route capability.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/model.py
@override
def capability_for(
    self,
    selection: ModelSelection | None = None,
) -> ModelCapability:
    """Return the exact selected primary route capability."""
    return self._resolve_target(selection).route.capability

validate_request(request)

Accept when any explicitly reachable candidate satisfies the request.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/model.py
@override
def validate_request(self, request: ModelRequest) -> None:
    """Accept when any explicitly reachable candidate satisfies the request."""
    root = self._request_target(request)
    candidates = (
        self._candidate_refs_for_failure(
            root.model_ref,
            LlmFailureClass.CAPABILITY,
        )
        if LlmFailureClass.CAPABILITY in root.route.fallback_on
        else (root.model_ref,)
    )
    for model_ref in candidates:
        target = self._candidate_target(root, model_ref)
        if len(self._capability_reasons(target, request)) == 0:
            return
    raise LlmCapabilityError

complete(request) async

Complete through bounded retries and explicitly ordered fallbacks.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/model.py
@override
async def complete(self, request: ModelRequest) -> ModelResponse:
    """Complete through bounded retries and explicitly ordered fallbacks."""
    request = request.snapshot()
    root = self._request_target(request)
    candidates = self._candidate_refs(root.model_ref)
    attempts: list[_Evidence] = []
    cache_selections: list[_Evidence] = []
    attempt_ordinal = 0
    retry_count = 0
    last_error: AbstractLlmError | None = None
    last_target = root
    for model_ref in candidates:
        target = self._candidate_target(root, model_ref)
        last_target = target
        capability_reasons = self._capability_reasons(target, request)
        if len(capability_reasons) > 0:
            capability_error = LlmCapabilityError(
                details={"capability_skip_reasons": capability_reasons}
            )
            attempts.append(
                self._selection_evidence(
                    root,
                    target,
                    "skipped_capability",
                    capability_reasons=capability_reasons,
                )
            )
            last_error = capability_error
            if not self._fallback_allowed(target, capability_error):
                break
            continue

        try:
            await self.__media_uri_policy.validate(target, request)
        except AbstractLlmError as error:
            last_error = error
            evidence = self._failure_evidence(root, target, error)
            evidence["failure_stage"] = "media_uri_validation"
            attempts.append(evidence)
            if not self._fallback_allowed(target, error):
                break
            continue

        try:
            cached, cache_query = await self._lookup_cache(
                target,
                request,
                cache_selections,
            )
        except AbstractLlmError as error:
            last_error = error
            self._record_cache_failure(
                target,
                cache_selections,
                error,
                stage="lookup",
            )
            evidence = self._failure_evidence(root, target, error)
            evidence["failure_stage"] = "cache_lookup"
            attempts.append(evidence)
            if not self._fallback_allowed(target, error):
                break
            continue
        if cached is not None:
            metadata = {
                **self._metadata(
                    root,
                    target,
                    attempts,
                    cache_selections,
                    retry_count,
                ),
                **self._cache_saved_usage(cached.response.usage),
            }
            return replace(
                deepcopy(cached.response),
                usage=ModelUsage(
                    input_tokens=0,
                    output_tokens=0,
                    total_tokens=0,
                    cached_input_tokens=0,
                    cache_write_input_tokens=0,
                    cache_write_5m_input_tokens=0,
                    cache_write_1h_input_tokens=0,
                ),
                metadata={**cached.response.metadata, **metadata},
            )

        provider = self._provider_for(target)
        retry_policy = target.profile.resilience.retry
        profile_attempt = 1
        while True:
            lease: LlmAttemptLease | None = None
            try:
                lease = await self.__resilience.acquire(
                    target.profile_name,
                    target.profile.resilience,
                )
                attempt_ordinal += 1
                response = await provider.complete(target, request)
            except AbstractLlmError as error:
                last_error = error
                if lease is not None:
                    await self.__resilience.record_failure(
                        lease,
                        target.profile.resilience.circuit,
                        error.failure_class,
                    )
                evidence = self._failure_evidence(
                    root,
                    target,
                    error,
                    attempt_ordinal=(
                        attempt_ordinal if lease is not None else None
                    ),
                    profile_attempt=profile_attempt,
                )
                attempts.append(evidence)
                if (
                    profile_attempt < retry_policy.max_attempts
                    and error.failure_class in retry_policy.failure_classes
                ):
                    retry_count += 1
                    if lease is not None:
                        await self.__resilience.release(lease)
                    evidence[
                        "retry_delay_seconds"
                    ] = await self.__resilience.retry_delay(
                        retry_policy,
                        profile_attempt,
                        error,
                    )
                    profile_attempt += 1
                    continue
                break
            else:
                await self.__resilience.record_success(
                    lease,
                    target.profile.resilience.circuit,
                )
                attempts.append(
                    self._success_evidence(
                        root,
                        target,
                        attempt_ordinal,
                        profile_attempt,
                    )
                )
                try:
                    cache_state = await self._store_cache(
                        target,
                        cache_query,
                        response,
                        cache_selections,
                    )
                except AbstractLlmError as error:
                    self._record_cache_failure(
                        target,
                        cache_selections,
                        error,
                        stage="store",
                    )
                    attempts[-1].update(
                        {
                            **self._failure_fields(error, emitted=False),
                            "failure_stage": "cache_store",
                            "fallback_suppressed": "provider_success",
                        }
                    )
                    annotated = self._annotated_error(
                        error,
                        root,
                        target,
                        attempts,
                        cache_selections,
                        retry_count,
                    )
                    annotated.attach_model_receipt(
                        response.usage,
                        {
                            **routing_metadata(target),
                            **annotated.details,
                        },
                    )
                    raise annotated
                metadata = self._metadata(
                    root,
                    target,
                    attempts,
                    cache_selections,
                    retry_count,
                    cache_state=cache_state,
                )
                return replace(
                    response,
                    metadata={**response.metadata, **metadata},
                )
            finally:
                if lease is not None:
                    await self.__resilience.release(lease)
        if last_error is not None and not self._fallback_allowed(
            target,
            last_error,
        ):
            break

    final_error = last_error or LlmCapabilityError()
    raise self._annotated_error(
        final_error,
        root,
        last_target,
        attempts,
        cache_selections,
        retry_count,
    )

stream(request)

Stream with pre-emission retry/fallback and no response-cache replay.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/model.py
@override
def stream(self, request: ModelRequest) -> AsyncIterator[ModelStreamEvent]:
    """Stream with pre-emission retry/fallback and no response-cache replay."""
    return self._stream(request.snapshot())

Provider adapter contract and resolved model target.

LlmModelTarget(model_ref, profile_name, profile, route) dataclass

One opaque model ref resolved against the operator-owned catalog.

model property

Return the physical provider model from the resolved route.

LlmRequestOptions(model=None, chat_template_kwargs=dict(), reasoning_effort=None, extra_body=dict()) dataclass

Bases: AgentRunExtension

Override the selected route's values for one model request.

Attach it to ModelRequest.extensions. Only the route chosen by model_selection is overridden; fallback routes keep their own values. The overridden route is validated again with LlmModelRoute rules.

model = None class-attribute instance-attribute

Provider model name used instead of route.model; None keeps the route's.

chat_template_kwargs = field(default_factory=dict) class-attribute instance-attribute

Keys merged over route.chat_template_kwargs (vLLM dialect only).

reasoning_effort = None class-attribute instance-attribute

Effort used instead of route.reasoning_effort; None keeps the route's.

extra_body = field(default_factory=dict) class-attribute instance-attribute

Keys merged over route.extra_body (vLLM dialect only).

ILLMProvider

Bases: ABC

Native SDK adapter for one provider API family.

apis abstractmethod property

Return every API family implemented by this adapter.

is_default property

Return whether this is a replaceable first-party default adapter.

complete(target, request) abstractmethod async

Return one provider-neutral completion.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/provider.py
@abstractmethod
async def complete(
    self,
    target: LlmModelTarget,
    request: ModelRequest,
) -> ModelResponse:
    """Return one provider-neutral completion."""
    ...

stream(target, request) abstractmethod

Return provider-neutral streaming events.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/provider.py
@abstractmethod
def stream(
    self,
    target: LlmModelTarget,
    request: ModelRequest,
) -> AsyncIterator[ModelStreamEvent]:
    """Return provider-neutral streaming events."""
    ...

LlmCredentialRequest(profile_name, request, rejected_token=None) dataclass

One credential lookup for the caller behind a provider attempt.

ILLMCredentialProvider

Bases: ABC

Resolve a bearer credential at call time instead of a static API key.

name abstractmethod property

Return the name profiles reference as credential_provider.

access_token(credential) abstractmethod async

Return a currently valid token, refreshing a rejected or expiring one.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/provider.py
@abstractmethod
async def access_token(self, credential: LlmCredentialRequest) -> LlmAccessToken:
    """Return a currently valid token, refreshing a rejected or expiring one."""
    ...

LlmBatchState

Bases: StrEnum

Provider-neutral lifecycle states for optional batch inference.

LlmBatchRequest(id, requests) dataclass

Explicit batch boundary kept separate from interactive ModelRequest calls.

LlmBatchHandle(id, state) dataclass

Opaque provider batch handle without SDK objects.

ILLMBatchProvider

Bases: ABC

Optional batch port; interactive providers do not implement it implicitly.

submit_batch(request) abstractmethod async

Submit a backend-native asynchronous batch.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/provider.py
@abstractmethod
async def submit_batch(self, request: LlmBatchRequest) -> LlmBatchHandle:
    """Submit a backend-native asynchronous batch."""
    ...

batch_status(handle) abstractmethod async

Read the current backend-native batch state.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/provider.py
@abstractmethod
async def batch_status(self, handle: LlmBatchHandle) -> LlmBatchHandle:
    """Read the current backend-native batch state."""
    ...

batch_results(handle) abstractmethod async

Return completed batch items in request order.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/provider.py
@abstractmethod
async def batch_results(self, handle: LlmBatchHandle) -> Sequence[ModelResponse]:
    """Return completed batch items in request order."""
    ...

LlmFileUpload(name, media_type, content) dataclass

Explicit provider-native file payload outside ModelRequest messages.

LlmFileHandle(id, name, media_type) dataclass

Opaque provider file reference scoped to its owning backend.

ILLMFileProvider

Bases: ABC

Optional file lifecycle port with no automatic upload or prompt injection.

upload_file(upload) abstractmethod async

Upload one file only when an application explicitly invokes this port.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/provider.py
@abstractmethod
async def upload_file(self, upload: LlmFileUpload) -> LlmFileHandle:
    """Upload one file only when an application explicitly invokes this port."""
    ...

delete_file(handle) abstractmethod async

Delete one explicit provider-owned file.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/provider.py
@abstractmethod
async def delete_file(self, handle: LlmFileHandle) -> None:
    """Delete one explicit provider-owned file."""
    ...

LlmNativeToolKind

Bases: StrEnum

Provider-native optional tools that are never Agent tool authority.

LlmNativeToolRequest(kind, arguments) dataclass

Explicit native-tool request outside ModelRequest.tool_calling.

LlmNativeToolResult(kind, output, metadata) dataclass

Provider-native tool result returned only through the optional port.

ILLMNativeToolProvider

Bases: ABC

Optional native-tool port; providers never auto-execute it during inference.

native_tools abstractmethod property

Return explicitly supported provider-native tool kinds.

invoke_native_tool(request) abstractmethod async

Invoke one native tool only through this separate application boundary.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/provider.py
@abstractmethod
async def invoke_native_tool(
    self,
    request: LlmNativeToolRequest,
) -> LlmNativeToolResult:
    """Invoke one native tool only through this separate application boundary."""
    ...

ensure_tool_call_allowed(request)

Reject a provider tool call that lacks caller-declared authority.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/provider.py
def ensure_tool_call_allowed(request: ModelRequest) -> None:
    """Reject a provider tool call that lacks caller-declared authority."""
    tool_calling = request.tool_calling
    if tool_calling is None or tool_calling.choice is ModelToolChoice.NONE:
        raise LlmResponseError

ensure_terminal_tool_choice(request, tool_call_count)

Validate the terminal tool-call count against the requested choice.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/provider.py
def ensure_terminal_tool_choice(
    request: ModelRequest,
    tool_call_count: int,
) -> None:
    """Validate the terminal tool-call count against the requested choice."""
    tool_calling = request.tool_calling
    if tool_call_count > 0:
        ensure_tool_call_allowed(request)
    if (
        tool_calling is not None
        and tool_calling.choice is ModelToolChoice.REQUIRED
        and tool_call_count == 0
    ):
        raise LlmResponseError

routing_metadata(target)

Return privacy-safe evidence for the exact resolved catalog route.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/provider.py
def routing_metadata(target: LlmModelTarget) -> JsonObject:
    """Return privacy-safe evidence for the exact resolved catalog route."""
    return {
        "model_ref": target.model_ref,
        "profile": target.profile_name,
        "provider": target.profile.provider,
        "model": target.model,
    }

failure_code(error)

Return the stable public code for one typed plugin failure.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/provider.py
def failure_code(error: AbstractLlmError) -> str:
    """Return the stable public code for one typed plugin failure."""
    if isinstance(error, LlmTimeoutError):
        return "llm_timeout"
    if isinstance(error, LlmStreamInterruptedError):
        return "llm_stream_interrupted"
    if isinstance(error, LlmTransportError):
        return "llm_transport_error"
    if isinstance(error, LlmRateLimitError):
        return "llm_rate_limited"
    if isinstance(error, LlmQuotaExhaustedError):
        return "llm_quota_exhausted"
    if isinstance(error, LlmAuthenticationError):
        return "llm_authentication_failed"
    if isinstance(error, LlmConcurrencyLimitError):
        return "llm_concurrency_limited"
    if isinstance(error, LlmCircuitOpenError):
        return "llm_circuit_open"
    if isinstance(error, LlmStreamingDisabledError):
        return "llm_streaming_disabled"
    if isinstance(error, LlmConfigurationError):
        return "llm_configuration_invalid"
    if isinstance(error, LlmCacheConfigurationError):
        return "llm_cache_invalid"
    if isinstance(error, LlmModelSelectionError):
        return "llm_model_selection_invalid"
    if isinstance(error, LlmProviderUnavailableError):
        return "llm_provider_unavailable"
    if isinstance(error, LlmCapabilityError):
        return "llm_capability_insufficient"
    if isinstance(error, LlmUnsupportedFeatureError):
        return "llm_feature_unsupported"
    if isinstance(error, LlmModelRefusalError):
        return "model_refusal"
    return "llm_response_error"

to_model_error(error, target)

Normalize one adapter exception for the public streaming error channel.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/provider.py
def to_model_error(error: AbstractLlmError, target: LlmModelTarget) -> ModelError:
    """Normalize one adapter exception for the public streaming error channel."""
    retryable = error.failure_class in {
        LlmFailureClass.TIMEOUT,
        LlmFailureClass.TRANSPORT,
        LlmFailureClass.RATE_LIMIT,
        LlmFailureClass.CONCURRENCY,
        LlmFailureClass.CIRCUIT_OPEN,
    }
    metadata: dict[str, JsonValue] = {
        **routing_metadata(target),
        "failure_class": error.failure_class.value,
        **error.details,
    }
    if error.retry_after_seconds is not None:
        metadata["retry_after_seconds"] = error.retry_after_seconds
    return ModelError(
        code=failure_code(error),
        message=error.message,
        retryable=retryable,
        metadata=metadata,
    )

error_event(error, target, metadata=None)

Return one normalized terminal error event.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/provider.py
def error_event(
    error: AbstractLlmError,
    target: LlmModelTarget,
    metadata: JsonObject | None = None,
) -> ModelStreamEvent:
    """Return one normalized terminal error event."""
    model_error = to_model_error(error, target)
    merged = {**model_error.metadata, **(metadata or {})}
    return ModelStreamEvent(
        kind=ModelStreamEventKind.ERROR,
        error=ModelError(
            code=model_error.code,
            message=model_error.message,
            retryable=model_error.retryable,
            metadata=merged,
        ),
        metadata=merged,
    )

done_event(target, finish_reason, usage, metadata=None)

Return one provider-neutral terminal stream event.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/provider.py
def done_event(
    target: LlmModelTarget,
    finish_reason: str | None,
    usage: ModelUsage | None,
    metadata: JsonObject | None = None,
) -> ModelStreamEvent:
    """Return one provider-neutral terminal stream event."""
    return ModelStreamEvent(
        kind=ModelStreamEventKind.DONE,
        usage=usage,
        metadata={
            **routing_metadata(target),
            "finish_reason": finish_reason,
            **(metadata or {}),
        },
    )

Cache와 runtime policy

Explicit exact and semantic response-cache contracts for LLM completion.

LlmCacheMode

Bases: StrEnum

Replacement mode selected by one logical model route.

LlmCachePolicy

Bases: BaseModel

Route-owned response-cache policy, disabled unless explicitly selected.

LlmCacheScope(tenant_scope, safety_scope) dataclass

Trusted cache partition resolved outside arbitrary request metadata.

LlmCacheKey(digest, namespace, tenant_scope, safety_scope, model_ref, profile_name, provider, model) dataclass

Privacy-safe exact key carrying only route and partition evidence.

LlmCacheLookup(mode, key, semantic_input) dataclass

Cache lookup with a distinct semantic input for semantic backends.

LlmCachedResponse(response) dataclass

Complete tool-free response stored by a replaceable cache backend.

ILLMResponseCache

Bases: ABC

Replaceable cache port; no in-memory production implementation is implicit.

mode abstractmethod property

Return the one lookup mode implemented by this backend.

lookup(query) abstractmethod async

Return an exact or semantic hit according to the backend mode.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/cache.py
@abstractmethod
async def lookup(self, query: LlmCacheLookup) -> LlmCachedResponse | None:
    """Return an exact or semantic hit according to the backend mode."""
    ...

store(query, response, *, ttl_seconds) abstractmethod async

Store one complete tool-free response with the configured TTL.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/cache.py
@abstractmethod
async def store(
    self,
    query: LlmCacheLookup,
    response: LlmCachedResponse,
    *,
    ttl_seconds: float,
) -> None:
    """Store one complete tool-free response with the configured TTL."""
    ...

ILLMCacheScopeResolver

Bases: ABC

Resolve trusted tenant and safety partitions independently of metadata keys.

resolve(request) abstractmethod

Return the authoritative cache partition for one request.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/cache.py
@abstractmethod
def resolve(self, request: ModelRequest) -> LlmCacheScope:
    """Return the authoritative cache partition for one request."""
    ...

LlmCacheKeyBuilder

Build canonical SHA-256 request fingerprints without exposing bodies.

build(policy, scope, target, request, *, reasoning_effort_overridden=False) classmethod

Bind route, guarded content, tools, schema, sampling, and safety scope.

reasoning_effort_overridden is true only when this request's LlmRequestOptions replaced the route's reasoning effort. A catalog reasoning effort was never part of the key, so keeping it out preserves existing digests.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/cache.py
@classmethod
def build(
    cls,
    policy: LlmCachePolicy,
    scope: LlmCacheScope,
    target: LlmModelTarget,
    request: ModelRequest,
    *,
    reasoning_effort_overridden: bool = False,
) -> LlmCacheLookup:
    """Bind route, guarded content, tools, schema, sampling, and safety scope.

    ``reasoning_effort_overridden`` is true only when this request's
    ``LlmRequestOptions`` replaced the route's reasoning effort. A catalog
    reasoning effort was never part of the key, so keeping it out preserves
    existing digests.
    """
    assembled = request.assemble_messages()
    messages: list[JsonValue] = []
    semantic_input: list[str] = []
    for message in assembled:
        content_fingerprint, semantic_parts = cls._content(message.content)
        semantic_input.extend(
            f"{message.role.value}:{part}" for part in semantic_parts
        )
        messages.append(
            {
                "role": message.role.value,
                "content": content_fingerprint,
                "metadata_sha256": cls._hash_json(message.metadata),
            }
        )
    route: dict[str, JsonValue] = {
        "model_ref": target.model_ref,
        "profile": target.profile_name,
        "provider": target.profile.provider,
        "api": target.profile.api.value,
        "model": target.model,
        "capability": {
            "supports_reasoning": target.route.capability.supports_reasoning,
            "context_window_tokens": (
                target.route.capability.context_window_tokens
            ),
            "supports_token_counting": (
                target.route.capability.supports_token_counting
            ),
            "input_modalities": tuple(
                sorted(
                    modality.value
                    for modality in target.route.capability.input_modalities
                )
            ),
            "output_modalities": tuple(
                sorted(
                    modality.value
                    for modality in target.route.capability.output_modalities
                )
            ),
            "supports_tools": target.route.capability.supports_tools,
            "supports_structured_output": (
                target.route.capability.supports_structured_output
            ),
        },
        "chat_template_kwargs": cls._json_value(target.route.chat_template_kwargs),
        "connection_sha256": cls._hash_json(
            {
                "provider": target.profile.provider,
                "api": target.profile.api.value,
                "base_url": target.profile.base_url,
                "headers": target.profile.headers,
                "openai_dialect": target.profile.openai_dialect.value,
                "google_project": target.profile.google_project,
                "google_location": target.profile.google_location,
            }
        ),
    }
    # Added only when set so that existing cache digests stay unchanged.
    if reasoning_effort_overridden and target.route.reasoning_effort is not None:
        route["reasoning_effort"] = target.route.reasoning_effort.value
    if len(target.route.extra_body) > 0:
        route["extra_body"] = cls._json_value(target.route.extra_body)
    payload: dict[str, JsonValue] = {
        "namespace": policy.namespace,
        "tenant_scope": scope.tenant_scope,
        "safety_scope": scope.safety_scope,
        "route": route,
        "messages": messages,
        "context_manifest_ref": (
            request.context_manifest.id
            if request.context_manifest is not None
            else None
        ),
        "context_digest": (
            request.context_digest.digest
            if request.context_digest is not None
            else None
        ),
        "tool_calling": cls._tool_calling(request),
        "structured_output": cls._structured_output(request),
        "sampling": {
            "temperature": request.sampling.temperature,
            "top_p": request.sampling.top_p,
            "max_tokens": request.sampling.max_tokens,
        },
    }
    encoded = dumps(
        cls._json_value(payload),
        ensure_ascii=False,
        separators=(",", ":"),
        sort_keys=True,
    )
    key = LlmCacheKey(
        digest=sha256(encoded.encode("utf-8")).hexdigest(),
        namespace=policy.namespace,
        tenant_scope=scope.tenant_scope,
        safety_scope=scope.safety_scope,
        model_ref=target.model_ref,
        profile_name=target.profile_name,
        provider=target.profile.provider,
        model=target.model,
    )
    return LlmCacheLookup(
        mode=policy.mode,
        key=key,
        semantic_input=(
            tuple(semantic_input) if policy.mode is LlmCacheMode.SEMANTIC else ()
        ),
    )

Profile-scoped retry, concurrency, rate, and circuit-breaker policies.

LlmRetryPolicy

Bases: BaseModel

Bounded orchestration retry policy; one attempt means disabled.

delay_for(retry_count, error)

Return Retry-After or the bounded deterministic exponential delay.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/resilience.py
def delay_for(self, retry_count: int, error: AbstractLlmError) -> float:
    """Return Retry-After or the bounded deterministic exponential delay."""
    if error.retry_after_seconds is not None:
        return error.retry_after_seconds
    if retry_count <= 0 or self.backoff_seconds == 0:
        return 0.0
    delay = self.backoff_seconds * (2 ** (retry_count - 1))
    return min(delay, self.max_backoff_seconds)

LlmConcurrencyPolicy

Bases: BaseModel

Optional bounded in-flight gate for one connection profile.

LlmRateLimitPolicy

Bases: BaseModel

Optional deterministic request pacing for one connection profile.

LlmCircuitBreakerPolicy

Bases: BaseModel

Optional consecutive-failure circuit for one connection profile.

LlmResiliencePolicy

Bases: BaseModel

Spring-style profile policy with every behavior disabled by default.

LlmCircuitState

Bases: StrEnum

Observable state of one profile-scoped circuit.

ILLMClock

Bases: ABC

Replaceable monotonic clock and sleeper for deterministic policies.

now() abstractmethod

Return monotonic seconds.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/resilience.py
@abstractmethod
def now(self) -> float:
    """Return monotonic seconds."""
    ...

sleep(seconds) abstractmethod async

Advance or wait for the requested duration.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/resilience.py
@abstractmethod
async def sleep(self, seconds: float) -> None:
    """Advance or wait for the requested duration."""
    ...

SystemLlmClock

Bases: ILLMClock

Default runtime clock backed by the event loop and monotonic time.

LlmAttemptLease(profile_name, state, circuit_state, circuit_epoch, semaphore_acquired, circuit_finished=False, released=False) dataclass

One admitted profile attempt whose resources must be released exactly once.

LlmResilienceController(clock=None)

Coordinate independent retry gates and circuit state per profile.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/resilience.py
def __init__(self, clock: ILLMClock | None = None) -> None:
    self.__clock = clock if clock is not None else SystemLlmClock()
    self.__states = {}

acquire(profile_name, policy) async

Apply circuit, rate, and concurrency gates before provider execution.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/resilience.py
async def acquire(
    self,
    profile_name: str,
    policy: LlmResiliencePolicy,
) -> LlmAttemptLease:
    """Apply circuit, rate, and concurrency gates before provider execution."""
    state = self._state(profile_name, policy)
    circuit_state, circuit_epoch = await self._reserve_circuit(
        state,
        policy.circuit,
    )
    semaphore_acquired = False
    try:
        semaphore_acquired = await self._acquire_concurrency(
            state,
            policy.concurrency,
        )
        await self._apply_rate_limit(state, policy.rate_limit)
    except BaseException:
        if semaphore_acquired and state.semaphore is not None:
            state.semaphore.release()
        await self._abandon_circuit_reservation(
            state,
            circuit_state,
            circuit_epoch,
        )
        raise
    return LlmAttemptLease(
        profile_name=profile_name,
        state=state,
        circuit_state=circuit_state,
        circuit_epoch=circuit_epoch,
        semaphore_acquired=semaphore_acquired,
    )

record_success(lease, policy) async

Close an enabled circuit after a successful provider attempt.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/resilience.py
async def record_success(
    self,
    lease: LlmAttemptLease,
    policy: LlmCircuitBreakerPolicy,
) -> None:
    """Close an enabled circuit after a successful provider attempt."""
    if policy.failure_threshold is None:
        lease.circuit_finished = True
        return
    async with lease.state.circuit_lock:
        if lease.circuit_epoch != lease.state.circuit_epoch:
            lease.circuit_finished = True
            return
        if lease.circuit_state is LlmCircuitState.HALF_OPEN:
            lease.state.half_open_in_flight -= 1
            if lease.state.half_open_in_flight == 0:
                self._close_circuit(lease.state, advance_epoch=True)
        else:
            self._close_circuit(lease.state, advance_epoch=False)
        lease.circuit_finished = True

record_failure(lease, policy, failure_class) async

Advance only explicitly counted failures through circuit state.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/resilience.py
async def record_failure(
    self,
    lease: LlmAttemptLease,
    policy: LlmCircuitBreakerPolicy,
    failure_class: LlmFailureClass,
) -> None:
    """Advance only explicitly counted failures through circuit state."""
    if policy.failure_threshold is None:
        lease.circuit_finished = True
        return
    async with lease.state.circuit_lock:
        if lease.circuit_epoch != lease.state.circuit_epoch:
            lease.circuit_finished = True
            return
        if lease.circuit_state is LlmCircuitState.HALF_OPEN:
            lease.state.half_open_in_flight -= 1
        if failure_class not in policy.failure_classes:
            if lease.circuit_state is LlmCircuitState.HALF_OPEN:
                if lease.state.half_open_in_flight == 0:
                    self._close_circuit(lease.state, advance_epoch=True)
            else:
                self._close_circuit(lease.state, advance_epoch=False)
            lease.circuit_finished = True
            return
        if lease.circuit_state is LlmCircuitState.HALF_OPEN:
            self._open_circuit(lease.state)
            lease.circuit_finished = True
            return
        lease.state.consecutive_failures += 1
        if lease.state.consecutive_failures >= policy.failure_threshold:
            self._open_circuit(lease.state)
        lease.circuit_finished = True

release(lease) async

Release concurrency and abandoned half-open reservations once.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/resilience.py
async def release(self, lease: LlmAttemptLease) -> None:
    """Release concurrency and abandoned half-open reservations once."""
    if lease.released:
        return
    if (
        not lease.circuit_finished
        and lease.circuit_state is LlmCircuitState.HALF_OPEN
    ):
        async with lease.state.circuit_lock:
            if lease.circuit_epoch == lease.state.circuit_epoch:
                lease.state.half_open_in_flight -= 1
    if lease.semaphore_acquired and lease.state.semaphore is not None:
        lease.state.semaphore.release()
    lease.released = True

retry_delay(policy, retry_count, error) async

Sleep for one deterministic retry delay and return the evidence value.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/resilience.py
async def retry_delay(
    self,
    policy: LlmRetryPolicy,
    retry_count: int,
    error: AbstractLlmError,
) -> float:
    """Sleep for one deterministic retry delay and return the evidence value."""
    delay = policy.delay_for(retry_count, error)
    if delay > 0:
        await self.__clock.sleep(delay)
    return delay

circuit_state(profile_name)

Return an existing profile circuit state without creating global state.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/resilience.py
def circuit_state(self, profile_name: str) -> LlmCircuitState:
    """Return an existing profile circuit state without creating global state."""
    state = self.__states.get(profile_name)
    return state.circuit_state if state is not None else LlmCircuitState.DISABLED

Async, replaceable remote-media URI validation before provider I/O.

ILLMMediaUriPolicy

Bases: ABC

Replaceable async authority for provider-bound remote media references.

validate(target, request) abstractmethod async

Validate every URI without blocking the caller's event-loop thread.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/media.py
@abstractmethod
async def validate(
    self,
    target: LlmModelTarget,
    request: ModelRequest,
) -> None:
    """Validate every URI without blocking the caller's event-loop thread."""
    ...

PublicLlmMediaUriPolicy(timeout_seconds=2.0)

Bases: ILLMMediaUriPolicy

Resolve untrusted HTTP(S) hostnames off-loop and require public addresses.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/media.py
def __init__(self, timeout_seconds: float = 2.0) -> None:
    if (
        isinstance(timeout_seconds, bool)
        or not isinstance(timeout_seconds, int | float)
        or not isfinite(timeout_seconds)
        or timeout_seconds <= 0
    ):
        raise LlmConfigurationError
    self.__timeout_seconds = float(timeout_seconds)

오류와 상수

Errors raised by the multi-provider LLM plugin.

LlmFailureClass

Bases: StrEnum

Provider-neutral failure classes used by retry and fallback policies.

AbstractLlmError(*, retry_after_seconds=None, details=None)

Bases: AbstractAgentModelError, ABC

Base class for LLM routing and provider adapter failures.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def __init__(
    self,
    *,
    retry_after_seconds: float | None = None,
    details: JsonObject | None = None,
) -> None:
    super().__init__()
    if retry_after_seconds is not None and (
        not isfinite(retry_after_seconds) or retry_after_seconds < 0
    ):
        raise LlmConfigurationError
    self.retry_after_seconds = retry_after_seconds
    try:
        self.details = _snapshot_json_object({} if details is None else details)
    except RecursionError as error:
        raise LlmConfigurationError from error

annotate(details)

Attach privacy-safe orchestration evidence before propagation.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def annotate(self, details: JsonObject) -> None:
    """Attach privacy-safe orchestration evidence before propagation."""
    try:
        self.details = _snapshot_json_object({**self.details, **details})
    except RecursionError as error:
        raise LlmConfigurationError from error

LlmConfigurationError(*, retry_after_seconds=None, details=None)

Bases: AbstractLlmError

Raised when catalog, provider registry, client, or media policy is invalid.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def __init__(
    self,
    *,
    retry_after_seconds: float | None = None,
    details: JsonObject | None = None,
) -> None:
    super().__init__()
    if retry_after_seconds is not None and (
        not isfinite(retry_after_seconds) or retry_after_seconds < 0
    ):
        raise LlmConfigurationError
    self.retry_after_seconds = retry_after_seconds
    try:
        self.details = _snapshot_json_object({} if details is None else details)
    except RecursionError as error:
        raise LlmConfigurationError from error

LlmModelSelectionError(*, retry_after_seconds=None, details=None)

Bases: AbstractLlmError

Raised when a request does not resolve to one catalog model ref.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def __init__(
    self,
    *,
    retry_after_seconds: float | None = None,
    details: JsonObject | None = None,
) -> None:
    super().__init__()
    if retry_after_seconds is not None and (
        not isfinite(retry_after_seconds) or retry_after_seconds < 0
    ):
        raise LlmConfigurationError
    self.retry_after_seconds = retry_after_seconds
    try:
        self.details = _snapshot_json_object({} if details is None else details)
    except RecursionError as error:
        raise LlmConfigurationError from error

LlmRequestOptionsError(*, retry_after_seconds=None, details=None)

Bases: LlmModelSelectionError

Raised when per-request route overrides cannot form a valid route.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def __init__(
    self,
    *,
    retry_after_seconds: float | None = None,
    details: JsonObject | None = None,
) -> None:
    super().__init__()
    if retry_after_seconds is not None and (
        not isfinite(retry_after_seconds) or retry_after_seconds < 0
    ):
        raise LlmConfigurationError
    self.retry_after_seconds = retry_after_seconds
    try:
        self.details = _snapshot_json_object({} if details is None else details)
    except RecursionError as error:
        raise LlmConfigurationError from error

LlmProviderUnavailableError(*, retry_after_seconds=None, details=None)

Bases: AbstractLlmError

Raised when no native SDK adapter exists for a selected profile API.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def __init__(
    self,
    *,
    retry_after_seconds: float | None = None,
    details: JsonObject | None = None,
) -> None:
    super().__init__()
    if retry_after_seconds is not None and (
        not isfinite(retry_after_seconds) or retry_after_seconds < 0
    ):
        raise LlmConfigurationError
    self.retry_after_seconds = retry_after_seconds
    try:
        self.details = _snapshot_json_object({} if details is None else details)
    except RecursionError as error:
        raise LlmConfigurationError from error

LlmStreamingDisabledError(*, retry_after_seconds=None, details=None)

Bases: AbstractLlmError

Raised when a selected profile disables streaming.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def __init__(
    self,
    *,
    retry_after_seconds: float | None = None,
    details: JsonObject | None = None,
) -> None:
    super().__init__()
    if retry_after_seconds is not None and (
        not isfinite(retry_after_seconds) or retry_after_seconds < 0
    ):
        raise LlmConfigurationError
    self.retry_after_seconds = retry_after_seconds
    try:
        self.details = _snapshot_json_object({} if details is None else details)
    except RecursionError as error:
        raise LlmConfigurationError from error

LlmTransportError(*, retry_after_seconds=None, details=None)

Bases: AbstractLlmError

Raised when an official provider SDK cannot reach its endpoint.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def __init__(
    self,
    *,
    retry_after_seconds: float | None = None,
    details: JsonObject | None = None,
) -> None:
    super().__init__()
    if retry_after_seconds is not None and (
        not isfinite(retry_after_seconds) or retry_after_seconds < 0
    ):
        raise LlmConfigurationError
    self.retry_after_seconds = retry_after_seconds
    try:
        self.details = _snapshot_json_object({} if details is None else details)
    except RecursionError as error:
        raise LlmConfigurationError from error

LlmTimeoutError(*, retry_after_seconds=None, details=None)

Bases: AbstractLlmError

Raised when an official provider SDK request times out.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def __init__(
    self,
    *,
    retry_after_seconds: float | None = None,
    details: JsonObject | None = None,
) -> None:
    super().__init__()
    if retry_after_seconds is not None and (
        not isfinite(retry_after_seconds) or retry_after_seconds < 0
    ):
        raise LlmConfigurationError
    self.retry_after_seconds = retry_after_seconds
    try:
        self.details = _snapshot_json_object({} if details is None else details)
    except RecursionError as error:
        raise LlmConfigurationError from error

LlmRateLimitError(*, retry_after_seconds=None, details=None)

Bases: AbstractLlmError

Raised when a provider or local profile rate gate rejects an attempt.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def __init__(
    self,
    *,
    retry_after_seconds: float | None = None,
    details: JsonObject | None = None,
) -> None:
    super().__init__()
    if retry_after_seconds is not None and (
        not isfinite(retry_after_seconds) or retry_after_seconds < 0
    ):
        raise LlmConfigurationError
    self.retry_after_seconds = retry_after_seconds
    try:
        self.details = _snapshot_json_object({} if details is None else details)
    except RecursionError as error:
        raise LlmConfigurationError from error

LlmQuotaExhaustedError(*, retry_after_seconds=None, details=None)

Bases: AbstractLlmError

Raised when an account or plan allowance is spent and retrying cannot help.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def __init__(
    self,
    *,
    retry_after_seconds: float | None = None,
    details: JsonObject | None = None,
) -> None:
    super().__init__()
    if retry_after_seconds is not None and (
        not isfinite(retry_after_seconds) or retry_after_seconds < 0
    ):
        raise LlmConfigurationError
    self.retry_after_seconds = retry_after_seconds
    try:
        self.details = _snapshot_json_object({} if details is None else details)
    except RecursionError as error:
        raise LlmConfigurationError from error

LlmAuthenticationError(*, retry_after_seconds=None, details=None)

Bases: AbstractLlmError

Raised when a provider rejects the resolved credential.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def __init__(
    self,
    *,
    retry_after_seconds: float | None = None,
    details: JsonObject | None = None,
) -> None:
    super().__init__()
    if retry_after_seconds is not None and (
        not isfinite(retry_after_seconds) or retry_after_seconds < 0
    ):
        raise LlmConfigurationError
    self.retry_after_seconds = retry_after_seconds
    try:
        self.details = _snapshot_json_object({} if details is None else details)
    except RecursionError as error:
        raise LlmConfigurationError from error

LlmStreamInterruptedError(*, retry_after_seconds=None, details=None)

Bases: LlmTransportError

Raised when a provider stream ends before its terminal event.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def __init__(
    self,
    *,
    retry_after_seconds: float | None = None,
    details: JsonObject | None = None,
) -> None:
    super().__init__()
    if retry_after_seconds is not None and (
        not isfinite(retry_after_seconds) or retry_after_seconds < 0
    ):
        raise LlmConfigurationError
    self.retry_after_seconds = retry_after_seconds
    try:
        self.details = _snapshot_json_object({} if details is None else details)
    except RecursionError as error:
        raise LlmConfigurationError from error

LlmConcurrencyLimitError(*, retry_after_seconds=None, details=None)

Bases: AbstractLlmError

Raised when a profile concurrency gate cannot admit an attempt.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def __init__(
    self,
    *,
    retry_after_seconds: float | None = None,
    details: JsonObject | None = None,
) -> None:
    super().__init__()
    if retry_after_seconds is not None and (
        not isfinite(retry_after_seconds) or retry_after_seconds < 0
    ):
        raise LlmConfigurationError
    self.retry_after_seconds = retry_after_seconds
    try:
        self.details = _snapshot_json_object({} if details is None else details)
    except RecursionError as error:
        raise LlmConfigurationError from error

LlmCircuitOpenError(*, retry_after_seconds=None, details=None)

Bases: AbstractLlmError

Raised while a profile circuit rejects calls before provider execution.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def __init__(
    self,
    *,
    retry_after_seconds: float | None = None,
    details: JsonObject | None = None,
) -> None:
    super().__init__()
    if retry_after_seconds is not None and (
        not isfinite(retry_after_seconds) or retry_after_seconds < 0
    ):
        raise LlmConfigurationError
    self.retry_after_seconds = retry_after_seconds
    try:
        self.details = _snapshot_json_object({} if details is None else details)
    except RecursionError as error:
        raise LlmConfigurationError from error

LlmResponseError(*, retry_after_seconds=None, details=None)

Bases: AbstractLlmError

Raised when a provider response cannot satisfy Spakky contracts.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def __init__(
    self,
    *,
    retry_after_seconds: float | None = None,
    details: JsonObject | None = None,
) -> None:
    super().__init__()
    if retry_after_seconds is not None and (
        not isfinite(retry_after_seconds) or retry_after_seconds < 0
    ):
        raise LlmConfigurationError
    self.retry_after_seconds = retry_after_seconds
    try:
        self.details = _snapshot_json_object({} if details is None else details)
    except RecursionError as error:
        raise LlmConfigurationError from error

LlmModelRefusalError(*, retry_after_seconds=None, details=None)

Bases: AbstractLlmError

Raised when a provider reports a model refusal or content filter.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def __init__(
    self,
    *,
    retry_after_seconds: float | None = None,
    details: JsonObject | None = None,
) -> None:
    super().__init__()
    if retry_after_seconds is not None and (
        not isfinite(retry_after_seconds) or retry_after_seconds < 0
    ):
        raise LlmConfigurationError
    self.retry_after_seconds = retry_after_seconds
    try:
        self.details = _snapshot_json_object({} if details is None else details)
    except RecursionError as error:
        raise LlmConfigurationError from error

LlmCapabilityError(*, retry_after_seconds=None, details=None)

Bases: AbstractLlmError

Raised when no configured route can satisfy request capabilities.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def __init__(
    self,
    *,
    retry_after_seconds: float | None = None,
    details: JsonObject | None = None,
) -> None:
    super().__init__()
    if retry_after_seconds is not None and (
        not isfinite(retry_after_seconds) or retry_after_seconds < 0
    ):
        raise LlmConfigurationError
    self.retry_after_seconds = retry_after_seconds
    try:
        self.details = _snapshot_json_object({} if details is None else details)
    except RecursionError as error:
        raise LlmConfigurationError from error

LlmUnsupportedFeatureError(*, retry_after_seconds=None, details=None)

Bases: AbstractLlmError

Raised when a selected provider cannot honor a requested feature.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def __init__(
    self,
    *,
    retry_after_seconds: float | None = None,
    details: JsonObject | None = None,
) -> None:
    super().__init__()
    if retry_after_seconds is not None and (
        not isfinite(retry_after_seconds) or retry_after_seconds < 0
    ):
        raise LlmConfigurationError
    self.retry_after_seconds = retry_after_seconds
    try:
        self.details = _snapshot_json_object({} if details is None else details)
    except RecursionError as error:
        raise LlmConfigurationError from error

LlmCacheConfigurationError(*, retry_after_seconds=None, details=None)

Bases: AbstractLlmError

Raised when an enabled cache mode has no exact replaceable backend.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def __init__(
    self,
    *,
    retry_after_seconds: float | None = None,
    details: JsonObject | None = None,
) -> None:
    super().__init__()
    if retry_after_seconds is not None and (
        not isfinite(retry_after_seconds) or retry_after_seconds < 0
    ):
        raise LlmConfigurationError
    self.retry_after_seconds = retry_after_seconds
    try:
        self.details = _snapshot_json_object({} if details is None else details)
    except RecursionError as error:
        raise LlmConfigurationError from error

LlmPlatformBoundaryError(*, retry_after_seconds=None, details=None)

Bases: AbstractLlmError

Raised for invalid optional batch, file, or native-tool requests.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
def __init__(
    self,
    *,
    retry_after_seconds: float | None = None,
    details: JsonObject | None = None,
) -> None:
    super().__init__()
    if retry_after_seconds is not None and (
        not isfinite(retry_after_seconds) or retry_after_seconds < 0
    ):
        raise LlmConfigurationError
    self.retry_after_seconds = retry_after_seconds
    try:
        self.details = _snapshot_json_object({} if details is None else details)
    except RecursionError as error:
        raise LlmConfigurationError from error

Defaults for the spakky-llm plugin.

Provider adapter

OpenAI SDK adapter for standard and vLLM chat-completions profiles.

OpenAIChatProvider(credential_providers=())

Bases: ILLMProvider

Map OpenAI SDK chat completions onto the Spakky model contract.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/providers/openai.py
def __init__(
    self,
    credential_providers: tuple[ILLMCredentialProvider, ...] = (),
) -> None:
    self.__codec = LlmJsonCodec()
    registry: dict[str, ILLMCredentialProvider] = {}
    for credential_provider in credential_providers:
        if credential_provider.name in registry:
            raise LlmConfigurationError
        registry[credential_provider.name] = credential_provider
    self.__credential_providers = registry

apis property

Return the OpenAI chat-completions API family.

is_default property

Mark the first-party OpenAI adapter as replaceable default.

complete(target, request) async

Return one normalized completion through the official async SDK.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/providers/openai.py
@override
async def complete(
    self,
    target: LlmModelTarget,
    request: ModelRequest,
) -> ModelResponse:
    """Return one normalized completion through the official async SDK."""
    self._ensure_supported_request(target, request)
    messages = self._messages(target, request)

    async def create(client: AsyncOpenAI) -> ChatCompletion:
        return await client.chat.completions.create(
            model=target.model,
            messages=messages,
            stream=False,
            temperature=self._optional_number(request.sampling.temperature),
            top_p=self._optional_number(request.sampling.top_p),
            max_tokens=self._legacy_max_tokens(target, request),
            max_completion_tokens=self._standard_max_tokens(target, request),
            tools=self._tools(request),
            tool_choice=self._tool_choice(request),
            response_format=self._response_format(request),
            extra_body=self._extra_body(target, request),
            timeout=target.profile.request_timeout_seconds,
        )

    try:
        async with AsyncExitStack() as stack:
            completion = await self._authorized(stack, target, request, create)
    except APIError as error:
        raise self._normalized_sdk_error(error) from error
    except JSONDecodeError as error:
        raise LlmResponseError from error
    try:
        return self._response(target, request, completion)
    except (AttributeError, TypeError) as error:
        raise LlmResponseError from error

stream(target, request)

Return normalized events from an official SDK async stream.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/providers/openai.py
@override
def stream(
    self,
    target: LlmModelTarget,
    request: ModelRequest,
) -> AsyncIterator[ModelStreamEvent]:
    """Return normalized events from an official SDK async stream."""
    return self._stream(target, request)

OpenAI SDK adapter for Responses API profiles, including ChatGPT sign-in.

OpenAIResponsesProvider(credential_providers=())

Bases: ILLMProvider

Map OpenAI Responses SSE streams onto the Spakky model contract.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/providers/openai_responses.py
def __init__(
    self,
    credential_providers: tuple[ILLMCredentialProvider, ...] = (),
) -> None:
    self.__codec = LlmJsonCodec()
    registry: dict[str, ILLMCredentialProvider] = {}
    for credential_provider in credential_providers:
        if credential_provider.name in registry:
            raise LlmConfigurationError
        registry[credential_provider.name] = credential_provider
    self.__credential_providers = registry

apis property

Return the OpenAI Responses API family.

is_default property

Mark the first-party Responses adapter as replaceable default.

complete(target, request) async

Return one completion aggregated from the Responses SSE stream.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/providers/openai_responses.py
@override
async def complete(
    self,
    target: LlmModelTarget,
    request: ModelRequest,
) -> ModelResponse:
    """Return one completion aggregated from the Responses SSE stream."""
    turn = _ResponseTurn()
    async for _ in self._events(
        target,
        request,
        turn,
        target.profile.request_timeout_seconds,
    ):
        continue
    metadata: dict[str, JsonValue] = self._metadata(target)
    metadata.update(turn.response_metadata)
    metadata["finish_reason"] = turn.finish_reason
    if len(turn.reasoning_fragments) > 0:
        metadata["reasoning"] = "".join(turn.reasoning_fragments)
    return ModelResponse(
        content="".join(turn.text_fragments),
        structured_output=turn.structured_output,
        tool_calls=turn.tool_calls,
        usage=turn.usage,
        metadata=metadata,
    )

stream(target, request)

Return normalized events from the Responses SSE stream.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/providers/openai_responses.py
@override
def stream(
    self,
    target: LlmModelTarget,
    request: ModelRequest,
) -> AsyncIterator[ModelStreamEvent]:
    """Return normalized events from the Responses SSE stream."""
    return self._stream(target, request)

Anthropic Messages adapter backed by the official async Python SDK.

AnthropicMessagesProvider()

Bases: ILLMProvider

Translate Spakky model contracts to Anthropic's native Messages API.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/providers/anthropic.py
def __init__(self) -> None:
    self.__codec = LlmJsonCodec()

apis property

Return the native Anthropic Messages API family.

is_default property

Mark the first-party Anthropic adapter as replaceable default.

complete(target, request) async

Return one provider-neutral completion through AsyncAnthropic.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/providers/anthropic.py
@override
async def complete(
    self,
    target: LlmModelTarget,
    request: ModelRequest,
) -> ModelResponse:
    """Return one provider-neutral completion through ``AsyncAnthropic``."""
    self._ensure_supported_request(target, request)
    messages, system = self._history(request)
    constraints = self.__codec.tool_constraints(request.tool_calling)
    try:
        async with self._client(
            target,
            target.profile.request_timeout_seconds,
        ) as client:
            response = await client.messages.create(
                max_tokens=self._max_tokens(target, request),
                messages=messages,
                model=target.model,
                output_config=self._output_config(request),
                system=system,
                tool_choice=self._tool_choice(request),
                tools=self._tools(request),
                extra_body=self._sampling_body(request),
            )
    except APIError as sdk_error:
        raise self._provider_error(sdk_error) from sdk_error
    except JSONDecodeError as sdk_error:
        raise LlmResponseError from sdk_error
    try:
        return self._response(target, request, response, constraints)
    except (AttributeError, TypeError) as sdk_error:
        raise LlmResponseError from sdk_error

stream(target, request)

Return SDK-managed message, tool, usage, and terminal events.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/providers/anthropic.py
@override
def stream(
    self,
    target: LlmModelTarget,
    request: ModelRequest,
) -> AsyncIterator[ModelStreamEvent]:
    """Return SDK-managed message, tool, usage, and terminal events."""
    return self._stream(target, request)

Google Gemini provider implemented with the official Google Gen AI SDK.

GoogleGenerateContentProvider()

Bases: ILLMProvider

Adapt Gemini GenerateContent responses to provider-neutral contracts.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/providers/google.py
def __init__(self) -> None:
    self.__codec = LlmJsonCodec()

apis property

Return both Google GenerateContent connection backends.

is_default property

Mark the first-party Google adapter as replaceable default.

complete(target, request) async

Return one Gemini response through the official async SDK client.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/providers/google.py
@override
async def complete(
    self,
    target: LlmModelTarget,
    request: ModelRequest,
) -> ModelResponse:
    """Return one Gemini response through the official async SDK client."""
    self._ensure_supported_request(target, request)
    constraints = self.__codec.tool_constraints(request.tool_calling)
    contents = self._contents(request)
    config = self._generate_config(target, request)
    client = self._client(
        target,
        timeout_seconds=target.profile.request_timeout_seconds,
    )
    try:
        async with client.aio as async_client:
            response = await async_client.models.generate_content(
                model=target.model,
                contents=contents,
                config=config,
            )
    except errors.APIError as error:
        self._raise_api_error(error)
    except (
        errors.UnknownApiResponseError,
        JSONDecodeError,
        TypeError,
        ValidationError,
        httpx.DecodingError,
    ) as error:
        raise LlmResponseError from error
    except (httpx.InvalidURL, httpx.UnsupportedProtocol) as error:
        raise LlmConfigurationError from error
    except httpx.TimeoutException as error:
        raise LlmTimeoutError from error
    except httpx.RequestError as error:
        raise LlmTransportError from error
    except GoogleAuthTransportError as error:
        raise LlmTransportError from error
    except GoogleAuthError as error:
        raise LlmConfigurationError from error
    finally:
        client.close()
    return self._response(target, request, response, constraints)

stream(target, request)

Stream Gemini parts through provider-neutral event kinds.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/providers/google.py
@override
def stream(
    self,
    target: LlmModelTarget,
    request: ModelRequest,
) -> AsyncIterator[ModelStreamEvent]:
    """Stream Gemini parts through provider-neutral event kinds."""
    return self._stream(target, request)

GoogleTextEmbedding(target, *, output_dimensionality=None)

Bases: ITextEmbedding

Embed text through an explicit operator-owned Google model route.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/providers/google.py
def __init__(
    self,
    target: LlmModelTarget,
    *,
    output_dimensionality: int | None = None,
) -> None:
    if (
        not isinstance(target.model_ref, str)
        or not target.model_ref.strip()
        or not isinstance(target.profile_name, str)
        or not target.profile_name.strip()
        or not isinstance(target.model, str)
        or not target.model.strip()
        or target.route.profile != target.profile_name
    ):
        raise LlmConfigurationError
    if target.profile.api not in (
        LlmProviderApi.GOOGLE_GEMINI_DEVELOPER,
        LlmProviderApi.GOOGLE_VERTEX,
    ):
        raise LlmConfigurationError
    if output_dimensionality is not None and (
        isinstance(output_dimensionality, bool)
        or not isinstance(output_dimensionality, int)
        or output_dimensionality <= 0
    ):
        raise LlmConfigurationError
    self._target = deepcopy(target)
    self._output_dimensionality = output_dimensionality
    self._transport = GoogleGenerateContentProvider()

from_config(config, model_ref, *, output_dimensionality=None) classmethod

Resolve and snapshot one opaque embedding route from an LLM catalog.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/providers/google.py
@classmethod
def from_config(
    cls,
    config: LlmConfig,
    model_ref: str,
    *,
    output_dimensionality: int | None = None,
) -> "GoogleTextEmbedding":
    """Resolve and snapshot one opaque embedding route from an LLM catalog."""
    if not isinstance(model_ref, str):
        raise LlmConfigurationError
    normalized_ref = model_ref.strip()
    if not normalized_ref:
        raise LlmConfigurationError
    route = config.models.get(normalized_ref)
    if route is None:
        raise LlmConfigurationError
    profile = config.profiles.get(route.profile)
    if profile is None:
        raise LlmConfigurationError
    return cls(
        LlmModelTarget(
            model_ref=normalized_ref,
            profile_name=route.profile,
            profile=profile,
            route=route,
        ),
        output_dimensionality=output_dimensionality,
    )

embed(texts, purpose) async

Return one validated vector per input without silent truncation.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/providers/google.py
@override
async def embed(
    self,
    texts: Sequence[str],
    purpose: EmbeddingPurpose,
) -> Sequence[EmbeddingVector]:
    """Return one validated vector per input without silent truncation."""
    if isinstance(texts, str | bytes) or not texts:
        raise LlmConfigurationError
    inputs = tuple(texts)
    if any(not isinstance(text, str) or not text.strip() for text in inputs):
        raise LlmConfigurationError
    task_type = {
        EmbeddingPurpose.QUERY: "RETRIEVAL_QUERY",
        EmbeddingPurpose.DOCUMENT: "RETRIEVAL_DOCUMENT",
    }.get(purpose)
    if task_type is None:
        raise LlmConfigurationError
    client = self._transport._client(
        self._target,
        timeout_seconds=self._target.profile.request_timeout_seconds,
    )
    try:
        async with client.aio as async_client:
            response = await async_client.models.embed_content(
                model=self._target.model,
                contents=list(inputs),
                config=types.EmbedContentConfig(
                    task_type=task_type,
                    output_dimensionality=self._output_dimensionality,
                ),
            )
    except errors.APIError as error:
        self._transport._raise_api_error(error)
    except (
        errors.UnknownApiResponseError,
        JSONDecodeError,
        TypeError,
        ValidationError,
        httpx.DecodingError,
        AgentRetrievalError,
    ) as error:
        raise LlmResponseError from error
    except (httpx.InvalidURL, httpx.UnsupportedProtocol) as error:
        raise LlmConfigurationError from error
    except httpx.TimeoutException as error:
        raise LlmTimeoutError from error
    except httpx.RequestError as error:
        raise LlmTransportError from error
    except GoogleAuthTransportError as error:
        raise LlmTransportError from error
    except GoogleAuthError as error:
        raise LlmConfigurationError from error
    finally:
        client.close()
    if not isinstance(response, types.EmbedContentResponse):
        raise LlmResponseError
    embeddings = response.embeddings
    if embeddings is None or len(embeddings) != len(inputs):
        raise LlmResponseError
    vectors: list[EmbeddingVector] = []
    for embedding in embeddings:
        if not isinstance(embedding, types.ContentEmbedding):
            raise LlmResponseError
        if embedding.statistics is not None and embedding.statistics.truncated:
            raise LlmResponseError
        values = embedding.values
        if values is None or any(
            not isinstance(value, int | float) or isinstance(value, bool)
            for value in values
        ):
            raise LlmResponseError
        try:
            vector = EmbeddingVector(tuple(values))
        except AgentRetrievalError as error:
            raise LlmResponseError from error
        if (
            self._output_dimensionality is not None
            and vector.dimension != self._output_dimensionality
        ):
            raise LlmResponseError
        if vectors and vector.dimension != vectors[0].dimension:
            raise LlmResponseError
        vectors.append(vector)
    return tuple(vectors)

Plugin entry point

Plugin initialization for the multi-provider LLM adapter.

initialize(app)

Register replaceable first-party SDK defaults and the catalog router.

Source code in plugins/spakky-llm/src/spakky/plugins/llm/main.py
def initialize(app: SpakkyApplication) -> None:
    """Register replaceable first-party SDK defaults and the catalog router."""
    app.add(LlmConfig)
    app.add(OpenAIChatProvider)
    app.add(OpenAIResponsesProvider)
    app.add(AnthropicMessagesProvider)
    app.add(GoogleGenerateContentProvider)
    app.add(LlmAgentModel)
    app.container.bind_to_type(IAgentModel, LlmAgentModel)