grok-loop-kit 1.0.0__tar.gz → 1.2.0__tar.gz
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.
- grok_loop_kit-1.2.0/PKG-INFO +38 -0
- grok_loop_kit-1.2.0/README.md +21 -0
- grok_loop_kit-1.2.0/grok_loop_kit/__init__.py +47 -0
- grok_loop_kit-1.2.0/grok_loop_kit/async_client.py +158 -0
- {grok_loop_kit-1.0.0 → grok_loop_kit-1.2.0}/grok_loop_kit/client.py +108 -20
- grok_loop_kit-1.2.0/grok_loop_kit/langchain.py +440 -0
- grok_loop_kit-1.2.0/grok_loop_kit.egg-info/PKG-INFO +38 -0
- {grok_loop_kit-1.0.0 → grok_loop_kit-1.2.0}/grok_loop_kit.egg-info/SOURCES.txt +1 -0
- grok_loop_kit-1.2.0/grok_loop_kit.egg-info/requires.txt +6 -0
- {grok_loop_kit-1.0.0 → grok_loop_kit-1.2.0}/pyproject.toml +7 -4
- grok_loop_kit-1.0.0/PKG-INFO +0 -28
- grok_loop_kit-1.0.0/README.md +0 -14
- grok_loop_kit-1.0.0/grok_loop_kit/__init__.py +0 -25
- grok_loop_kit-1.0.0/grok_loop_kit/async_client.py +0 -88
- grok_loop_kit-1.0.0/grok_loop_kit.egg-info/PKG-INFO +0 -28
- grok_loop_kit-1.0.0/grok_loop_kit.egg-info/requires.txt +0 -3
- {grok_loop_kit-1.0.0 → grok_loop_kit-1.2.0}/grok_loop_kit/py.typed +0 -0
- {grok_loop_kit-1.0.0 → grok_loop_kit-1.2.0}/grok_loop_kit.egg-info/dependency_links.txt +0 -0
- {grok_loop_kit-1.0.0 → grok_loop_kit-1.2.0}/grok_loop_kit.egg-info/top_level.txt +0 -0
- {grok_loop_kit-1.0.0 → grok_loop_kit-1.2.0}/setup.cfg +0 -0
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: grok-loop-kit
|
|
3
|
+
Version: 1.2.0
|
|
4
|
+
Summary: Auto-apply Grok 4.7 context compaction to xAI Responses API agent loops.
|
|
5
|
+
Author: Booyaka101
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Booyaka101/grok-loop-kit
|
|
8
|
+
Project-URL: Repository, https://github.com/Booyaka101/grok-loop-kit
|
|
9
|
+
Project-URL: Issues, https://github.com/Booyaka101/grok-loop-kit/issues
|
|
10
|
+
Keywords: grok,grok-4.7,grok-4.5,xai,context-compaction,agent,responses-api,llm,langchain,langgraph
|
|
11
|
+
Requires-Python: >=3.9
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
Provides-Extra: requests
|
|
14
|
+
Requires-Dist: requests>=2.28; extra == "requests"
|
|
15
|
+
Provides-Extra: langchain
|
|
16
|
+
Requires-Dist: langchain-core>=0.3; extra == "langchain"
|
|
17
|
+
|
|
18
|
+
# grok-loop-kit (Python)
|
|
19
|
+
|
|
20
|
+
Automatic Grok 4.7 context compaction for xAI Responses API agent loops.
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
from grok_loop_kit import GrokLoopClient
|
|
24
|
+
|
|
25
|
+
client = GrokLoopClient(
|
|
26
|
+
api_key,
|
|
27
|
+
compact_every=8,
|
|
28
|
+
compact_at_tokens=8000,
|
|
29
|
+
model="grok-4.7",
|
|
30
|
+
reasoning_effort="medium",
|
|
31
|
+
)
|
|
32
|
+
res = client.send_message("hello")
|
|
33
|
+
print(res["_grokLoopKit"].totalCompactions)
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Zero runtime dependencies (stdlib `urllib`). Install `grok-loop-kit[langchain]` to
|
|
37
|
+
use `GrokLoopChatModel` with LangChain and LangGraph. See the repository root README
|
|
38
|
+
for the full API and the Node/LangGraph packages.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# grok-loop-kit (Python)
|
|
2
|
+
|
|
3
|
+
Automatic Grok 4.7 context compaction for xAI Responses API agent loops.
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
from grok_loop_kit import GrokLoopClient
|
|
7
|
+
|
|
8
|
+
client = GrokLoopClient(
|
|
9
|
+
api_key,
|
|
10
|
+
compact_every=8,
|
|
11
|
+
compact_at_tokens=8000,
|
|
12
|
+
model="grok-4.7",
|
|
13
|
+
reasoning_effort="medium",
|
|
14
|
+
)
|
|
15
|
+
res = client.send_message("hello")
|
|
16
|
+
print(res["_grokLoopKit"].totalCompactions)
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Zero runtime dependencies (stdlib `urllib`). Install `grok-loop-kit[langchain]` to
|
|
20
|
+
use `GrokLoopChatModel` with LangChain and LangGraph. See the repository root README
|
|
21
|
+
for the full API and the Node/LangGraph packages.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""grok-loop-kit: automatic Grok 4.7 context compaction for xAI Responses API agent loops."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib.util
|
|
6
|
+
from typing import TYPE_CHECKING, Any
|
|
7
|
+
|
|
8
|
+
from .async_client import AsyncGrokLoopClient
|
|
9
|
+
from .client import (
|
|
10
|
+
CompactionEvent,
|
|
11
|
+
CompletionWithMeta,
|
|
12
|
+
GrokLoopClient,
|
|
13
|
+
GrokLoopKitMeta,
|
|
14
|
+
ReasoningEffort,
|
|
15
|
+
build_compacted_transcript,
|
|
16
|
+
extract_assistant_text,
|
|
17
|
+
extract_compaction_text,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from .langchain import GrokLoopChatModel
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"GrokLoopClient",
|
|
25
|
+
"AsyncGrokLoopClient",
|
|
26
|
+
"CompletionWithMeta",
|
|
27
|
+
"CompactionEvent",
|
|
28
|
+
"GrokLoopKitMeta",
|
|
29
|
+
"ReasoningEffort",
|
|
30
|
+
"build_compacted_transcript",
|
|
31
|
+
"extract_assistant_text",
|
|
32
|
+
"extract_compaction_text",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
if importlib.util.find_spec("langchain_core") is not None:
|
|
36
|
+
__all__.append("GrokLoopChatModel")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def __getattr__(name: str) -> Any:
|
|
40
|
+
if name == "GrokLoopChatModel":
|
|
41
|
+
from .langchain import GrokLoopChatModel
|
|
42
|
+
|
|
43
|
+
return GrokLoopChatModel
|
|
44
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
__version__ = "1.2.0"
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""
|
|
2
|
+
AsyncGrokLoopClient — an asyncio-friendly facade over GrokLoopClient.
|
|
3
|
+
|
|
4
|
+
Zero extra dependencies: each network-bound call runs the synchronous client in
|
|
5
|
+
a worker thread via ``asyncio.to_thread``, so it never blocks the event loop.
|
|
6
|
+
State (messages, turn_count, compaction counters) lives on the wrapped sync
|
|
7
|
+
client and is exposed here as read-through properties.
|
|
8
|
+
|
|
9
|
+
Note: like the sync client, a single instance is not safe to drive with
|
|
10
|
+
concurrent overlapping calls — its transcript is shared mutable state. Use one
|
|
11
|
+
client per conversation.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import asyncio
|
|
17
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
18
|
+
|
|
19
|
+
from .client import CompletionWithMeta, GrokLoopClient, ReasoningEffort
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class AsyncGrokLoopClient:
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
api_key: str,
|
|
26
|
+
*,
|
|
27
|
+
reasoning_effort: Optional[ReasoningEffort] = None,
|
|
28
|
+
_client: Optional[GrokLoopClient] = None,
|
|
29
|
+
**kwargs: Any,
|
|
30
|
+
) -> None:
|
|
31
|
+
self._c = (
|
|
32
|
+
_client
|
|
33
|
+
if _client is not None
|
|
34
|
+
else GrokLoopClient(api_key, reasoning_effort=reasoning_effort, **kwargs)
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
# --- async API ---
|
|
38
|
+
|
|
39
|
+
async def send_message(
|
|
40
|
+
self,
|
|
41
|
+
user_content: str,
|
|
42
|
+
tools: Optional[List[Dict[str, Any]]] = None,
|
|
43
|
+
*,
|
|
44
|
+
reasoning_effort: Optional[ReasoningEffort] = None,
|
|
45
|
+
extra_body: Optional[Dict[str, Any]] = None,
|
|
46
|
+
) -> CompletionWithMeta:
|
|
47
|
+
return await asyncio.to_thread(
|
|
48
|
+
self._c.send_message,
|
|
49
|
+
user_content,
|
|
50
|
+
tools,
|
|
51
|
+
reasoning_effort=reasoning_effort,
|
|
52
|
+
extra_body=extra_body,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
async def send_tool_outputs(
|
|
56
|
+
self,
|
|
57
|
+
outputs: List[Dict[str, str]],
|
|
58
|
+
tools: Optional[List[Dict[str, Any]]] = None,
|
|
59
|
+
*,
|
|
60
|
+
reasoning_effort: Optional[ReasoningEffort] = None,
|
|
61
|
+
extra_body: Optional[Dict[str, Any]] = None,
|
|
62
|
+
) -> CompletionWithMeta:
|
|
63
|
+
return await asyncio.to_thread(
|
|
64
|
+
self._c.send_tool_outputs,
|
|
65
|
+
outputs,
|
|
66
|
+
tools,
|
|
67
|
+
reasoning_effort=reasoning_effort,
|
|
68
|
+
extra_body=extra_body,
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
async def stream_message(
|
|
72
|
+
self,
|
|
73
|
+
user_content: str,
|
|
74
|
+
tools: Optional[List[Dict[str, Any]]] = None,
|
|
75
|
+
on_token: Optional[Callable[[str], None]] = None,
|
|
76
|
+
*,
|
|
77
|
+
reasoning_effort: Optional[ReasoningEffort] = None,
|
|
78
|
+
extra_body: Optional[Dict[str, Any]] = None,
|
|
79
|
+
) -> CompletionWithMeta:
|
|
80
|
+
# The sync generator yields tokens as they arrive; on_token fires from the
|
|
81
|
+
# worker thread in real time. Returns the assembled final completion.
|
|
82
|
+
return await asyncio.to_thread(
|
|
83
|
+
self._c.stream_message,
|
|
84
|
+
user_content,
|
|
85
|
+
tools,
|
|
86
|
+
on_token,
|
|
87
|
+
reasoning_effort=reasoning_effort,
|
|
88
|
+
extra_body=extra_body,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
async def compact(self) -> Dict[str, Any]:
|
|
92
|
+
return await asyncio.to_thread(self._c.compact)
|
|
93
|
+
|
|
94
|
+
async def create_response(
|
|
95
|
+
self,
|
|
96
|
+
input_items: List[Dict[str, Any]],
|
|
97
|
+
tools: Optional[List[Dict[str, Any]]] = None,
|
|
98
|
+
*,
|
|
99
|
+
reasoning_effort: Optional[ReasoningEffort] = None,
|
|
100
|
+
extra_body: Optional[Dict[str, Any]] = None,
|
|
101
|
+
) -> Dict[str, Any]:
|
|
102
|
+
return await asyncio.to_thread(
|
|
103
|
+
self._c.create_response,
|
|
104
|
+
input_items,
|
|
105
|
+
tools,
|
|
106
|
+
reasoning_effort=reasoning_effort,
|
|
107
|
+
extra_body=extra_body,
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
async def compact_input(self, input_items: List[Dict[str, Any]]) -> Dict[str, Any]:
|
|
111
|
+
return await asyncio.to_thread(self._c.compact_input, input_items)
|
|
112
|
+
|
|
113
|
+
# --- passthroughs ---
|
|
114
|
+
|
|
115
|
+
def get_tool_calls(self, completion: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
116
|
+
return self._c.get_tool_calls(completion)
|
|
117
|
+
|
|
118
|
+
def reset(self) -> None:
|
|
119
|
+
self._c.reset()
|
|
120
|
+
|
|
121
|
+
def get_state(self) -> Dict[str, Any]:
|
|
122
|
+
return self._c.get_state()
|
|
123
|
+
|
|
124
|
+
def load_state(self, state: Dict[str, Any]) -> None:
|
|
125
|
+
self._c.load_state(state)
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def messages(self) -> List[Dict[str, Any]]:
|
|
129
|
+
return self._c.messages
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def turn_count(self) -> int:
|
|
133
|
+
return self._c.turn_count
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def total_compactions(self) -> int:
|
|
137
|
+
return self._c.total_compactions
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def accumulated_tokens(self) -> int:
|
|
141
|
+
return self._c.accumulated_tokens
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
def estimated_tokens_saved(self) -> int:
|
|
145
|
+
return self._c.estimated_tokens_saved
|
|
146
|
+
|
|
147
|
+
@property
|
|
148
|
+
def model(self) -> str:
|
|
149
|
+
return self._c.model
|
|
150
|
+
|
|
151
|
+
@property
|
|
152
|
+
def reasoning_effort(self) -> Optional[ReasoningEffort]:
|
|
153
|
+
return self._c.reasoning_effort
|
|
154
|
+
|
|
155
|
+
@property
|
|
156
|
+
def sync(self) -> GrokLoopClient:
|
|
157
|
+
"""Access the underlying synchronous client."""
|
|
158
|
+
return self._c
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
"""
|
|
2
2
|
GrokLoopClient — a thin wrapper over xAI's Responses API that transparently
|
|
3
|
-
applies Grok 4.
|
|
3
|
+
applies Grok 4.7 context compaction inside an agent loop.
|
|
4
4
|
|
|
5
5
|
Mirrors the TypeScript implementation. Uses only the standard library
|
|
6
6
|
(urllib) so it has no runtime dependencies.
|
|
7
7
|
|
|
8
8
|
Docs:
|
|
9
|
-
https://docs.x.ai/
|
|
9
|
+
https://docs.x.ai/docs/models
|
|
10
|
+
https://docs.x.ai/developers/model-capabilities/text/reasoning
|
|
10
11
|
https://docs.x.ai/developers/advanced-api-usage/context-compaction
|
|
11
12
|
"""
|
|
12
13
|
|
|
@@ -17,20 +18,35 @@ import time
|
|
|
17
18
|
import urllib.error
|
|
18
19
|
import urllib.request
|
|
19
20
|
from dataclasses import dataclass
|
|
20
|
-
from typing import Any, Callable, Dict, List, Optional
|
|
21
|
+
from typing import Any, Callable, Dict, List, Literal, Optional
|
|
21
22
|
|
|
22
23
|
InputItem = Dict[str, Any]
|
|
23
24
|
Tool = Dict[str, Any]
|
|
25
|
+
ReasoningEffort = Literal["low", "medium", "high", "xhigh"]
|
|
26
|
+
|
|
27
|
+
VALID_REASONING_EFFORTS = frozenset({"low", "medium", "high", "xhigh"})
|
|
24
28
|
|
|
25
29
|
DEFAULT_COMPACT_EVERY = 8
|
|
26
30
|
DEFAULT_COMPACT_AT_TOKENS = 8000
|
|
27
|
-
DEFAULT_MODEL = "grok-4.
|
|
31
|
+
DEFAULT_MODEL = "grok-4.7"
|
|
28
32
|
DEFAULT_BASE_URL = "https://api.x.ai/v1"
|
|
29
33
|
DEFAULT_MAX_RETRIES = 2
|
|
30
34
|
DEFAULT_RETRY_BASE_MS = 500
|
|
31
35
|
RETRYABLE_STATUS = {429, 500, 502, 503, 504}
|
|
32
36
|
|
|
33
37
|
|
|
38
|
+
def validate_reasoning_effort(effort: Optional[str]) -> Optional[ReasoningEffort]:
|
|
39
|
+
"""Validate optional reasoning effort against Grok 4.7 supported values."""
|
|
40
|
+
if effort is None:
|
|
41
|
+
return None
|
|
42
|
+
if not isinstance(effort, str) or effort not in VALID_REASONING_EFFORTS:
|
|
43
|
+
raise ValueError(
|
|
44
|
+
f"grok-loop-kit: invalid reasoning_effort {effort!r}; "
|
|
45
|
+
"expected one of low, medium, high, xhigh"
|
|
46
|
+
)
|
|
47
|
+
return effort # type: ignore[return-value]
|
|
48
|
+
|
|
49
|
+
|
|
34
50
|
@dataclass
|
|
35
51
|
class GrokLoopKitMeta:
|
|
36
52
|
"""Bookkeeping attached to every completion GrokLoopClient returns."""
|
|
@@ -122,7 +138,13 @@ def _default_stream(base_url, path, body, api_key, headers=None, timeout=None):
|
|
|
122
138
|
if headers:
|
|
123
139
|
hdrs.update(headers)
|
|
124
140
|
req = urllib.request.Request(f"{base_url}{path}", data=data, method="POST", headers=hdrs)
|
|
125
|
-
|
|
141
|
+
try:
|
|
142
|
+
resp = urllib.request.urlopen(req, timeout=timeout) # noqa: S310
|
|
143
|
+
except urllib.error.HTTPError as exc:
|
|
144
|
+
detail = exc.read().decode("utf-8", "replace")[:500]
|
|
145
|
+
raise RuntimeError(
|
|
146
|
+
f"grok-loop-kit: POST {path} (stream) failed {exc.code}: {detail}"
|
|
147
|
+
) from exc
|
|
126
148
|
try:
|
|
127
149
|
for raw in resp:
|
|
128
150
|
line = raw.decode("utf-8").strip()
|
|
@@ -157,6 +179,7 @@ class GrokLoopClient:
|
|
|
157
179
|
retry_base_ms: int = DEFAULT_RETRY_BASE_MS,
|
|
158
180
|
on_compact: Optional[Callable[[CompactionEvent], None]] = None,
|
|
159
181
|
extra_body: Optional[Dict[str, Any]] = None,
|
|
182
|
+
reasoning_effort: Optional[ReasoningEffort] = None,
|
|
160
183
|
poster: Optional[Poster] = None,
|
|
161
184
|
stream_poster: Optional[Callable[..., Any]] = None,
|
|
162
185
|
) -> None:
|
|
@@ -177,6 +200,7 @@ class GrokLoopClient:
|
|
|
177
200
|
self.retry_base_ms = retry_base_ms
|
|
178
201
|
self.on_compact = on_compact
|
|
179
202
|
self.extra_body = extra_body or {}
|
|
203
|
+
self.reasoning_effort: Optional[ReasoningEffort] = validate_reasoning_effort(reasoning_effort)
|
|
180
204
|
self._post_impl: Poster = poster or _default_post
|
|
181
205
|
self._stream_impl = stream_poster or _default_stream
|
|
182
206
|
|
|
@@ -190,39 +214,52 @@ class GrokLoopClient:
|
|
|
190
214
|
self._last_input_tokens = 0
|
|
191
215
|
|
|
192
216
|
def send_message(
|
|
193
|
-
self,
|
|
217
|
+
self,
|
|
218
|
+
user_content: str,
|
|
219
|
+
tools: Optional[List[Tool]] = None,
|
|
220
|
+
*,
|
|
221
|
+
reasoning_effort: Optional[ReasoningEffort] = None,
|
|
222
|
+
extra_body: Optional[Dict[str, Any]] = None,
|
|
194
223
|
) -> CompletionWithMeta:
|
|
195
224
|
"""Send a user turn through the loop, auto-compacting when due."""
|
|
225
|
+
validate_reasoning_effort(reasoning_effort)
|
|
196
226
|
self.messages.append({"role": "user", "content": user_content})
|
|
197
|
-
return self._run_turn(tools)
|
|
227
|
+
return self._run_turn(tools, reasoning_effort=reasoning_effort, extra_body=extra_body)
|
|
198
228
|
|
|
199
229
|
def send_tool_outputs(
|
|
200
|
-
self,
|
|
230
|
+
self,
|
|
231
|
+
outputs: List[Dict[str, str]],
|
|
232
|
+
tools: Optional[List[Tool]] = None,
|
|
233
|
+
*,
|
|
234
|
+
reasoning_effort: Optional[ReasoningEffort] = None,
|
|
235
|
+
extra_body: Optional[Dict[str, Any]] = None,
|
|
201
236
|
) -> CompletionWithMeta:
|
|
202
237
|
"""Submit tool-call results and continue the loop (counts as a turn)."""
|
|
238
|
+
validate_reasoning_effort(reasoning_effort)
|
|
203
239
|
for o in outputs:
|
|
204
240
|
self.messages.append(
|
|
205
241
|
{"type": "function_call_output", "call_id": o["call_id"], "output": o["output"]}
|
|
206
242
|
)
|
|
207
|
-
return self._run_turn(tools)
|
|
243
|
+
return self._run_turn(tools, reasoning_effort=reasoning_effort, extra_body=extra_body)
|
|
208
244
|
|
|
209
245
|
def stream_message(
|
|
210
246
|
self,
|
|
211
247
|
user_content: str,
|
|
212
248
|
tools: Optional[List[Tool]] = None,
|
|
213
249
|
on_token: Optional[Callable[[str], None]] = None,
|
|
250
|
+
*,
|
|
251
|
+
reasoning_effort: Optional[ReasoningEffort] = None,
|
|
252
|
+
extra_body: Optional[Dict[str, Any]] = None,
|
|
214
253
|
) -> CompletionWithMeta:
|
|
215
254
|
"""Stream a user turn: deltas go to ``on_token``; returns the final completion."""
|
|
255
|
+
validate_reasoning_effort(reasoning_effort)
|
|
216
256
|
self.messages.append({"role": "user", "content": user_content})
|
|
217
257
|
self.turn_count += 1
|
|
218
258
|
self.turns_since_compact += 1
|
|
219
259
|
|
|
220
|
-
body
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
if tools:
|
|
224
|
-
body["tools"] = tools
|
|
225
|
-
body.update(self.extra_body)
|
|
260
|
+
body = self._build_responses_body(
|
|
261
|
+
self.messages, tools, reasoning_effort=reasoning_effort, extra_body=extra_body
|
|
262
|
+
)
|
|
226
263
|
|
|
227
264
|
text_parts: List[str] = []
|
|
228
265
|
final: Optional[Dict[str, Any]] = None
|
|
@@ -249,6 +286,23 @@ class GrokLoopClient:
|
|
|
249
286
|
}
|
|
250
287
|
return self._finalize_turn(completion)
|
|
251
288
|
|
|
289
|
+
def create_response(
|
|
290
|
+
self,
|
|
291
|
+
input_items: List[InputItem],
|
|
292
|
+
tools: Optional[List[Tool]] = None,
|
|
293
|
+
*,
|
|
294
|
+
reasoning_effort: Optional[ReasoningEffort] = None,
|
|
295
|
+
extra_body: Optional[Dict[str, Any]] = None,
|
|
296
|
+
) -> Dict[str, Any]:
|
|
297
|
+
"""Stateless one-shot completion against arbitrary input items (no transcript mutation)."""
|
|
298
|
+
return self._post_responses(
|
|
299
|
+
input_items, tools, reasoning_effort=reasoning_effort, extra_body=extra_body
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
def compact_input(self, input_items: List[InputItem]) -> Dict[str, Any]:
|
|
303
|
+
"""Stateless one-shot compaction against arbitrary input items (no transcript mutation)."""
|
|
304
|
+
return self._post_compact(input_items)
|
|
305
|
+
|
|
252
306
|
def get_tool_calls(self, completion: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
253
307
|
"""Extract ``function_call`` items from a completion's output."""
|
|
254
308
|
return [i for i in (completion.get("output") or []) if i.get("type") == "function_call"]
|
|
@@ -319,10 +373,18 @@ class GrokLoopClient:
|
|
|
319
373
|
|
|
320
374
|
# --- internal ---
|
|
321
375
|
|
|
322
|
-
def _run_turn(
|
|
376
|
+
def _run_turn(
|
|
377
|
+
self,
|
|
378
|
+
tools: Optional[List[Tool]],
|
|
379
|
+
*,
|
|
380
|
+
reasoning_effort: Optional[ReasoningEffort] = None,
|
|
381
|
+
extra_body: Optional[Dict[str, Any]] = None,
|
|
382
|
+
) -> CompletionWithMeta:
|
|
323
383
|
self.turn_count += 1
|
|
324
384
|
self.turns_since_compact += 1
|
|
325
|
-
completion = self._post_responses(
|
|
385
|
+
completion = self._post_responses(
|
|
386
|
+
self.messages, tools, reasoning_effort=reasoning_effort, extra_body=extra_body
|
|
387
|
+
)
|
|
326
388
|
return self._finalize_turn(completion)
|
|
327
389
|
|
|
328
390
|
def _finalize_turn(self, completion: Dict[str, Any]) -> CompletionWithMeta:
|
|
@@ -356,15 +418,41 @@ class GrokLoopClient:
|
|
|
356
418
|
),
|
|
357
419
|
)
|
|
358
420
|
|
|
359
|
-
def
|
|
360
|
-
self,
|
|
421
|
+
def _build_responses_body(
|
|
422
|
+
self,
|
|
423
|
+
input_items: List[InputItem],
|
|
424
|
+
tools: Optional[List[Tool]] = None,
|
|
425
|
+
*,
|
|
426
|
+
reasoning_effort: Optional[ReasoningEffort] = None,
|
|
427
|
+
extra_body: Optional[Dict[str, Any]] = None,
|
|
361
428
|
) -> Dict[str, Any]:
|
|
362
429
|
body: Dict[str, Any] = {"model": self.model, "input": input_items}
|
|
363
430
|
if self.instructions:
|
|
364
431
|
body["instructions"] = self.instructions
|
|
365
432
|
if tools:
|
|
366
433
|
body["tools"] = tools
|
|
367
|
-
|
|
434
|
+
if self.reasoning_effort is not None:
|
|
435
|
+
body["reasoning"] = {"effort": self.reasoning_effort}
|
|
436
|
+
if self.extra_body:
|
|
437
|
+
body.update({k: v for k, v in self.extra_body.items() if v is not None})
|
|
438
|
+
call_effort = validate_reasoning_effort(reasoning_effort)
|
|
439
|
+
if call_effort is not None:
|
|
440
|
+
body["reasoning"] = {"effort": call_effort}
|
|
441
|
+
if extra_body:
|
|
442
|
+
body.update({k: v for k, v in extra_body.items() if v is not None})
|
|
443
|
+
return body
|
|
444
|
+
|
|
445
|
+
def _post_responses(
|
|
446
|
+
self,
|
|
447
|
+
input_items: List[InputItem],
|
|
448
|
+
tools: Optional[List[Tool]],
|
|
449
|
+
*,
|
|
450
|
+
reasoning_effort: Optional[ReasoningEffort] = None,
|
|
451
|
+
extra_body: Optional[Dict[str, Any]] = None,
|
|
452
|
+
) -> Dict[str, Any]:
|
|
453
|
+
body = self._build_responses_body(
|
|
454
|
+
input_items, tools, reasoning_effort=reasoning_effort, extra_body=extra_body
|
|
455
|
+
)
|
|
368
456
|
return self._post("/responses", body)
|
|
369
457
|
|
|
370
458
|
def _post_compact(self, input_items: List[InputItem]) -> Dict[str, Any]:
|
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
"""
|
|
2
|
+
LangChain / LangGraph chat-model adapter for grok-loop-kit.
|
|
3
|
+
|
|
4
|
+
Mirrors the TypeScript ``GrokLoopChatModel`` in ``src/langgraph.ts``: subclasses
|
|
5
|
+
``BaseChatModel``, converts LangChain messages and tool definitions to xAI
|
|
6
|
+
Responses API format, compacts incoming history on schedule or over token
|
|
7
|
+
budget, and attaches ``_grokLoopKit`` bookkeeping and ``usage_metadata`` on the
|
|
8
|
+
returned ``AIMessage``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import math
|
|
15
|
+
import os
|
|
16
|
+
from collections.abc import Mapping
|
|
17
|
+
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
|
|
18
|
+
|
|
19
|
+
try:
|
|
20
|
+
from langchain_core.language_models.chat_models import BaseChatModel
|
|
21
|
+
from langchain_core.messages import AIMessage, BaseMessage, ToolMessage
|
|
22
|
+
from langchain_core.outputs import ChatGeneration, ChatResult
|
|
23
|
+
from langchain_core.utils.function_calling import convert_to_openai_tool
|
|
24
|
+
except ImportError as exc:
|
|
25
|
+
raise ImportError(
|
|
26
|
+
"GrokLoopChatModel requires langchain-core>=0.3. "
|
|
27
|
+
"Install it with: pip install grok-loop-kit[langchain]"
|
|
28
|
+
) from exc
|
|
29
|
+
|
|
30
|
+
if hasattr(BaseChatModel, "model_fields"):
|
|
31
|
+
from pydantic import Field, PrivateAttr
|
|
32
|
+
else: # Minimal BaseChatModel stub fallback for dependency-free unit tests.
|
|
33
|
+
|
|
34
|
+
def Field(default: Any = None, **_: Any) -> Any: # type: ignore[no-redef]
|
|
35
|
+
return default
|
|
36
|
+
|
|
37
|
+
def PrivateAttr(default: Any = None, **_: Any) -> Any: # type: ignore[no-redef]
|
|
38
|
+
return default
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
from .async_client import AsyncGrokLoopClient
|
|
42
|
+
from .client import (
|
|
43
|
+
DEFAULT_BASE_URL,
|
|
44
|
+
DEFAULT_COMPACT_AT_TOKENS,
|
|
45
|
+
DEFAULT_COMPACT_EVERY,
|
|
46
|
+
DEFAULT_MAX_RETRIES,
|
|
47
|
+
DEFAULT_MODEL,
|
|
48
|
+
DEFAULT_RETRY_BASE_MS,
|
|
49
|
+
CompactionEvent,
|
|
50
|
+
GrokLoopClient,
|
|
51
|
+
GrokLoopKitMeta,
|
|
52
|
+
InputItem,
|
|
53
|
+
Poster,
|
|
54
|
+
ReasoningEffort,
|
|
55
|
+
Tool,
|
|
56
|
+
build_compacted_transcript,
|
|
57
|
+
extract_assistant_text,
|
|
58
|
+
validate_reasoning_effort,
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
if TYPE_CHECKING:
|
|
62
|
+
from langchain_core.callbacks import (
|
|
63
|
+
AsyncCallbackManagerForLLMRun,
|
|
64
|
+
CallbackManagerForLLMRun,
|
|
65
|
+
)
|
|
66
|
+
from langchain_core.language_models.base import LanguageModelInput
|
|
67
|
+
from langchain_core.runnables import Runnable
|
|
68
|
+
from langchain_core.tools import BaseTool
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _resolve_api_key(api_key: Any) -> str:
|
|
72
|
+
if api_key is not None:
|
|
73
|
+
raw = api_key.get_secret_value() if hasattr(api_key, "get_secret_value") else str(api_key)
|
|
74
|
+
if raw:
|
|
75
|
+
return raw
|
|
76
|
+
return (
|
|
77
|
+
os.environ.get("XAI_API_KEY")
|
|
78
|
+
or os.environ.get("GROK_API_KEY")
|
|
79
|
+
or "grok-loop-kit-placeholder"
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _message_to_text(msg: BaseMessage) -> str:
|
|
84
|
+
content = getattr(msg, "content", "")
|
|
85
|
+
if isinstance(content, str):
|
|
86
|
+
return content
|
|
87
|
+
if isinstance(content, list):
|
|
88
|
+
parts: List[str] = []
|
|
89
|
+
for part in content:
|
|
90
|
+
if isinstance(part, str):
|
|
91
|
+
parts.append(part)
|
|
92
|
+
elif isinstance(part, Mapping) and isinstance(part.get("text"), str):
|
|
93
|
+
parts.append(part["text"])
|
|
94
|
+
return "".join(parts)
|
|
95
|
+
if isinstance(content, Mapping):
|
|
96
|
+
return json.dumps(dict(content))
|
|
97
|
+
return "" if content is None else str(content)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _message_to_input(msg: BaseMessage) -> List[InputItem]:
|
|
101
|
+
msg_type = getattr(msg, "type", "")
|
|
102
|
+
if msg_type == "system":
|
|
103
|
+
return [{"role": "system", "content": _message_to_text(msg)}]
|
|
104
|
+
if msg_type == "tool":
|
|
105
|
+
return [
|
|
106
|
+
{
|
|
107
|
+
"type": "function_call_output",
|
|
108
|
+
"call_id": getattr(msg, "tool_call_id", ""),
|
|
109
|
+
"output": _message_to_text(msg),
|
|
110
|
+
}
|
|
111
|
+
]
|
|
112
|
+
if msg_type == "ai":
|
|
113
|
+
items: List[InputItem] = []
|
|
114
|
+
additional = getattr(msg, "additional_kwargs", None)
|
|
115
|
+
if isinstance(additional, Mapping):
|
|
116
|
+
raw_reasoning = additional.get("_grokReasoning")
|
|
117
|
+
if isinstance(raw_reasoning, list):
|
|
118
|
+
for r in raw_reasoning:
|
|
119
|
+
if isinstance(r, Mapping):
|
|
120
|
+
items.append(dict(r))
|
|
121
|
+
text = _message_to_text(msg)
|
|
122
|
+
if text:
|
|
123
|
+
items.append({"role": "assistant", "content": text})
|
|
124
|
+
for tc in getattr(msg, "tool_calls", None) or []:
|
|
125
|
+
if isinstance(tc, Mapping):
|
|
126
|
+
call_id = tc.get("id") or ""
|
|
127
|
+
name = tc.get("name") or ""
|
|
128
|
+
args = tc.get("args")
|
|
129
|
+
else:
|
|
130
|
+
call_id = getattr(tc, "id", None) or ""
|
|
131
|
+
name = getattr(tc, "name", None) or ""
|
|
132
|
+
args = getattr(tc, "args", None)
|
|
133
|
+
items.append(
|
|
134
|
+
{
|
|
135
|
+
"type": "function_call",
|
|
136
|
+
"call_id": call_id,
|
|
137
|
+
"name": name,
|
|
138
|
+
"arguments": json.dumps(args if args is not None else {}),
|
|
139
|
+
}
|
|
140
|
+
)
|
|
141
|
+
return items if items else [{"role": "assistant", "content": ""}]
|
|
142
|
+
return [{"role": "user", "content": _message_to_text(msg)}]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _flatten_openai_tool(tool: Mapping[str, Any]) -> Tool:
|
|
146
|
+
fn = tool.get("function")
|
|
147
|
+
if isinstance(fn, Mapping):
|
|
148
|
+
out: Tool = {"type": "function", "name": fn.get("name")}
|
|
149
|
+
for key in ("description", "parameters", "strict"):
|
|
150
|
+
if fn.get(key) is not None:
|
|
151
|
+
out[key] = fn[key]
|
|
152
|
+
return out
|
|
153
|
+
return dict(tool)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _to_xai_tool(tool: Any) -> Tool:
|
|
157
|
+
if isinstance(tool, Mapping):
|
|
158
|
+
if "function" in tool:
|
|
159
|
+
return _flatten_openai_tool(tool)
|
|
160
|
+
if tool.get("type") == "function" and "name" in tool:
|
|
161
|
+
return dict(tool)
|
|
162
|
+
if "name" in tool:
|
|
163
|
+
return {"type": "function", **{k: v for k, v in tool.items() if v is not None}}
|
|
164
|
+
converted = convert_to_openai_tool(tool)
|
|
165
|
+
return _flatten_openai_tool(converted)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _maybe_xai_tool(tool: Any) -> Tool:
|
|
169
|
+
if isinstance(tool, Mapping) and "function" not in tool and tool.get("type") == "function":
|
|
170
|
+
return dict(tool)
|
|
171
|
+
return _to_xai_tool(tool)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _estimate_tokens(input_items: List[InputItem]) -> int:
|
|
175
|
+
return math.ceil(len(json.dumps(input_items)) / 4)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _safe_json(raw: Any) -> Dict[str, Any]:
|
|
179
|
+
if isinstance(raw, Mapping):
|
|
180
|
+
return dict(raw)
|
|
181
|
+
if not isinstance(raw, str) or not raw:
|
|
182
|
+
return {}
|
|
183
|
+
try:
|
|
184
|
+
parsed = json.loads(raw)
|
|
185
|
+
return dict(parsed) if isinstance(parsed, Mapping) else {}
|
|
186
|
+
except json.JSONDecodeError:
|
|
187
|
+
return {}
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class GrokLoopChatModel(BaseChatModel):
|
|
191
|
+
"""
|
|
192
|
+
LangChain ``BaseChatModel`` backed by ``GrokLoopClient`` with automatic
|
|
193
|
+
Grok 4.7 context compaction and tool-call normalization.
|
|
194
|
+
"""
|
|
195
|
+
|
|
196
|
+
api_key: Optional[Any] = Field(default=None, exclude=True)
|
|
197
|
+
model: str = DEFAULT_MODEL
|
|
198
|
+
compact_every: int = DEFAULT_COMPACT_EVERY
|
|
199
|
+
compact_at_tokens: int = DEFAULT_COMPACT_AT_TOKENS
|
|
200
|
+
base_url: str = DEFAULT_BASE_URL
|
|
201
|
+
reasoning_effort: Optional[ReasoningEffort] = None
|
|
202
|
+
instructions: Optional[str] = None
|
|
203
|
+
headers: Optional[Dict[str, str]] = None
|
|
204
|
+
timeout: Optional[float] = None
|
|
205
|
+
max_retries: int = DEFAULT_MAX_RETRIES
|
|
206
|
+
retry_base_ms: int = DEFAULT_RETRY_BASE_MS
|
|
207
|
+
on_compact: Optional[Callable[[CompactionEvent], None]] = Field(default=None, exclude=True)
|
|
208
|
+
extra_body: Optional[Dict[str, Any]] = None
|
|
209
|
+
poster: Optional[Poster] = Field(default=None, exclude=True)
|
|
210
|
+
stream_poster: Optional[Callable[..., Any]] = Field(default=None, exclude=True)
|
|
211
|
+
|
|
212
|
+
total_compactions: int = Field(default=0, exclude=True)
|
|
213
|
+
estimated_tokens_saved: int = Field(default=0, exclude=True)
|
|
214
|
+
last_meta: Optional[GrokLoopKitMeta] = Field(default=None, exclude=True)
|
|
215
|
+
|
|
216
|
+
_gen_count: int = PrivateAttr(default=0)
|
|
217
|
+
_turns_since_compact: int = PrivateAttr(default=0)
|
|
218
|
+
_engine: Optional[GrokLoopClient] = PrivateAttr(default=None)
|
|
219
|
+
_async_engine: Optional[AsyncGrokLoopClient] = PrivateAttr(default=None)
|
|
220
|
+
|
|
221
|
+
def __init__(self, **kwargs: Any) -> None:
|
|
222
|
+
super().__init__(**kwargs)
|
|
223
|
+
if getattr(self, "_engine", None) is None:
|
|
224
|
+
self._init_engines()
|
|
225
|
+
|
|
226
|
+
def model_post_init(self, __context: Any) -> None:
|
|
227
|
+
self._init_engines()
|
|
228
|
+
|
|
229
|
+
def _init_engines(self) -> None:
|
|
230
|
+
resolved_key = _resolve_api_key(self.api_key)
|
|
231
|
+
sync_client = GrokLoopClient(
|
|
232
|
+
resolved_key,
|
|
233
|
+
compact_every=self.compact_every,
|
|
234
|
+
compact_at_tokens=self.compact_at_tokens,
|
|
235
|
+
model=self.model,
|
|
236
|
+
base_url=self.base_url,
|
|
237
|
+
instructions=self.instructions,
|
|
238
|
+
headers=self.headers,
|
|
239
|
+
timeout=self.timeout,
|
|
240
|
+
max_retries=self.max_retries,
|
|
241
|
+
retry_base_ms=self.retry_base_ms,
|
|
242
|
+
on_compact=self.on_compact,
|
|
243
|
+
extra_body=self.extra_body,
|
|
244
|
+
reasoning_effort=self.reasoning_effort,
|
|
245
|
+
poster=self.poster,
|
|
246
|
+
stream_poster=self.stream_poster,
|
|
247
|
+
)
|
|
248
|
+
self._engine = sync_client
|
|
249
|
+
self._async_engine = AsyncGrokLoopClient(resolved_key, _client=sync_client)
|
|
250
|
+
|
|
251
|
+
@property
|
|
252
|
+
def engine(self) -> GrokLoopClient:
|
|
253
|
+
if self._engine is None:
|
|
254
|
+
self._init_engines()
|
|
255
|
+
assert self._engine is not None
|
|
256
|
+
return self._engine
|
|
257
|
+
|
|
258
|
+
@property
|
|
259
|
+
def _llm_type(self) -> str:
|
|
260
|
+
return "grok-loop-kit"
|
|
261
|
+
|
|
262
|
+
@property
|
|
263
|
+
def _identifying_params(self) -> Dict[str, Any]:
|
|
264
|
+
return {
|
|
265
|
+
"model": self.model,
|
|
266
|
+
"base_url": self.base_url,
|
|
267
|
+
"compact_every": self.compact_every,
|
|
268
|
+
"compact_at_tokens": self.compact_at_tokens,
|
|
269
|
+
"reasoning_effort": self.reasoning_effort,
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
@property
|
|
273
|
+
def lc_secrets(self) -> Dict[str, str]:
|
|
274
|
+
return {"api_key": "XAI_API_KEY"}
|
|
275
|
+
|
|
276
|
+
def bind_tools(
|
|
277
|
+
self,
|
|
278
|
+
tools: Sequence[Union[Dict[str, Any], type, Callable[..., Any], BaseTool]],
|
|
279
|
+
*,
|
|
280
|
+
tool_choice: Optional[Union[str, Dict[str, Any]]] = None,
|
|
281
|
+
**kwargs: Any,
|
|
282
|
+
) -> Runnable[LanguageModelInput, AIMessage]:
|
|
283
|
+
"""Bind tools normalized to xAI's flat function-tool shape."""
|
|
284
|
+
formatted = [_to_xai_tool(t) for t in tools]
|
|
285
|
+
bind_kwargs: Dict[str, Any] = dict(kwargs)
|
|
286
|
+
if tool_choice is not None:
|
|
287
|
+
bind_kwargs["tool_choice"] = tool_choice
|
|
288
|
+
return self.bind(tools=formatted, **bind_kwargs)
|
|
289
|
+
|
|
290
|
+
def _prepare_turn(
|
|
291
|
+
self, messages: List[BaseMessage], kwargs: Dict[str, Any]
|
|
292
|
+
) -> Tuple[
|
|
293
|
+
List[InputItem],
|
|
294
|
+
Optional[Tuple[List[InputItem], List[InputItem]]],
|
|
295
|
+
Optional[List[Tool]],
|
|
296
|
+
Optional[ReasoningEffort],
|
|
297
|
+
Optional[Dict[str, Any]],
|
|
298
|
+
]:
|
|
299
|
+
reasoning = kwargs.get("reasoning")
|
|
300
|
+
effort = kwargs.get("reasoning_effort")
|
|
301
|
+
if effort is None and isinstance(reasoning, Mapping):
|
|
302
|
+
effort = reasoning.get("effort")
|
|
303
|
+
validated_effort = validate_reasoning_effort(effort)
|
|
304
|
+
|
|
305
|
+
self._gen_count += 1
|
|
306
|
+
self._turns_since_compact += 1
|
|
307
|
+
input_items = [item for msg in messages for item in _message_to_input(msg)]
|
|
308
|
+
|
|
309
|
+
compact_parts: Optional[Tuple[List[InputItem], List[InputItem]]] = None
|
|
310
|
+
over_budget = _estimate_tokens(input_items) > self.compact_at_tokens
|
|
311
|
+
on_schedule = self._gen_count % self.compact_every == 0
|
|
312
|
+
if len(input_items) > 1 and (on_schedule or over_budget):
|
|
313
|
+
compact_parts = (input_items[:-1], input_items[-1:])
|
|
314
|
+
|
|
315
|
+
raw_tools = kwargs.get("tools")
|
|
316
|
+
tools = [_maybe_xai_tool(t) for t in raw_tools] if raw_tools else None
|
|
317
|
+
extra_body: Dict[str, Any] = dict(kwargs.get("extra_body") or {})
|
|
318
|
+
if kwargs.get("tool_choice") is not None:
|
|
319
|
+
extra_body["tool_choice"] = kwargs["tool_choice"]
|
|
320
|
+
|
|
321
|
+
return input_items, compact_parts, tools, validated_effort, (extra_body or None)
|
|
322
|
+
|
|
323
|
+
def _apply_compaction(
|
|
324
|
+
self, compaction: Dict[str, Any], head: List[InputItem], tail: List[InputItem]
|
|
325
|
+
) -> List[InputItem]:
|
|
326
|
+
usage = compaction.get("usage") or {}
|
|
327
|
+
pre_tokens = usage.get("input_tokens")
|
|
328
|
+
if not isinstance(pre_tokens, (int, float)):
|
|
329
|
+
pre_tokens = _estimate_tokens(head)
|
|
330
|
+
record_tokens = usage.get("output_tokens") or 0
|
|
331
|
+
self.estimated_tokens_saved += max(0, int(pre_tokens) - int(record_tokens))
|
|
332
|
+
self.total_compactions += 1
|
|
333
|
+
self._turns_since_compact = 0
|
|
334
|
+
|
|
335
|
+
if self.on_compact:
|
|
336
|
+
dropped = usage.get("dropped_message_count", len(head))
|
|
337
|
+
self.on_compact(
|
|
338
|
+
CompactionEvent(
|
|
339
|
+
totalCompactions=self.total_compactions,
|
|
340
|
+
estimatedTokensSaved=self.estimated_tokens_saved,
|
|
341
|
+
droppedMessageCount=dropped,
|
|
342
|
+
atTurn=self._gen_count,
|
|
343
|
+
compaction=compaction,
|
|
344
|
+
)
|
|
345
|
+
)
|
|
346
|
+
return [*build_compacted_transcript(compaction), *tail]
|
|
347
|
+
|
|
348
|
+
def _build_chat_result(self, completion: Dict[str, Any]) -> ChatResult:
|
|
349
|
+
text = extract_assistant_text(completion)
|
|
350
|
+
reasoning_items = [
|
|
351
|
+
dict(item)
|
|
352
|
+
for item in (completion.get("output") or [])
|
|
353
|
+
if isinstance(item, Mapping) and item.get("type") == "reasoning"
|
|
354
|
+
]
|
|
355
|
+
tool_calls = [
|
|
356
|
+
{
|
|
357
|
+
"id": c.get("call_id") or c.get("id") or "",
|
|
358
|
+
"name": c.get("name") or "",
|
|
359
|
+
"args": _safe_json(c.get("arguments")),
|
|
360
|
+
"type": "tool_call",
|
|
361
|
+
}
|
|
362
|
+
for c in self.engine.get_tool_calls(completion)
|
|
363
|
+
]
|
|
364
|
+
|
|
365
|
+
meta = GrokLoopKitMeta(
|
|
366
|
+
turnsSinceCompact=self._turns_since_compact,
|
|
367
|
+
estimatedTokensSaved=self.estimated_tokens_saved,
|
|
368
|
+
totalCompactions=self.total_compactions,
|
|
369
|
+
)
|
|
370
|
+
self.last_meta = meta
|
|
371
|
+
meta_dict = meta.as_dict()
|
|
372
|
+
|
|
373
|
+
usage = completion.get("usage") or {}
|
|
374
|
+
in_tok = int(usage.get("input_tokens") or 0)
|
|
375
|
+
out_tok = int(usage.get("output_tokens") or 0)
|
|
376
|
+
tot_tok = int(usage.get("total_tokens") or (in_tok + out_tok))
|
|
377
|
+
|
|
378
|
+
ai_kwargs: Dict[str, Any] = {
|
|
379
|
+
"content": text,
|
|
380
|
+
"tool_calls": tool_calls,
|
|
381
|
+
"response_metadata": {"_grokLoopKit": meta_dict, "usage": usage},
|
|
382
|
+
"usage_metadata": {
|
|
383
|
+
"input_tokens": in_tok,
|
|
384
|
+
"output_tokens": out_tok,
|
|
385
|
+
"total_tokens": tot_tok,
|
|
386
|
+
},
|
|
387
|
+
}
|
|
388
|
+
if reasoning_items:
|
|
389
|
+
ai_kwargs["additional_kwargs"] = {"_grokReasoning": reasoning_items}
|
|
390
|
+
|
|
391
|
+
message = AIMessage(**ai_kwargs)
|
|
392
|
+
return ChatResult(
|
|
393
|
+
generations=[ChatGeneration(message=message)],
|
|
394
|
+
llm_output={
|
|
395
|
+
"token_usage": {
|
|
396
|
+
"prompt_tokens": usage.get("input_tokens"),
|
|
397
|
+
"completion_tokens": usage.get("output_tokens"),
|
|
398
|
+
"total_tokens": usage.get("total_tokens"),
|
|
399
|
+
},
|
|
400
|
+
"model_name": completion.get("model") or self.model,
|
|
401
|
+
"_grokLoopKit": meta_dict,
|
|
402
|
+
},
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
def _generate(
|
|
406
|
+
self,
|
|
407
|
+
messages: List[BaseMessage],
|
|
408
|
+
stop: Optional[List[str]] = None,
|
|
409
|
+
run_manager: Optional[CallbackManagerForLLMRun] = None,
|
|
410
|
+
**kwargs: Any,
|
|
411
|
+
) -> ChatResult:
|
|
412
|
+
del stop # Reasoning models on xAI Responses API reject/ignore stop sequences.
|
|
413
|
+
input_items, compact_parts, tools, effort, extra_body = self._prepare_turn(messages, kwargs)
|
|
414
|
+
if compact_parts is not None:
|
|
415
|
+
compaction = self.engine.compact_input(compact_parts[0])
|
|
416
|
+
input_items = self._apply_compaction(compaction, *compact_parts)
|
|
417
|
+
|
|
418
|
+
completion = self.engine.create_response(
|
|
419
|
+
input_items, tools=tools, reasoning_effort=effort, extra_body=extra_body
|
|
420
|
+
)
|
|
421
|
+
return self._build_chat_result(completion)
|
|
422
|
+
|
|
423
|
+
async def _agenerate(
|
|
424
|
+
self,
|
|
425
|
+
messages: List[BaseMessage],
|
|
426
|
+
stop: Optional[List[str]] = None,
|
|
427
|
+
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
|
|
428
|
+
**kwargs: Any,
|
|
429
|
+
) -> ChatResult:
|
|
430
|
+
del stop
|
|
431
|
+
assert self._async_engine is not None
|
|
432
|
+
input_items, compact_parts, tools, effort, extra_body = self._prepare_turn(messages, kwargs)
|
|
433
|
+
if compact_parts is not None:
|
|
434
|
+
compaction = await self._async_engine.compact_input(compact_parts[0])
|
|
435
|
+
input_items = self._apply_compaction(compaction, *compact_parts)
|
|
436
|
+
|
|
437
|
+
completion = await self._async_engine.create_response(
|
|
438
|
+
input_items, tools=tools, reasoning_effort=effort, extra_body=extra_body
|
|
439
|
+
)
|
|
440
|
+
return self._build_chat_result(completion)
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: grok-loop-kit
|
|
3
|
+
Version: 1.2.0
|
|
4
|
+
Summary: Auto-apply Grok 4.7 context compaction to xAI Responses API agent loops.
|
|
5
|
+
Author: Booyaka101
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Booyaka101/grok-loop-kit
|
|
8
|
+
Project-URL: Repository, https://github.com/Booyaka101/grok-loop-kit
|
|
9
|
+
Project-URL: Issues, https://github.com/Booyaka101/grok-loop-kit/issues
|
|
10
|
+
Keywords: grok,grok-4.7,grok-4.5,xai,context-compaction,agent,responses-api,llm,langchain,langgraph
|
|
11
|
+
Requires-Python: >=3.9
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
Provides-Extra: requests
|
|
14
|
+
Requires-Dist: requests>=2.28; extra == "requests"
|
|
15
|
+
Provides-Extra: langchain
|
|
16
|
+
Requires-Dist: langchain-core>=0.3; extra == "langchain"
|
|
17
|
+
|
|
18
|
+
# grok-loop-kit (Python)
|
|
19
|
+
|
|
20
|
+
Automatic Grok 4.7 context compaction for xAI Responses API agent loops.
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
from grok_loop_kit import GrokLoopClient
|
|
24
|
+
|
|
25
|
+
client = GrokLoopClient(
|
|
26
|
+
api_key,
|
|
27
|
+
compact_every=8,
|
|
28
|
+
compact_at_tokens=8000,
|
|
29
|
+
model="grok-4.7",
|
|
30
|
+
reasoning_effort="medium",
|
|
31
|
+
)
|
|
32
|
+
res = client.send_message("hello")
|
|
33
|
+
print(res["_grokLoopKit"].totalCompactions)
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Zero runtime dependencies (stdlib `urllib`). Install `grok-loop-kit[langchain]` to
|
|
37
|
+
use `GrokLoopChatModel` with LangChain and LangGraph. See the repository root README
|
|
38
|
+
for the full API and the Node/LangGraph packages.
|
|
@@ -4,12 +4,13 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "grok-loop-kit"
|
|
7
|
-
version = "1.
|
|
8
|
-
description = "Auto-apply Grok 4.
|
|
7
|
+
version = "1.2.0"
|
|
8
|
+
description = "Auto-apply Grok 4.7 context compaction to xAI Responses API agent loops."
|
|
9
9
|
readme = "README.md"
|
|
10
|
-
requires-python = ">=3.
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
11
|
license = { text = "MIT" }
|
|
12
|
-
|
|
12
|
+
authors = [{ name = "Booyaka101" }]
|
|
13
|
+
keywords = ["grok", "grok-4.7", "grok-4.5", "xai", "context-compaction", "agent", "responses-api", "llm", "langchain", "langgraph"]
|
|
13
14
|
dependencies = []
|
|
14
15
|
|
|
15
16
|
[project.urls]
|
|
@@ -20,6 +21,8 @@ Issues = "https://github.com/Booyaka101/grok-loop-kit/issues"
|
|
|
20
21
|
[project.optional-dependencies]
|
|
21
22
|
# Faster HTTP if you prefer; the package works on stdlib urllib without it.
|
|
22
23
|
requests = ["requests>=2.28"]
|
|
24
|
+
# LangChain / LangGraph chat-model adapter (GrokLoopChatModel).
|
|
25
|
+
langchain = ["langchain-core>=0.3"]
|
|
23
26
|
|
|
24
27
|
[tool.setuptools]
|
|
25
28
|
packages = ["grok_loop_kit"]
|
grok_loop_kit-1.0.0/PKG-INFO
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: grok-loop-kit
|
|
3
|
-
Version: 1.0.0
|
|
4
|
-
Summary: Auto-apply Grok 4.5 context compaction to xAI Responses API agent loops.
|
|
5
|
-
License: MIT
|
|
6
|
-
Project-URL: Homepage, https://github.com/Booyaka101/grok-loop-kit
|
|
7
|
-
Project-URL: Repository, https://github.com/Booyaka101/grok-loop-kit
|
|
8
|
-
Project-URL: Issues, https://github.com/Booyaka101/grok-loop-kit/issues
|
|
9
|
-
Keywords: grok,grok-4.5,xai,context-compaction,agent,responses-api,llm
|
|
10
|
-
Requires-Python: >=3.8
|
|
11
|
-
Description-Content-Type: text/markdown
|
|
12
|
-
Provides-Extra: requests
|
|
13
|
-
Requires-Dist: requests>=2.28; extra == "requests"
|
|
14
|
-
|
|
15
|
-
# grok-loop-kit (Python)
|
|
16
|
-
|
|
17
|
-
Automatic Grok 4.5 context compaction for xAI Responses API agent loops.
|
|
18
|
-
|
|
19
|
-
```python
|
|
20
|
-
from grok_loop_kit import GrokLoopClient
|
|
21
|
-
|
|
22
|
-
client = GrokLoopClient(api_key, compact_every=8, compact_at_tokens=8000, model="grok-4.5")
|
|
23
|
-
res = client.send_message("hello")
|
|
24
|
-
print(res["_grokLoopKit"].totalCompactions)
|
|
25
|
-
```
|
|
26
|
-
|
|
27
|
-
Zero runtime dependencies (stdlib `urllib`). See the repository root README for the
|
|
28
|
-
full API and the Node/LangGraph packages.
|
grok_loop_kit-1.0.0/README.md
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
# grok-loop-kit (Python)
|
|
2
|
-
|
|
3
|
-
Automatic Grok 4.5 context compaction for xAI Responses API agent loops.
|
|
4
|
-
|
|
5
|
-
```python
|
|
6
|
-
from grok_loop_kit import GrokLoopClient
|
|
7
|
-
|
|
8
|
-
client = GrokLoopClient(api_key, compact_every=8, compact_at_tokens=8000, model="grok-4.5")
|
|
9
|
-
res = client.send_message("hello")
|
|
10
|
-
print(res["_grokLoopKit"].totalCompactions)
|
|
11
|
-
```
|
|
12
|
-
|
|
13
|
-
Zero runtime dependencies (stdlib `urllib`). See the repository root README for the
|
|
14
|
-
full API and the Node/LangGraph packages.
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
"""grok-loop-kit: automatic Grok 4.5 context compaction for xAI Responses API agent loops."""
|
|
2
|
-
|
|
3
|
-
from .async_client import AsyncGrokLoopClient
|
|
4
|
-
from .client import (
|
|
5
|
-
CompactionEvent,
|
|
6
|
-
CompletionWithMeta,
|
|
7
|
-
GrokLoopClient,
|
|
8
|
-
GrokLoopKitMeta,
|
|
9
|
-
build_compacted_transcript,
|
|
10
|
-
extract_assistant_text,
|
|
11
|
-
extract_compaction_text,
|
|
12
|
-
)
|
|
13
|
-
|
|
14
|
-
__all__ = [
|
|
15
|
-
"GrokLoopClient",
|
|
16
|
-
"AsyncGrokLoopClient",
|
|
17
|
-
"CompletionWithMeta",
|
|
18
|
-
"CompactionEvent",
|
|
19
|
-
"GrokLoopKitMeta",
|
|
20
|
-
"build_compacted_transcript",
|
|
21
|
-
"extract_assistant_text",
|
|
22
|
-
"extract_compaction_text",
|
|
23
|
-
]
|
|
24
|
-
|
|
25
|
-
__version__ = "1.0.0"
|
|
@@ -1,88 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
AsyncGrokLoopClient — an asyncio-friendly facade over GrokLoopClient.
|
|
3
|
-
|
|
4
|
-
Zero extra dependencies: each network-bound call runs the synchronous client in
|
|
5
|
-
a worker thread via ``asyncio.to_thread``, so it never blocks the event loop.
|
|
6
|
-
State (messages, turn_count, compaction counters) lives on the wrapped sync
|
|
7
|
-
client and is exposed here as read-through properties.
|
|
8
|
-
|
|
9
|
-
Note: like the sync client, a single instance is not safe to drive with
|
|
10
|
-
concurrent overlapping calls — its transcript is shared mutable state. Use one
|
|
11
|
-
client per conversation.
|
|
12
|
-
"""
|
|
13
|
-
|
|
14
|
-
from __future__ import annotations
|
|
15
|
-
|
|
16
|
-
import asyncio
|
|
17
|
-
from typing import Any, Callable, Dict, List, Optional
|
|
18
|
-
|
|
19
|
-
from .client import CompletionWithMeta, GrokLoopClient
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
class AsyncGrokLoopClient:
|
|
23
|
-
def __init__(self, api_key: str, **kwargs: Any) -> None:
|
|
24
|
-
self._c = GrokLoopClient(api_key, **kwargs)
|
|
25
|
-
|
|
26
|
-
# --- async API ---
|
|
27
|
-
|
|
28
|
-
async def send_message(
|
|
29
|
-
self, user_content: str, tools: Optional[List[Dict[str, Any]]] = None
|
|
30
|
-
) -> CompletionWithMeta:
|
|
31
|
-
return await asyncio.to_thread(self._c.send_message, user_content, tools)
|
|
32
|
-
|
|
33
|
-
async def send_tool_outputs(
|
|
34
|
-
self, outputs: List[Dict[str, str]], tools: Optional[List[Dict[str, Any]]] = None
|
|
35
|
-
) -> CompletionWithMeta:
|
|
36
|
-
return await asyncio.to_thread(self._c.send_tool_outputs, outputs, tools)
|
|
37
|
-
|
|
38
|
-
async def stream_message(
|
|
39
|
-
self,
|
|
40
|
-
user_content: str,
|
|
41
|
-
tools: Optional[List[Dict[str, Any]]] = None,
|
|
42
|
-
on_token: Optional[Callable[[str], None]] = None,
|
|
43
|
-
) -> CompletionWithMeta:
|
|
44
|
-
# The sync generator yields tokens as they arrive; on_token fires from the
|
|
45
|
-
# worker thread in real time. Returns the assembled final completion.
|
|
46
|
-
return await asyncio.to_thread(self._c.stream_message, user_content, tools, on_token)
|
|
47
|
-
|
|
48
|
-
async def compact(self) -> Dict[str, Any]:
|
|
49
|
-
return await asyncio.to_thread(self._c.compact)
|
|
50
|
-
|
|
51
|
-
# --- passthroughs ---
|
|
52
|
-
|
|
53
|
-
def get_tool_calls(self, completion: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
54
|
-
return self._c.get_tool_calls(completion)
|
|
55
|
-
|
|
56
|
-
def reset(self) -> None:
|
|
57
|
-
self._c.reset()
|
|
58
|
-
|
|
59
|
-
def get_state(self) -> Dict[str, Any]:
|
|
60
|
-
return self._c.get_state()
|
|
61
|
-
|
|
62
|
-
def load_state(self, state: Dict[str, Any]) -> None:
|
|
63
|
-
self._c.load_state(state)
|
|
64
|
-
|
|
65
|
-
@property
|
|
66
|
-
def messages(self) -> List[Dict[str, Any]]:
|
|
67
|
-
return self._c.messages
|
|
68
|
-
|
|
69
|
-
@property
|
|
70
|
-
def turn_count(self) -> int:
|
|
71
|
-
return self._c.turn_count
|
|
72
|
-
|
|
73
|
-
@property
|
|
74
|
-
def total_compactions(self) -> int:
|
|
75
|
-
return self._c.total_compactions
|
|
76
|
-
|
|
77
|
-
@property
|
|
78
|
-
def accumulated_tokens(self) -> int:
|
|
79
|
-
return self._c.accumulated_tokens
|
|
80
|
-
|
|
81
|
-
@property
|
|
82
|
-
def estimated_tokens_saved(self) -> int:
|
|
83
|
-
return self._c.estimated_tokens_saved
|
|
84
|
-
|
|
85
|
-
@property
|
|
86
|
-
def sync(self) -> GrokLoopClient:
|
|
87
|
-
"""Access the underlying synchronous client."""
|
|
88
|
-
return self._c
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: grok-loop-kit
|
|
3
|
-
Version: 1.0.0
|
|
4
|
-
Summary: Auto-apply Grok 4.5 context compaction to xAI Responses API agent loops.
|
|
5
|
-
License: MIT
|
|
6
|
-
Project-URL: Homepage, https://github.com/Booyaka101/grok-loop-kit
|
|
7
|
-
Project-URL: Repository, https://github.com/Booyaka101/grok-loop-kit
|
|
8
|
-
Project-URL: Issues, https://github.com/Booyaka101/grok-loop-kit/issues
|
|
9
|
-
Keywords: grok,grok-4.5,xai,context-compaction,agent,responses-api,llm
|
|
10
|
-
Requires-Python: >=3.8
|
|
11
|
-
Description-Content-Type: text/markdown
|
|
12
|
-
Provides-Extra: requests
|
|
13
|
-
Requires-Dist: requests>=2.28; extra == "requests"
|
|
14
|
-
|
|
15
|
-
# grok-loop-kit (Python)
|
|
16
|
-
|
|
17
|
-
Automatic Grok 4.5 context compaction for xAI Responses API agent loops.
|
|
18
|
-
|
|
19
|
-
```python
|
|
20
|
-
from grok_loop_kit import GrokLoopClient
|
|
21
|
-
|
|
22
|
-
client = GrokLoopClient(api_key, compact_every=8, compact_at_tokens=8000, model="grok-4.5")
|
|
23
|
-
res = client.send_message("hello")
|
|
24
|
-
print(res["_grokLoopKit"].totalCompactions)
|
|
25
|
-
```
|
|
26
|
-
|
|
27
|
-
Zero runtime dependencies (stdlib `urllib`). See the repository root README for the
|
|
28
|
-
full API and the Node/LangGraph packages.
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|