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를 호출하도록 구성됩니다.
설치와 로드¶
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검증을 다시 거칩니다(modelstrip, 문자열"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_unsupportederror 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 |
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 경로는 다음과 같습니다.
권장 생성 경계는
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.
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
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
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
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
validate_request(request)
¶
Accept when any explicitly reachable candidate satisfies the request.
Source code in plugins/spakky-llm/src/spakky/plugins/llm/model.py
complete(request)
async
¶
Complete through bounded retries and explicitly ordered fallbacks.
Source code in plugins/spakky-llm/src/spakky/plugins/llm/model.py
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 | |
stream(request)
¶
Stream with pre-emission retry/fallback and no response-cache replay.
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
¶
stream(target, request)
abstractmethod
¶
Return provider-neutral streaming events.
LlmCredentialRequest(profile_name, request, rejected_token=None)
dataclass
¶
One credential lookup for the caller behind a provider attempt.
ILLMCredentialProvider
¶
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
¶
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.
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.
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
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
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
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
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
error_event(error, target, metadata=None)
¶
Return one normalized terminal error event.
Source code in plugins/spakky-llm/src/spakky/plugins/llm/provider.py
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
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.
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
ILLMCacheScopeResolver
¶
Bases: ABC
Resolve trusted tenant and safety partitions independently of metadata keys.
resolve(request)
abstractmethod
¶
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
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 | |
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
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
¶
SystemLlmClock
¶
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
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
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
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
release(lease)
async
¶
Release concurrency and abandoned half-open reservations once.
Source code in plugins/spakky-llm/src/spakky/plugins/llm/resilience.py
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
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
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.
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
오류와 상수¶
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
annotate(details)
¶
Attach privacy-safe orchestration evidence before propagation.
Source code in plugins/spakky-llm/src/spakky/plugins/llm/error.py
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
stream(target, request)
¶
Stream Gemini parts through provider-neutral event kinds.
Source code in plugins/spakky-llm/src/spakky/plugins/llm/providers/google.py
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
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
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
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 | |
Plugin entry point¶
Plugin initialization for the multi-provider LLM adapter.
initialize(app)
¶
Register replaceable first-party SDK defaults and the catalog router.