incierge 0.2.1__py3-none-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- incierge/__init__.py +5 -0
- incierge/_bin/__init__.py +1 -0
- incierge/_bin/incierge-kernel.exe +0 -0
- incierge/adapter/__init__.py +85 -0
- incierge/adapter/anthropic.py +154 -0
- incierge/adapter/base.py +168 -0
- incierge/adapter/gemini.py +168 -0
- incierge/adapter/local.py +64 -0
- incierge/adapter/openai.py +161 -0
- incierge/broker/__init__.py +3 -0
- incierge/broker/lock.py +247 -0
- incierge/capacity/__init__.py +32 -0
- incierge/capacity/router.py +274 -0
- incierge/cli.py +559 -0
- incierge/core/__init__.py +3 -0
- incierge/core/sprint.py +97 -0
- incierge/gate/__init__.py +3 -0
- incierge/gate/selfcheck.py +144 -0
- incierge/guard/__init__.py +24 -0
- incierge/guard/mcp_server.py +564 -0
- incierge/harness/__init__.py +28 -0
- incierge/harness/hook_chain.py +306 -0
- incierge/harness/hook_runner.py +92 -0
- incierge/harness/installer.py +199 -0
- incierge/kernel/__init__.py +18 -0
- incierge/kernel/bridge.py +164 -0
- incierge/loop/__init__.py +36 -0
- incierge/loop/engine.py +614 -0
- incierge/review/__init__.py +24 -0
- incierge/review/contract.py +249 -0
- incierge/sandbox/__init__.py +12 -0
- incierge/sandbox/hook.py +116 -0
- incierge/sandbox/interceptor.py +589 -0
- incierge/sandbox/mcp.py +244 -0
- incierge-0.2.1.dist-info/METADATA +357 -0
- incierge-0.2.1.dist-info/RECORD +41 -0
- incierge-0.2.1.dist-info/WHEEL +5 -0
- incierge-0.2.1.dist-info/entry_points.txt +4 -0
- incierge-0.2.1.dist-info/licenses/LICENSE +202 -0
- incierge-0.2.1.dist-info/licenses/NOTICE +32 -0
- incierge-0.2.1.dist-info/top_level.txt +1 -0
incierge/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Bundled native incierge-kernel binary directory."""
|
|
Binary file
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""incierge.adapter — Multi-runtime portable model execution adapters.
|
|
4
|
+
|
|
5
|
+
Provides a unified interface to execute inference requests across Anthropic, OpenAI,
|
|
6
|
+
Google Gemini, and local OpenAI-compatible servers (`muse` / `gemma` / `mlx` / `llamacpp`)
|
|
7
|
+
with zero external dependencies.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Dict, Optional, Type
|
|
12
|
+
|
|
13
|
+
from incierge.adapter.anthropic import AnthropicAdapter
|
|
14
|
+
from incierge.adapter.base import (
|
|
15
|
+
AdapterError,
|
|
16
|
+
BaseAdapter,
|
|
17
|
+
Message,
|
|
18
|
+
ModelRequest,
|
|
19
|
+
ModelResponse,
|
|
20
|
+
ToolCall,
|
|
21
|
+
ToolDefinition,
|
|
22
|
+
Usage,
|
|
23
|
+
)
|
|
24
|
+
from incierge.adapter.gemini import GeminiAdapter
|
|
25
|
+
from incierge.adapter.local import LocalOpenAIAdapter
|
|
26
|
+
from incierge.adapter.openai import OpenAIAdapter
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"AdapterError",
|
|
30
|
+
"AnthropicAdapter",
|
|
31
|
+
"BaseAdapter",
|
|
32
|
+
"GeminiAdapter",
|
|
33
|
+
"LocalOpenAIAdapter",
|
|
34
|
+
"Message",
|
|
35
|
+
"ModelRequest",
|
|
36
|
+
"ModelResponse",
|
|
37
|
+
"OpenAIAdapter",
|
|
38
|
+
"ToolCall",
|
|
39
|
+
"ToolDefinition",
|
|
40
|
+
"Usage",
|
|
41
|
+
"get_adapter",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
_PROVIDER_REGISTRY: Dict[str, Type[BaseAdapter]] = {
|
|
45
|
+
"anthropic": AnthropicAdapter,
|
|
46
|
+
"claude": AnthropicAdapter,
|
|
47
|
+
"openai": OpenAIAdapter,
|
|
48
|
+
"codex": OpenAIAdapter,
|
|
49
|
+
"gemini": GeminiAdapter,
|
|
50
|
+
"google": GeminiAdapter,
|
|
51
|
+
"antigravity": GeminiAdapter,
|
|
52
|
+
"agy": GeminiAdapter,
|
|
53
|
+
"local": LocalOpenAIAdapter,
|
|
54
|
+
"muse": LocalOpenAIAdapter,
|
|
55
|
+
"gemma": LocalOpenAIAdapter,
|
|
56
|
+
"mlx": LocalOpenAIAdapter,
|
|
57
|
+
"llamacpp": LocalOpenAIAdapter,
|
|
58
|
+
"ollama": LocalOpenAIAdapter,
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def get_adapter(provider_or_model: str, default_model: Optional[str] = None) -> BaseAdapter:
|
|
63
|
+
"""Resolve and return an adapter instance for the given provider or model name."""
|
|
64
|
+
key = provider_or_model.strip().lower()
|
|
65
|
+
|
|
66
|
+
if key in _PROVIDER_REGISTRY:
|
|
67
|
+
cls = _PROVIDER_REGISTRY[key]
|
|
68
|
+
return cls(default_model=default_model)
|
|
69
|
+
|
|
70
|
+
if key.startswith("claude"):
|
|
71
|
+
return AnthropicAdapter(default_model=provider_or_model)
|
|
72
|
+
|
|
73
|
+
if key.startswith(("gpt", "o1", "o3", "o4", "text-embedding")):
|
|
74
|
+
return OpenAIAdapter(default_model=provider_or_model)
|
|
75
|
+
|
|
76
|
+
if key.startswith("gemini"):
|
|
77
|
+
return GeminiAdapter(default_model=provider_or_model)
|
|
78
|
+
|
|
79
|
+
if key.startswith(("muse", "gemma", "local-")):
|
|
80
|
+
return LocalOpenAIAdapter(default_model=provider_or_model)
|
|
81
|
+
|
|
82
|
+
raise ValueError(
|
|
83
|
+
f"Unsupported provider or model name: '{provider_or_model}'. "
|
|
84
|
+
f"Supported providers: {sorted(set(_PROVIDER_REGISTRY.keys()))}"
|
|
85
|
+
)
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""incierge.adapter.anthropic — Anthropic Claude model execution adapter.
|
|
4
|
+
|
|
5
|
+
Standard library implementation of Anthropic Messages API format (/v1/messages).
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
from typing import Any, Dict, List, Optional
|
|
11
|
+
|
|
12
|
+
from incierge.adapter.base import (
|
|
13
|
+
AdapterError,
|
|
14
|
+
BaseAdapter,
|
|
15
|
+
Message,
|
|
16
|
+
ModelRequest,
|
|
17
|
+
ModelResponse,
|
|
18
|
+
ToolCall,
|
|
19
|
+
Usage,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class AnthropicAdapter(BaseAdapter):
|
|
24
|
+
"""Execution adapter for Anthropic Claude models."""
|
|
25
|
+
|
|
26
|
+
DEFAULT_MODEL = "claude-3-5-sonnet-latest"
|
|
27
|
+
DEFAULT_API_URL = "https://api.anthropic.com/v1/messages"
|
|
28
|
+
API_VERSION = "2023-06-01"
|
|
29
|
+
|
|
30
|
+
def get_endpoint_url(self, request: ModelRequest, api_key: Optional[str] = None) -> str:
|
|
31
|
+
return os.environ.get("ANTHROPIC_BASE_URL", self.DEFAULT_API_URL)
|
|
32
|
+
|
|
33
|
+
def get_headers(self, request: ModelRequest, api_key: Optional[str] = None) -> Dict[str, str]:
|
|
34
|
+
key = api_key or os.environ.get("ANTHROPIC_API_KEY", "")
|
|
35
|
+
if not key:
|
|
36
|
+
raise AdapterError("ANTHROPIC_API_KEY is not configured or provided")
|
|
37
|
+
return {
|
|
38
|
+
"x-api-key": key,
|
|
39
|
+
"anthropic-version": self.API_VERSION,
|
|
40
|
+
"content-type": "application/json",
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
def format_request(self, request: ModelRequest) -> Dict[str, Any]:
|
|
44
|
+
system_prompts: List[str] = []
|
|
45
|
+
if request.system_prompt:
|
|
46
|
+
system_prompts.append(request.system_prompt)
|
|
47
|
+
|
|
48
|
+
messages_payload: List[Dict[str, Any]] = []
|
|
49
|
+
|
|
50
|
+
for msg in request.messages:
|
|
51
|
+
if msg.role == "system":
|
|
52
|
+
system_prompts.append(msg.content)
|
|
53
|
+
continue
|
|
54
|
+
|
|
55
|
+
if msg.role == "tool":
|
|
56
|
+
# Tool responses are wrapped as user messages with tool_result content block
|
|
57
|
+
content_block = {
|
|
58
|
+
"type": "tool_result",
|
|
59
|
+
"tool_use_id": msg.tool_call_id or "",
|
|
60
|
+
"content": msg.content,
|
|
61
|
+
}
|
|
62
|
+
messages_payload.append({
|
|
63
|
+
"role": "user",
|
|
64
|
+
"content": [content_block],
|
|
65
|
+
})
|
|
66
|
+
continue
|
|
67
|
+
|
|
68
|
+
# Assistant role
|
|
69
|
+
if msg.role == "assistant":
|
|
70
|
+
blocks: List[Dict[str, Any]] = []
|
|
71
|
+
if msg.content:
|
|
72
|
+
blocks.append({"type": "text", "text": msg.content})
|
|
73
|
+
if msg.tool_calls:
|
|
74
|
+
for tc in msg.tool_calls:
|
|
75
|
+
blocks.append({
|
|
76
|
+
"type": "tool_use",
|
|
77
|
+
"id": tc.id,
|
|
78
|
+
"name": tc.name,
|
|
79
|
+
"input": tc.arguments,
|
|
80
|
+
})
|
|
81
|
+
messages_payload.append({
|
|
82
|
+
"role": "assistant",
|
|
83
|
+
"content": blocks if blocks else msg.content,
|
|
84
|
+
})
|
|
85
|
+
continue
|
|
86
|
+
|
|
87
|
+
# Standard user role
|
|
88
|
+
messages_payload.append({
|
|
89
|
+
"role": "user",
|
|
90
|
+
"content": msg.content,
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
payload: Dict[str, Any] = {
|
|
94
|
+
"model": request.model or self.default_model or self.DEFAULT_MODEL,
|
|
95
|
+
"messages": messages_payload,
|
|
96
|
+
"max_tokens": request.max_tokens if request.max_tokens is not None else 4096,
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if system_prompts:
|
|
100
|
+
payload["system"] = "\n\n".join(system_prompts)
|
|
101
|
+
|
|
102
|
+
if request.temperature is not None:
|
|
103
|
+
payload["temperature"] = request.temperature
|
|
104
|
+
|
|
105
|
+
if request.stop_sequences:
|
|
106
|
+
payload["stop_sequences"] = request.stop_sequences
|
|
107
|
+
|
|
108
|
+
if request.tools:
|
|
109
|
+
tools_payload = []
|
|
110
|
+
for t in request.tools:
|
|
111
|
+
tools_payload.append({
|
|
112
|
+
"name": t.name,
|
|
113
|
+
"description": t.description,
|
|
114
|
+
"input_schema": t.parameters if t.parameters else {"type": "object"},
|
|
115
|
+
})
|
|
116
|
+
payload["tools"] = tools_payload
|
|
117
|
+
|
|
118
|
+
return payload
|
|
119
|
+
|
|
120
|
+
def parse_response(self, raw_json: Dict[str, Any]) -> ModelResponse:
|
|
121
|
+
text_parts: List[str] = []
|
|
122
|
+
tool_calls: List[ToolCall] = []
|
|
123
|
+
|
|
124
|
+
content_blocks = raw_json.get("content", [])
|
|
125
|
+
if isinstance(content_blocks, list):
|
|
126
|
+
for block in content_blocks:
|
|
127
|
+
b_type = block.get("type")
|
|
128
|
+
if b_type == "text":
|
|
129
|
+
text_parts.append(block.get("text", ""))
|
|
130
|
+
elif b_type == "tool_use":
|
|
131
|
+
tool_calls.append(ToolCall(
|
|
132
|
+
id=str(block.get("id", "")),
|
|
133
|
+
name=str(block.get("name", "")),
|
|
134
|
+
arguments=block.get("input", {}),
|
|
135
|
+
))
|
|
136
|
+
elif isinstance(content_blocks, str):
|
|
137
|
+
text_parts.append(content_blocks)
|
|
138
|
+
|
|
139
|
+
usage_raw = raw_json.get("usage", {})
|
|
140
|
+
inp_tokens = usage_raw.get("input_tokens", 0)
|
|
141
|
+
out_tokens = usage_raw.get("output_tokens", 0)
|
|
142
|
+
usage = Usage(
|
|
143
|
+
input_tokens=inp_tokens,
|
|
144
|
+
output_tokens=out_tokens,
|
|
145
|
+
total_tokens=inp_tokens + out_tokens,
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
return ModelResponse(
|
|
149
|
+
content="".join(text_parts),
|
|
150
|
+
tool_calls=tool_calls,
|
|
151
|
+
usage=usage,
|
|
152
|
+
stop_reason=raw_json.get("stop_reason"),
|
|
153
|
+
raw_response=raw_json,
|
|
154
|
+
)
|
incierge/adapter/base.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""incierge.adapter.base — Zero-dependency multi-runtime model execution interface.
|
|
4
|
+
|
|
5
|
+
Provides normalized abstractions for LLM chat requests, responses, tool definitions,
|
|
6
|
+
and execution adapters across various inference providers without external SDK dependencies.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import urllib.error
|
|
12
|
+
import urllib.request
|
|
13
|
+
from abc import ABC, abstractmethod
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from typing import Any, Dict, List, Optional
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class ToolDefinition:
|
|
20
|
+
name: str
|
|
21
|
+
description: str
|
|
22
|
+
parameters: Dict[str, Any] = field(default_factory=dict)
|
|
23
|
+
|
|
24
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
25
|
+
return {
|
|
26
|
+
"name": self.name,
|
|
27
|
+
"description": self.description,
|
|
28
|
+
"parameters": self.parameters,
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class ToolCall:
|
|
34
|
+
id: str
|
|
35
|
+
name: str
|
|
36
|
+
arguments: Dict[str, Any] = field(default_factory=dict)
|
|
37
|
+
|
|
38
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
39
|
+
return {
|
|
40
|
+
"id": self.id,
|
|
41
|
+
"name": self.name,
|
|
42
|
+
"arguments": self.arguments,
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class Message:
|
|
48
|
+
role: str # "system", "user", "assistant", "tool"
|
|
49
|
+
content: str
|
|
50
|
+
tool_calls: Optional[List[ToolCall]] = None
|
|
51
|
+
tool_call_id: Optional[str] = None
|
|
52
|
+
|
|
53
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
54
|
+
d: Dict[str, Any] = {"role": self.role, "content": self.content}
|
|
55
|
+
if self.tool_calls:
|
|
56
|
+
d["tool_calls"] = [tc.to_dict() for tc in self.tool_calls]
|
|
57
|
+
if self.tool_call_id:
|
|
58
|
+
d["tool_call_id"] = self.tool_call_id
|
|
59
|
+
return d
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class Usage:
|
|
64
|
+
input_tokens: int = 0
|
|
65
|
+
output_tokens: int = 0
|
|
66
|
+
total_tokens: int = 0
|
|
67
|
+
|
|
68
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
69
|
+
return {
|
|
70
|
+
"input_tokens": self.input_tokens,
|
|
71
|
+
"output_tokens": self.output_tokens,
|
|
72
|
+
"total_tokens": self.total_tokens,
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass
|
|
77
|
+
class ModelRequest:
|
|
78
|
+
model: str
|
|
79
|
+
messages: List[Message]
|
|
80
|
+
tools: Optional[List[ToolDefinition]] = None
|
|
81
|
+
temperature: Optional[float] = None
|
|
82
|
+
max_tokens: Optional[int] = None
|
|
83
|
+
system_prompt: Optional[str] = None
|
|
84
|
+
stop_sequences: Optional[List[str]] = None
|
|
85
|
+
extra_headers: Optional[Dict[str, str]] = None
|
|
86
|
+
timeout: float = 60.0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@dataclass
|
|
90
|
+
class ModelResponse:
|
|
91
|
+
content: str
|
|
92
|
+
tool_calls: List[ToolCall] = field(default_factory=list)
|
|
93
|
+
usage: Usage = field(default_factory=Usage)
|
|
94
|
+
stop_reason: Optional[str] = None
|
|
95
|
+
raw_response: Dict[str, Any] = field(default_factory=dict)
|
|
96
|
+
|
|
97
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
98
|
+
return {
|
|
99
|
+
"content": self.content,
|
|
100
|
+
"tool_calls": [tc.to_dict() for tc in self.tool_calls],
|
|
101
|
+
"usage": self.usage.to_dict(),
|
|
102
|
+
"stop_reason": self.stop_reason,
|
|
103
|
+
"raw_response": self.raw_response,
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class AdapterError(Exception):
|
|
108
|
+
"""Base exception for model execution adapter failures."""
|
|
109
|
+
|
|
110
|
+
def __init__(self, message: str, status_code: Optional[int] = None, response_body: Optional[str] = None):
|
|
111
|
+
super().__init__(message)
|
|
112
|
+
self.status_code = status_code
|
|
113
|
+
self.response_body = response_body
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class BaseAdapter(ABC):
|
|
117
|
+
"""Abstract base adapter for LLM inference execution."""
|
|
118
|
+
|
|
119
|
+
def __init__(self, default_model: Optional[str] = None):
|
|
120
|
+
self.default_model = default_model
|
|
121
|
+
|
|
122
|
+
@abstractmethod
|
|
123
|
+
def format_request(self, request: ModelRequest) -> Dict[str, Any]:
|
|
124
|
+
"""Convert standard ModelRequest into provider payload."""
|
|
125
|
+
pass
|
|
126
|
+
|
|
127
|
+
@abstractmethod
|
|
128
|
+
def parse_response(self, raw_json: Dict[str, Any]) -> ModelResponse:
|
|
129
|
+
"""Parse provider response payload into standard ModelResponse."""
|
|
130
|
+
pass
|
|
131
|
+
|
|
132
|
+
@abstractmethod
|
|
133
|
+
def get_endpoint_url(self, request: ModelRequest, api_key: Optional[str] = None) -> str:
|
|
134
|
+
"""Return the API endpoint URL for HTTP request."""
|
|
135
|
+
pass
|
|
136
|
+
|
|
137
|
+
@abstractmethod
|
|
138
|
+
def get_headers(self, request: ModelRequest, api_key: Optional[str] = None) -> Dict[str, str]:
|
|
139
|
+
"""Return HTTP headers for authentication and content type."""
|
|
140
|
+
pass
|
|
141
|
+
|
|
142
|
+
def execute(self, request: ModelRequest, api_key: Optional[str] = None) -> ModelResponse:
|
|
143
|
+
"""Execute request via standard library urllib.request."""
|
|
144
|
+
url = self.get_endpoint_url(request, api_key)
|
|
145
|
+
headers = self.get_headers(request, api_key)
|
|
146
|
+
if request.extra_headers:
|
|
147
|
+
headers.update(request.extra_headers)
|
|
148
|
+
|
|
149
|
+
payload = self.format_request(request)
|
|
150
|
+
data = json.dumps(payload).encode("utf-8")
|
|
151
|
+
|
|
152
|
+
req = urllib.request.Request(url, data=data, headers=headers, method="POST")
|
|
153
|
+
try:
|
|
154
|
+
with urllib.request.urlopen(req, timeout=request.timeout) as resp:
|
|
155
|
+
resp_bytes = resp.read()
|
|
156
|
+
resp_json = json.loads(resp_bytes.decode("utf-8"))
|
|
157
|
+
return self.parse_response(resp_json)
|
|
158
|
+
except urllib.error.HTTPError as e:
|
|
159
|
+
err_body = e.read().decode("utf-8", errors="replace") if hasattr(e, "read") else ""
|
|
160
|
+
raise AdapterError(
|
|
161
|
+
f"HTTP {e.code} error from provider: {e.reason}",
|
|
162
|
+
status_code=e.code,
|
|
163
|
+
response_body=err_body,
|
|
164
|
+
) from e
|
|
165
|
+
except urllib.error.URLError as e:
|
|
166
|
+
raise AdapterError(f"Network error communicating with provider: {e.reason}") from e
|
|
167
|
+
except json.JSONDecodeError as e:
|
|
168
|
+
raise AdapterError(f"Failed to decode provider JSON response: {e}") from e
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""incierge.adapter.gemini — Google Gemini & Antigravity execution adapter.
|
|
4
|
+
|
|
5
|
+
Standard library implementation of Google Generative Language API (v1beta).
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
from typing import Any, Dict, List, Optional
|
|
11
|
+
|
|
12
|
+
from incierge.adapter.base import (
|
|
13
|
+
AdapterError,
|
|
14
|
+
BaseAdapter,
|
|
15
|
+
Message,
|
|
16
|
+
ModelRequest,
|
|
17
|
+
ModelResponse,
|
|
18
|
+
ToolCall,
|
|
19
|
+
Usage,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class GeminiAdapter(BaseAdapter):
|
|
24
|
+
"""Execution adapter for Google Gemini models."""
|
|
25
|
+
|
|
26
|
+
DEFAULT_MODEL = "gemini-2.5-flash"
|
|
27
|
+
BASE_API_URL = "https://generativelanguage.googleapis.com/v1beta/models"
|
|
28
|
+
|
|
29
|
+
@staticmethod
|
|
30
|
+
def _resolve_key(api_key: Optional[str]) -> str:
|
|
31
|
+
key = api_key or os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY", "")
|
|
32
|
+
if not key:
|
|
33
|
+
raise AdapterError("GEMINI_API_KEY (or GOOGLE_API_KEY) is not configured or provided")
|
|
34
|
+
return key
|
|
35
|
+
|
|
36
|
+
def get_endpoint_url(self, request: ModelRequest, api_key: Optional[str] = None) -> str:
|
|
37
|
+
# The key is sent in the `x-goog-api-key` header, never in the URL: URLs end up in proxy and
|
|
38
|
+
# access logs and in `HTTPError.url`, which the adapter chains into its own exceptions.
|
|
39
|
+
self._resolve_key(api_key)
|
|
40
|
+
model = request.model or self.default_model or self.DEFAULT_MODEL
|
|
41
|
+
base = os.environ.get("GEMINI_BASE_URL", self.BASE_API_URL).rstrip("/")
|
|
42
|
+
return f"{base}/{model}:generateContent"
|
|
43
|
+
|
|
44
|
+
def get_headers(self, request: ModelRequest, api_key: Optional[str] = None) -> Dict[str, str]:
|
|
45
|
+
return {
|
|
46
|
+
"Content-Type": "application/json",
|
|
47
|
+
"x-goog-api-key": self._resolve_key(api_key),
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
def format_request(self, request: ModelRequest) -> Dict[str, Any]:
|
|
51
|
+
contents: List[Dict[str, Any]] = []
|
|
52
|
+
system_instructions: List[str] = []
|
|
53
|
+
|
|
54
|
+
if request.system_prompt:
|
|
55
|
+
system_instructions.append(request.system_prompt)
|
|
56
|
+
|
|
57
|
+
for msg in request.messages:
|
|
58
|
+
if msg.role == "system":
|
|
59
|
+
system_instructions.append(msg.content)
|
|
60
|
+
continue
|
|
61
|
+
|
|
62
|
+
if msg.role == "tool":
|
|
63
|
+
contents.append({
|
|
64
|
+
"role": "user",
|
|
65
|
+
"parts": [{
|
|
66
|
+
"functionResponse": {
|
|
67
|
+
"name": msg.tool_call_id or "tool_result",
|
|
68
|
+
"response": {"output": msg.content},
|
|
69
|
+
}
|
|
70
|
+
}],
|
|
71
|
+
})
|
|
72
|
+
continue
|
|
73
|
+
|
|
74
|
+
if msg.role == "assistant":
|
|
75
|
+
parts: List[Dict[str, Any]] = []
|
|
76
|
+
if msg.content:
|
|
77
|
+
parts.append({"text": msg.content})
|
|
78
|
+
if msg.tool_calls:
|
|
79
|
+
for tc in msg.tool_calls:
|
|
80
|
+
parts.append({
|
|
81
|
+
"functionCall": {
|
|
82
|
+
"name": tc.name,
|
|
83
|
+
"args": tc.arguments,
|
|
84
|
+
}
|
|
85
|
+
})
|
|
86
|
+
contents.append({
|
|
87
|
+
"role": "model",
|
|
88
|
+
"parts": parts if parts else [{"text": msg.content or ""}],
|
|
89
|
+
})
|
|
90
|
+
continue
|
|
91
|
+
|
|
92
|
+
# Standard user role
|
|
93
|
+
contents.append({
|
|
94
|
+
"role": "user",
|
|
95
|
+
"parts": [{"text": msg.content}],
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
payload: Dict[str, Any] = {
|
|
99
|
+
"contents": contents,
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if system_instructions:
|
|
103
|
+
payload["systemInstruction"] = {
|
|
104
|
+
"parts": [{"text": "\n\n".join(system_instructions)}]
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
generation_config: Dict[str, Any] = {}
|
|
108
|
+
if request.temperature is not None:
|
|
109
|
+
generation_config["temperature"] = request.temperature
|
|
110
|
+
if request.max_tokens is not None:
|
|
111
|
+
generation_config["maxOutputTokens"] = request.max_tokens
|
|
112
|
+
if request.stop_sequences:
|
|
113
|
+
generation_config["stopSequences"] = request.stop_sequences
|
|
114
|
+
|
|
115
|
+
if generation_config:
|
|
116
|
+
payload["generationConfig"] = generation_config
|
|
117
|
+
|
|
118
|
+
if request.tools:
|
|
119
|
+
function_declarations = []
|
|
120
|
+
for t in request.tools:
|
|
121
|
+
decl: Dict[str, Any] = {
|
|
122
|
+
"name": t.name,
|
|
123
|
+
"description": t.description,
|
|
124
|
+
}
|
|
125
|
+
if t.parameters:
|
|
126
|
+
decl["parameters"] = t.parameters
|
|
127
|
+
function_declarations.append(decl)
|
|
128
|
+
payload["tools"] = [{"functionDeclarations": function_declarations}]
|
|
129
|
+
|
|
130
|
+
return payload
|
|
131
|
+
|
|
132
|
+
def parse_response(self, raw_json: Dict[str, Any]) -> ModelResponse:
|
|
133
|
+
candidates = raw_json.get("candidates", [])
|
|
134
|
+
if not candidates:
|
|
135
|
+
return ModelResponse(content="", raw_response=raw_json)
|
|
136
|
+
|
|
137
|
+
first_cand = candidates[0]
|
|
138
|
+
content_obj = first_cand.get("content", {})
|
|
139
|
+
parts = content_obj.get("parts", [])
|
|
140
|
+
|
|
141
|
+
text_pieces: List[str] = []
|
|
142
|
+
tool_calls: List[ToolCall] = []
|
|
143
|
+
|
|
144
|
+
for i, part in enumerate(parts):
|
|
145
|
+
if "text" in part:
|
|
146
|
+
text_pieces.append(part["text"])
|
|
147
|
+
if "functionCall" in part:
|
|
148
|
+
fc = part["functionCall"]
|
|
149
|
+
tool_calls.append(ToolCall(
|
|
150
|
+
id=f"call_{i}_{fc.get('name', 'tool')}",
|
|
151
|
+
name=fc.get("name", ""),
|
|
152
|
+
arguments=fc.get("args", {}),
|
|
153
|
+
))
|
|
154
|
+
|
|
155
|
+
usage_meta = raw_json.get("usageMetadata", {})
|
|
156
|
+
usage = Usage(
|
|
157
|
+
input_tokens=usage_meta.get("promptTokenCount", 0),
|
|
158
|
+
output_tokens=usage_meta.get("candidatesTokenCount", 0),
|
|
159
|
+
total_tokens=usage_meta.get("totalTokenCount", 0),
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
return ModelResponse(
|
|
163
|
+
content="".join(text_pieces),
|
|
164
|
+
tool_calls=tool_calls,
|
|
165
|
+
usage=usage,
|
|
166
|
+
stop_reason=first_cand.get("finishReason"),
|
|
167
|
+
raw_response=raw_json,
|
|
168
|
+
)
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""incierge.adapter.local — Local OpenAI-compatible inference adapter (llama-server / mlx / ollama).
|
|
4
|
+
|
|
5
|
+
Supports keyless local inference for `muse`, `gemma`, `local`, `mlx`, and `llamacpp`
|
|
6
|
+
with optional `/v1/models` & `/health` readiness probing and host RAM floor guard.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import urllib.error
|
|
13
|
+
import urllib.request
|
|
14
|
+
from typing import Any, Dict, List, Optional
|
|
15
|
+
|
|
16
|
+
from incierge.adapter.openai import OpenAIAdapter
|
|
17
|
+
from incierge.adapter.base import ModelRequest
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class LocalOpenAIAdapter(OpenAIAdapter):
|
|
21
|
+
"""Execution adapter for local OpenAI-compatible servers (llama.cpp, MLX, Ollama, vLLM)."""
|
|
22
|
+
|
|
23
|
+
DEFAULT_MODEL = "local-default"
|
|
24
|
+
DEFAULT_BASE_URL = "http://127.0.0.1:8080/v1"
|
|
25
|
+
MIN_RAM_GB_FOR_AUTO_START = 64
|
|
26
|
+
|
|
27
|
+
def _base_url(self) -> str:
|
|
28
|
+
return (
|
|
29
|
+
os.environ.get("INCIERGE_LOCAL_LLM_URL")
|
|
30
|
+
or os.environ.get("LOCAL_OPENAI_BASE_URL")
|
|
31
|
+
or self.DEFAULT_BASE_URL
|
|
32
|
+
).rstrip("/")
|
|
33
|
+
|
|
34
|
+
def get_endpoint_url(self, request: ModelRequest, api_key: Optional[str] = None) -> str:
|
|
35
|
+
base = self._base_url()
|
|
36
|
+
if base.endswith("/chat/completions"):
|
|
37
|
+
return base
|
|
38
|
+
return base + "/chat/completions"
|
|
39
|
+
|
|
40
|
+
def get_headers(self, request: ModelRequest, api_key: Optional[str] = None) -> Dict[str, str]:
|
|
41
|
+
key = api_key or os.environ.get("INCIERGE_LOCAL_LLM_KEY", "")
|
|
42
|
+
headers: Dict[str, str] = {"Content-Type": "application/json"}
|
|
43
|
+
if key:
|
|
44
|
+
headers["Authorization"] = f"Bearer {key}"
|
|
45
|
+
return headers
|
|
46
|
+
|
|
47
|
+
def probe_served_models(self, timeout_sec: float = 2.0) -> List[str]:
|
|
48
|
+
"""Return model IDs currently served by `/v1/models`, or empty list if unreachable."""
|
|
49
|
+
base = self._base_url()
|
|
50
|
+
models_url = base + "/models" if base.endswith("/v1") else base.rstrip("/") + "/v1/models"
|
|
51
|
+
req = urllib.request.Request(models_url, method="GET")
|
|
52
|
+
try:
|
|
53
|
+
with urllib.request.urlopen(req, timeout=timeout_sec) as resp:
|
|
54
|
+
payload: Dict[str, Any] = json.loads(resp.read().decode("utf-8", errors="replace"))
|
|
55
|
+
data = payload.get("data") or []
|
|
56
|
+
return [str(item.get("id")) for item in data if isinstance(item, dict) and item.get("id")]
|
|
57
|
+
except (OSError, urllib.error.URLError, ValueError):
|
|
58
|
+
return []
|
|
59
|
+
|
|
60
|
+
@classmethod
|
|
61
|
+
def check_ram_guard(cls, host_ram_gb: int, min_ram_gb: Optional[int] = None) -> bool:
|
|
62
|
+
"""Enforce minimum RAM floor before auto-spawning heavy local model servers."""
|
|
63
|
+
floor = cls.MIN_RAM_GB_FOR_AUTO_START if min_ram_gb is None else int(min_ram_gb)
|
|
64
|
+
return int(host_ram_gb) >= floor
|