python-corekit 0.3.0__py3-none-any.whl → 0.4.0__py3-none-any.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.
corekit/http/__init__.py CHANGED
@@ -27,6 +27,7 @@ from corekit.http.exceptions import (
27
27
  from corekit.http.exponential_backoff import ExponentialBackoff
28
28
  from corekit.http.response import BaseApiResponse
29
29
  from corekit.http.status import HTTPStatusCode
30
+ from corekit.http.stream import SseDecoder, SseJsonDecoder, SseTextDecoder, StreamDecoder
30
31
 
31
32
  __all__ = [
32
33
  "BadGatewayException",
@@ -42,6 +43,10 @@ __all__ = [
42
43
  "InternalServerErrorException",
43
44
  "NotFoundException",
44
45
  "ServiceUnavailableException",
46
+ "SseDecoder",
47
+ "SseJsonDecoder",
48
+ "SseTextDecoder",
49
+ "StreamDecoder",
45
50
  "TooManyRequestsException",
46
51
  "UnauthorizedException",
47
52
  "UnprocessableEntityException",
corekit/http/client.py CHANGED
@@ -2,9 +2,10 @@
2
2
  A small HTTP client with retries.
3
3
 
4
4
  ``BaseHttpClient`` is the transport: relative paths, optional strict URL
5
- checking, and retries for statuses the typed HTTP exceptions mark as
6
- retryable. Subclass ``BaseApiClient`` when the client always talks to one
7
- API and a foreign absolute URL should be a bug.
5
+ checking, retries for statuses the typed HTTP exceptions mark as
6
+ retryable, and ``stream_request`` for SSE / chunked bodies. Subclass
7
+ ``BaseApiClient`` when the client always talks to one API and a foreign
8
+ absolute URL should be a bug.
8
9
 
9
10
  class GithubClient(BaseApiClient):
10
11
  '''
@@ -27,6 +28,8 @@ Every response comes back as a ``BaseApiResponse``, so callers see one shape
27
28
  regardless of what the endpoint returned.
28
29
  """
29
30
 
31
+ from collections.abc import AsyncIterator
32
+ from contextlib import asynccontextmanager
30
33
  from http import HTTPMethod
31
34
  from typing import Any
32
35
  from urllib.parse import urljoin, urlsplit, urlunsplit
@@ -182,6 +185,34 @@ class BaseHttpClient(Benchmarkable):
182
185
  self.warning(f"{method} {_without_query(target)} returned {raw.status_code}; retrying")
183
186
  await backoff.async_wait()
184
187
 
188
+ @asynccontextmanager
189
+ async def stream_request(self, method: HTTPMethod, url: str, **kwargs: Any) -> AsyncIterator[httpx.Response]:
190
+ """
191
+ Open a streaming response and yield the raw ``httpx.Response``.
192
+
193
+ Holds the connection for the life of the ``async with`` block. Unlike
194
+ ``request``, the body is not buffered into a ``BaseApiResponse`` — the
195
+ caller reads it (for example with ``aiter_lines`` for SSE). Retries are
196
+ not applied: a mid-stream failure cannot be replayed safely.
197
+ """
198
+ if method not in self.supported_methods:
199
+ raise UnsupportedMethodError(method)
200
+
201
+ target = self._build_url(url)
202
+ headers = dict(self.headers)
203
+ extra_headers: dict[str, Any] | None = kwargs.pop("headers", None)
204
+ if extra_headers:
205
+ headers.update(extra_headers)
206
+
207
+ if self._http_client is not None:
208
+ async with self._http_client.stream(str(method), target, headers=headers, **kwargs) as response:
209
+ yield response
210
+ return
211
+
212
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
213
+ async with client.stream(str(method), target, headers=headers, **kwargs) as response:
214
+ yield response
215
+
185
216
  @allow_sync
186
217
  async def get(self, url: str, **kwargs: Any) -> BaseApiResponse:
187
218
  return await self.request(HTTPMethod.GET, url, **kwargs)
corekit/http/stream.py ADDED
@@ -0,0 +1,110 @@
1
+ """
2
+ Decode streaming HTTP response bodies into typed events.
3
+
4
+ ``BaseHttpClient.stream_request`` yields a raw ``httpx.Response``. Decoders
5
+ turn that into an async iterator of useful values (SSE text, SSE JSON, …).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from abc import ABC, abstractmethod
12
+ from collections.abc import AsyncIterator
13
+ from typing import Any, Generic, TypeVar
14
+
15
+ import httpx
16
+
17
+ from corekit.observability import Loggable
18
+
19
+ __all__ = [
20
+ "SseDecoder",
21
+ "SseJsonDecoder",
22
+ "SseTextDecoder",
23
+ "StreamDecoder",
24
+ ]
25
+
26
+ T = TypeVar("T")
27
+
28
+
29
+ class StreamDecoder(Loggable, ABC, Generic[T]):
30
+ """
31
+ Turn a streaming ``httpx.Response`` into an async iterator of ``T``.
32
+ """
33
+
34
+ @abstractmethod
35
+ def decode(self, response: httpx.Response) -> AsyncIterator[T]:
36
+ """
37
+ Consume ``response`` and yield decoded items.
38
+
39
+ Implemented as an async generator on concrete subclasses.
40
+ """
41
+ ...
42
+
43
+
44
+ class SseDecoder(StreamDecoder[T], ABC):
45
+ """
46
+ Server-Sent Events framing: ``data:`` lines, skip comments / blanks.
47
+
48
+ Optional ``done_sentinel`` (e.g. OpenAI's ``[DONE]``) ends the stream
49
+ early. Subclasses interpret each data payload via ``_decode_payload``.
50
+ """
51
+
52
+ def __init__(self, *, done_sentinel: str | None = None) -> None:
53
+ super().__init__()
54
+ self.done_sentinel = done_sentinel
55
+
56
+ async def decode(self, response: httpx.Response) -> AsyncIterator[T]:
57
+ async for data in self._iter_data_payloads(response):
58
+ item = self._decode_payload(data)
59
+ if item is not None:
60
+ yield item
61
+
62
+ async def _iter_data_payloads(self, response: httpx.Response) -> AsyncIterator[str]:
63
+ async for line in response.aiter_lines():
64
+ line = line.strip()
65
+ if not line.startswith("data:"):
66
+ continue
67
+ data = line.removeprefix("data:").strip()
68
+ if not data:
69
+ continue
70
+ if self.done_sentinel is not None and data == self.done_sentinel:
71
+ return
72
+ yield data
73
+
74
+ @abstractmethod
75
+ def _decode_payload(self, data: str) -> T | None:
76
+ """
77
+ Map one SSE data payload to ``T``, or ``None`` to skip.
78
+ """
79
+
80
+
81
+ class SseTextDecoder(SseDecoder[str]):
82
+ """
83
+ Yield SSE data payloads as plain strings.
84
+ """
85
+
86
+ def _decode_payload(self, data: str) -> str | None:
87
+ return data
88
+
89
+
90
+ class SseJsonDecoder(SseDecoder[dict[str, Any]]):
91
+ """
92
+ Yield SSE data payloads parsed as JSON objects.
93
+
94
+ Non-object JSON and decode failures are skipped (with a warning). Default
95
+ ``done_sentinel`` matches OpenAI-compatible chat streams.
96
+ """
97
+
98
+ def __init__(self, *, done_sentinel: str | None = "[DONE]") -> None:
99
+ super().__init__(done_sentinel=done_sentinel)
100
+
101
+ def _decode_payload(self, data: str) -> dict[str, Any] | None:
102
+ try:
103
+ payload = json.loads(data)
104
+ except json.JSONDecodeError:
105
+ self.warning(f"[SseJsonDecoder] Skipping bad SSE payload: {data!r}")
106
+ return None
107
+ if isinstance(payload, dict):
108
+ return payload
109
+ self.warning(f"[SseJsonDecoder] Skipping non-object SSE JSON: {type(payload).__name__}")
110
+ return None
@@ -0,0 +1,134 @@
1
+ """
2
+ OpenAI-shaped chat primitives, tool registry, and agentic loop.
3
+
4
+ Wire format in, structured stream events out. Use ``ChatCompletionsClient``
5
+ against any OpenAI-compatible server (llama.cpp, vLLM, OpenAI, …):
6
+
7
+ from corekit.llm import ChatCompletionsClient, PromptLoader, ToolLoop, ToolRegistry
8
+
9
+ client = ChatCompletionsClient("http://localhost:8080/v1", model="local")
10
+ prompts = PromptLoader("/path/to/prompts")
11
+ tmpl = prompts.load("summarization", "general", system="1.0.0", user="1.0.0")
12
+ registry = ToolRegistry()
13
+ registry.register(MyTool())
14
+ loop = ToolLoop(client, registry)
15
+ async for event in loop.stream(tmpl.messages(text="…", style="brief", length="1 paragraph")):
16
+ ...
17
+ """
18
+
19
+ from corekit.llm.client import DEFAULT_LLM_TIMEOUT, ChatCompletionsClient
20
+ from corekit.llm.enum import (
21
+ ContentPartType,
22
+ FinishReason,
23
+ Role,
24
+ StopReason,
25
+ StreamEventType,
26
+ ToolCallType,
27
+ ToolKind,
28
+ WireField,
29
+ )
30
+ from corekit.llm.events import (
31
+ DoneEvent,
32
+ StopEvent,
33
+ StreamEvent,
34
+ TextEvent,
35
+ ThinkingEvent,
36
+ ToolCallEvent,
37
+ ToolResultEvent,
38
+ UIComponentEvent,
39
+ UsageEvent,
40
+ )
41
+ from corekit.llm.messages import (
42
+ AssistantMessage,
43
+ ChatTurn,
44
+ Message,
45
+ SystemMessage,
46
+ ToolMessage,
47
+ UserMessage,
48
+ )
49
+ from corekit.llm.prompts import (
50
+ DEFAULT_PROMPT_VERSION,
51
+ PromptError,
52
+ PromptFileRole,
53
+ PromptKind,
54
+ PromptLoader,
55
+ PromptNotFoundError,
56
+ PromptTemplate,
57
+ ThinkingLevel,
58
+ )
59
+ from corekit.llm.protocols import ChatClient, MetricsRecorder
60
+ from corekit.llm.streaming import (
61
+ THINK_PATTERN,
62
+ ModelStreamingState,
63
+ ThinkingMarker,
64
+ ThinkingMarkerPair,
65
+ strip_thinking,
66
+ )
67
+ from corekit.llm.tools.base import Tool, ToolCall, ToolResult
68
+ from corekit.llm.tools.detection import MAX_TOOL_ITERATIONS, ToolCallLoopDetector
69
+ from corekit.llm.tools.loop import ToolLoop
70
+ from corekit.llm.tools.registry import ToolRegistry
71
+ from corekit.llm.wire import (
72
+ ChoiceDelta,
73
+ CompletionTurn,
74
+ FunctionCallDelta,
75
+ ToolCallAccumulator,
76
+ ToolCallDelta,
77
+ UsageInfo,
78
+ )
79
+
80
+ __all__ = [
81
+ "DEFAULT_LLM_TIMEOUT",
82
+ "DEFAULT_PROMPT_VERSION",
83
+ "MAX_TOOL_ITERATIONS",
84
+ "THINK_PATTERN",
85
+ "AssistantMessage",
86
+ "ChatClient",
87
+ "ChatCompletionsClient",
88
+ "ChatTurn",
89
+ "ChoiceDelta",
90
+ "CompletionTurn",
91
+ "ContentPartType",
92
+ "DoneEvent",
93
+ "FinishReason",
94
+ "FunctionCallDelta",
95
+ "Message",
96
+ "MetricsRecorder",
97
+ "ModelStreamingState",
98
+ "PromptError",
99
+ "PromptFileRole",
100
+ "PromptKind",
101
+ "PromptLoader",
102
+ "PromptNotFoundError",
103
+ "PromptTemplate",
104
+ "Role",
105
+ "StopEvent",
106
+ "StopReason",
107
+ "StreamEvent",
108
+ "StreamEventType",
109
+ "SystemMessage",
110
+ "TextEvent",
111
+ "ThinkingEvent",
112
+ "ThinkingLevel",
113
+ "ThinkingMarker",
114
+ "ThinkingMarkerPair",
115
+ "Tool",
116
+ "ToolCall",
117
+ "ToolCallAccumulator",
118
+ "ToolCallDelta",
119
+ "ToolCallEvent",
120
+ "ToolCallLoopDetector",
121
+ "ToolCallType",
122
+ "ToolKind",
123
+ "ToolLoop",
124
+ "ToolMessage",
125
+ "ToolRegistry",
126
+ "ToolResult",
127
+ "ToolResultEvent",
128
+ "UIComponentEvent",
129
+ "UsageEvent",
130
+ "UsageInfo",
131
+ "UserMessage",
132
+ "WireField",
133
+ "strip_thinking",
134
+ ]
corekit/llm/client.py ADDED
@@ -0,0 +1,179 @@
1
+ """
2
+ OpenAI-compatible chat completions client.
3
+
4
+ A thin ``BaseApiClient`` for ``/chat/completions``. Transport and status
5
+ handling come from the HTTP layer; streaming bodies go through
6
+ ``SseJsonDecoder``. This module only knows the OpenAI request wire shape.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import AsyncIterator, Coroutine, Mapping, Sequence
12
+ from http import HTTPMethod
13
+ from typing import Any, Literal, overload
14
+
15
+ from corekit.concurrency.decorators import allow_sync
16
+ from corekit.http import BaseApiClient, BaseApiResponse, SseJsonDecoder
17
+ from corekit.llm.messages import ChatTurn, Message
18
+
19
+ __all__ = ["ChatCompletionsClient", "DEFAULT_LLM_TIMEOUT"]
20
+
21
+ # LLM calls can run for minutes; the HTTP default of 30s is too short.
22
+ DEFAULT_LLM_TIMEOUT = 600.0
23
+
24
+ # Owned by this client — sampling kwargs and friends pass through untouched.
25
+ _BODY_RESERVED = frozenset({"model", "messages", "stream", "stream_options", "tools", "tool_choice"})
26
+
27
+
28
+ class ChatCompletionsClient(BaseApiClient):
29
+ """
30
+ OpenAI-shaped chat completions over HTTP.
31
+
32
+ client = ChatCompletionsClient("http://localhost:8080/v1", model="local")
33
+
34
+ # one-shot: a dict from sync code, a coroutine inside a running loop
35
+ result = client.complete([UserMessage(content="hi")])
36
+ result = await client.complete([UserMessage(content="hi")])
37
+
38
+ # streaming is always an async iterator — there is no sync equivalent
39
+ async for chunk in client.complete(messages, stream=True):
40
+ ...
41
+
42
+ ``base_url`` should include the API root (typically ``…/v1``). Accepts
43
+ ``Message`` instances or raw OpenAI message dicts.
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ base_url: str,
49
+ *,
50
+ api_key: str | None = None,
51
+ model: str | None = None,
52
+ timeout: float = DEFAULT_LLM_TIMEOUT,
53
+ **kwargs: Any,
54
+ ) -> None:
55
+ self._api_key = api_key
56
+ self._model = model
57
+ # Trailing slash so urljoin keeps the ``/v1`` segment for relative paths.
58
+ self._api_base = base_url if base_url.endswith("/") else f"{base_url}/"
59
+ self._stream_decoder = SseJsonDecoder()
60
+ super().__init__(timeout=timeout, **kwargs)
61
+
62
+ @property
63
+ def base_url(self) -> str:
64
+ return self._api_base
65
+
66
+ @property
67
+ def headers(self) -> dict[str, str]:
68
+ if not self._api_key:
69
+ return {}
70
+ return {"Authorization": f"Bearer {self._api_key}"}
71
+
72
+ def _resolve_model(self, model: str | None) -> str:
73
+ resolved = model if model is not None else self._model
74
+ if not resolved:
75
+ raise ValueError("model is required (pass model= to complete() or the constructor)")
76
+ return resolved
77
+
78
+ def _build_body(
79
+ self,
80
+ messages: Sequence[ChatTurn],
81
+ *,
82
+ stream: bool,
83
+ tools: Sequence[Mapping[str, Any]] | None = None,
84
+ model: str | None = None,
85
+ internal: bool = False,
86
+ **params: Any,
87
+ ) -> dict[str, Any]:
88
+ body: dict[str, Any] = {
89
+ "model": self._resolve_model(model),
90
+ "messages": Message.as_wire(messages, internal=internal),
91
+ "stream": stream,
92
+ }
93
+ if stream:
94
+ body["stream_options"] = {"include_usage": True}
95
+ if tools:
96
+ body["tools"] = list(tools)
97
+ body["tool_choice"] = params.pop("tool_choice", "auto")
98
+ for key, value in params.items():
99
+ if key not in _BODY_RESERVED:
100
+ body[key] = value
101
+ return body
102
+
103
+ @overload
104
+ def complete(
105
+ self,
106
+ messages: Sequence[ChatTurn],
107
+ *,
108
+ tools: Sequence[Mapping[str, Any]] | None = None,
109
+ model: str | None = None,
110
+ stream: Literal[False] = False,
111
+ internal: bool = False,
112
+ **kwargs: Any,
113
+ ) -> dict[str, Any] | Coroutine[Any, Any, dict[str, Any]]: ...
114
+
115
+ @overload
116
+ def complete(
117
+ self,
118
+ messages: Sequence[ChatTurn],
119
+ *,
120
+ tools: Sequence[Mapping[str, Any]] | None = None,
121
+ model: str | None = None,
122
+ stream: Literal[True],
123
+ internal: bool = False,
124
+ **kwargs: Any,
125
+ ) -> AsyncIterator[dict[str, Any]]: ...
126
+
127
+ def complete(
128
+ self,
129
+ messages: Sequence[ChatTurn],
130
+ *,
131
+ tools: Sequence[Mapping[str, Any]] | None = None,
132
+ model: str | None = None,
133
+ stream: bool = False,
134
+ internal: bool = False,
135
+ **kwargs: Any,
136
+ ) -> dict[str, Any] | Coroutine[Any, Any, dict[str, Any]] | AsyncIterator[dict[str, Any]]:
137
+ """
138
+ POST ``/chat/completions``.
139
+
140
+ ``stream=False`` (default) uses ``@allow_sync``: a script gets the
141
+ response dict back; inside a running event loop you must ``await`` it.
142
+ ``stream=True`` is always an async iterator — ``@allow_sync`` only
143
+ unwraps one awaitable, and buffering a stream would defeat streaming.
144
+ """
145
+ body = self._build_body(
146
+ messages,
147
+ stream=stream,
148
+ tools=tools,
149
+ model=model,
150
+ internal=internal,
151
+ **kwargs,
152
+ )
153
+ if stream:
154
+ return self._complete_stream(body)
155
+ return self._complete(body)
156
+
157
+ @allow_sync
158
+ async def _complete(self, body: dict[str, Any]) -> dict[str, Any]:
159
+ self.info(
160
+ f"[ChatCompletionsClient] Completing {body['model']!r} — "
161
+ f"messages={len(body['messages'])}, tools={'tools' in body}"
162
+ )
163
+ response = await self.post("chat/completions", json=body)
164
+ response.raise_for_status()
165
+ if not response.data:
166
+ raise ValueError(f"chat/completions returned non-JSON body: {response.text!r}")
167
+ return dict(response.data)
168
+
169
+ async def _complete_stream(self, body: dict[str, Any]) -> AsyncIterator[dict[str, Any]]:
170
+ self.info(
171
+ f"[ChatCompletionsClient] Streaming {body['model']!r} — "
172
+ f"messages={len(body['messages'])}, tools={'tools' in body}"
173
+ )
174
+ async with self.stream_request(HTTPMethod.POST, "chat/completions", json=body) as response:
175
+ if int(response.status_code) >= 400:
176
+ error_body = (await response.aread()).decode("utf-8", errors="replace")
177
+ BaseApiResponse(status_code=response.status_code, text=error_body).raise_for_status()
178
+ async for chunk in self._stream_decoder.decode(response):
179
+ yield chunk
corekit/llm/enum.py ADDED
@@ -0,0 +1,123 @@
1
+ """
2
+ Wire-facing LLM enumerations.
3
+ """
4
+
5
+ from corekit.schemas import StringEnum
6
+
7
+ __all__ = [
8
+ "ContentPartType",
9
+ "FinishReason",
10
+ "Role",
11
+ "StopReason",
12
+ "StreamEventType",
13
+ "ToolCallType",
14
+ "ToolKind",
15
+ "WireField",
16
+ ]
17
+
18
+
19
+ class Role(StringEnum):
20
+ """
21
+ OpenAI-shaped chat roles. Product bookkeeping roles (slash commands, and
22
+ so on) stay in the consumer.
23
+ """
24
+
25
+ USER = "user"
26
+ SYSTEM = "system"
27
+ ASSISTANT = "assistant"
28
+ TOOL = "tool"
29
+
30
+ def is_for_llm(self) -> bool:
31
+ """
32
+ True when this role may be included in model context.
33
+ """
34
+ return self in {Role.USER, Role.SYSTEM, Role.ASSISTANT, Role.TOOL}
35
+
36
+
37
+ class ToolKind(StringEnum):
38
+ """
39
+ How a tool participates in the agentic loop.
40
+ """
41
+
42
+ DATA = "data" # executed server-side; result fed back into the model
43
+ UI = "ui" # payload for the client; halts the model loop
44
+
45
+
46
+ class StreamEventType(StringEnum):
47
+ """
48
+ Kind of event yielded by a tool-aware streaming loop.
49
+ """
50
+
51
+ TEXT = "text"
52
+ THINKING = "thinking"
53
+ TOOL_CALL = "tool_call"
54
+ TOOL_RESULT = "tool_result"
55
+ UI_COMPONENT = "ui_component"
56
+ USAGE = "usage"
57
+ DONE = "done"
58
+ STOP = "stop"
59
+
60
+
61
+ class StopReason(StringEnum):
62
+ """
63
+ Why a ``StopEvent`` ended the loop early.
64
+ """
65
+
66
+ LOOP_DETECTED = "loop_detected"
67
+ MAX_ITERATIONS = "max_iterations"
68
+
69
+
70
+ class FinishReason(StringEnum):
71
+ """
72
+ OpenAI-compatible ``finish_reason`` values on a completion choice.
73
+ """
74
+
75
+ STOP = "stop"
76
+ TOOL_CALLS = "tool_calls"
77
+ LENGTH = "length"
78
+ CONTENT_FILTER = "content_filter"
79
+
80
+
81
+ class ContentPartType(StringEnum):
82
+ """
83
+ Multimodal content-part ``type`` values in OpenAI chat messages.
84
+ """
85
+
86
+ TEXT = "text"
87
+ IMAGE_URL = "image_url"
88
+
89
+
90
+ class ToolCallType(StringEnum):
91
+ """
92
+ OpenAI tool-call ``type`` on assistant messages.
93
+ """
94
+
95
+ FUNCTION = "function"
96
+
97
+
98
+ class WireField(StringEnum):
99
+ """
100
+ Recurring OpenAI wire field names used across messages and chunks.
101
+ """
102
+
103
+ ROLE = "role"
104
+ CONTENT = "content"
105
+ TOOL_CALLS = "tool_calls"
106
+ TOOL_CALL_ID = "tool_call_id"
107
+ REASONING_CONTENT = "reasoning_content"
108
+ TYPE = "type"
109
+ ID = "id"
110
+ NAME = "name"
111
+ ARGUMENTS = "arguments"
112
+ FUNCTION = "function"
113
+ INDEX = "index"
114
+ CHOICES = "choices"
115
+ DELTA = "delta"
116
+ USAGE = "usage"
117
+ FINISH_REASON = "finish_reason"
118
+ PROMPT_TOKENS = "prompt_tokens"
119
+ COMPLETION_TOKENS = "completion_tokens"
120
+ TOTAL_TOKENS = "total_tokens"
121
+ IMAGE_URL = "image_url"
122
+ URL = "url"
123
+ TEXT = "text"