python-corekit 0.3.0__py3-none-any.whl → 0.4.1__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.
Files changed (45) hide show
  1. corekit/exceptionator/__init__.py +68 -0
  2. corekit/exceptionator/actions.py +46 -0
  3. corekit/exceptionator/asgi.py +115 -0
  4. corekit/exceptionator/constants.py +7 -0
  5. corekit/exceptionator/exceptionator.py +62 -0
  6. corekit/exceptionator/fingerprint.py +86 -0
  7. corekit/exceptionator/guard.py +53 -0
  8. corekit/exceptionator/jobs.py +52 -0
  9. corekit/exceptionator/models.py +98 -0
  10. corekit/http/__init__.py +5 -0
  11. corekit/http/client.py +34 -3
  12. corekit/http/stream.py +110 -0
  13. corekit/jobs/runner.py +22 -2
  14. corekit/llm/__init__.py +134 -0
  15. corekit/llm/client.py +179 -0
  16. corekit/llm/enum.py +123 -0
  17. corekit/llm/events.py +96 -0
  18. corekit/llm/messages.py +173 -0
  19. corekit/llm/prompts/__init__.py +19 -0
  20. corekit/llm/prompts/enum.py +54 -0
  21. corekit/llm/prompts/exceptions.py +22 -0
  22. corekit/llm/prompts/loader.py +139 -0
  23. corekit/llm/prompts/template.py +53 -0
  24. corekit/llm/protocols.py +65 -0
  25. corekit/llm/streaming.py +149 -0
  26. corekit/llm/tools/__init__.py +19 -0
  27. corekit/llm/tools/base.py +118 -0
  28. corekit/llm/tools/detection.py +99 -0
  29. corekit/llm/tools/loop.py +255 -0
  30. corekit/llm/tools/registry.py +103 -0
  31. corekit/llm/wire.py +199 -0
  32. corekit/observability/__init__.py +3 -3
  33. corekit/observability/benchmarkable.py +16 -2
  34. corekit/observability/timing/split.py +14 -0
  35. corekit/observability/timing/timer.py +31 -9
  36. corekit/schemas/__init__.py +2 -1
  37. corekit/schemas/version.py +58 -0
  38. corekit/utils/__init__.py +4 -2
  39. corekit/utils/collections.py +16 -1
  40. corekit/utils/text.py +21 -2
  41. {python_corekit-0.3.0.dist-info → python_corekit-0.4.1.dist-info}/METADATA +56 -4
  42. {python_corekit-0.3.0.dist-info → python_corekit-0.4.1.dist-info}/RECORD +45 -16
  43. {python_corekit-0.3.0.dist-info → python_corekit-0.4.1.dist-info}/WHEEL +0 -0
  44. {python_corekit-0.3.0.dist-info → python_corekit-0.4.1.dist-info}/licenses/LICENSE +0 -0
  45. {python_corekit-0.3.0.dist-info → python_corekit-0.4.1.dist-info}/top_level.txt +0 -0
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
corekit/jobs/runner.py CHANGED
@@ -18,6 +18,7 @@ import inspect
18
18
  import logging
19
19
  from typing import Any
20
20
 
21
+ from corekit.exceptionator.jobs import get_run_task_hook
21
22
  from corekit.jobs.registry import task_registry
22
23
  from corekit.utils.payload import decode_payload
23
24
 
@@ -34,8 +35,10 @@ def run_task(task_name: str, payload: str | bytes | None = None) -> Any:
34
35
  raises, and the original exception is re-raised so the queue records the
35
36
  job as failed. A hook that raises does not mask the original error.
36
37
  ``last_result`` and ``last_error`` are set on the task before the hook
37
- runs. A coroutine ``task_function`` is awaited. ``timeout`` is not applied
38
- here; the scheduling adapter owns that.
38
+ runs. When an Exceptionator ``run_task`` hook is installed it runs after
39
+ ``last_error`` is set and before ``failure()``. A coroutine
40
+ ``task_function`` is awaited. ``timeout`` is not applied here; the
41
+ scheduling adapter owns that.
39
42
 
40
43
  Args:
41
44
  task_name: The registered name of the task to run.
@@ -58,6 +61,7 @@ def run_task(task_name: str, payload: str | bytes | None = None) -> Any:
58
61
  except Exception as exc:
59
62
  task.last_result = None
60
63
  task.last_error = exc
64
+ _run_exceptionator_hook(task_name, exc)
61
65
  _run_hook(task, "failure", args, kwargs)
62
66
  raise
63
67
 
@@ -67,6 +71,22 @@ def run_task(task_name: str, payload: str | bytes | None = None) -> Any:
67
71
  return result
68
72
 
69
73
 
74
+ def _run_exceptionator_hook(task_name: str, exc: BaseException) -> None:
75
+ """
76
+ Run the optional Exceptionator hook without replacing the original error.
77
+ """
78
+ hook = get_run_task_hook()
79
+ if hook is None:
80
+ return
81
+ try:
82
+ hook(task_name, exc)
83
+ except Exception:
84
+ logger.exception(
85
+ "Exceptionator run_task hook raised for %s; the task's own outcome stands",
86
+ task_name,
87
+ )
88
+
89
+
70
90
  def _run_hook(task: Any, hook_name: str, args: list[Any], kwargs: dict[str, Any]) -> None:
71
91
  """
72
92
  Run a success or failure hook without letting it replace the real outcome.
@@ -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"
corekit/llm/events.py ADDED
@@ -0,0 +1,96 @@
1
+ """
2
+ Transport-agnostic stream events from a tool-aware loop.
3
+ """
4
+
5
+ from typing import Any
6
+
7
+ from pydantic import BaseModel
8
+
9
+ from corekit.llm.enum import StopReason, StreamEventType
10
+ from corekit.llm.tools.base import ToolCall, ToolResult
11
+
12
+ __all__ = [
13
+ "DoneEvent",
14
+ "StopEvent",
15
+ "StreamEvent",
16
+ "TextEvent",
17
+ "ThinkingEvent",
18
+ "ToolCallEvent",
19
+ "ToolResultEvent",
20
+ "UIComponentEvent",
21
+ "UsageEvent",
22
+ ]
23
+
24
+
25
+ class StreamEvent(BaseModel):
26
+ """
27
+ Base event yielded by the tool-aware streaming loop.
28
+
29
+ Subclasses fix ``kind``; ``payload()`` is what an SSE ``data:`` line would
30
+ carry (``kind`` is omitted — it belongs on the event name).
31
+ """
32
+
33
+ kind: StreamEventType
34
+
35
+ def payload(self) -> dict[str, Any]:
36
+ """
37
+ JSON-serializable payload without the ``kind`` field.
38
+ """
39
+ return self.model_dump(exclude={"kind"})
40
+
41
+
42
+ class TextEvent(StreamEvent):
43
+ kind: StreamEventType = StreamEventType.TEXT
44
+ content: str
45
+
46
+
47
+ class ThinkingEvent(StreamEvent):
48
+ kind: StreamEventType = StreamEventType.THINKING
49
+ content: str
50
+
51
+
52
+ class ToolCallEvent(StreamEvent):
53
+ kind: StreamEventType = StreamEventType.TOOL_CALL
54
+ tool_call: ToolCall
55
+
56
+ def payload(self) -> dict[str, Any]:
57
+ return self.tool_call.model_dump()
58
+
59
+
60
+ class ToolResultEvent(StreamEvent):
61
+ kind: StreamEventType = StreamEventType.TOOL_RESULT
62
+ tool_result: ToolResult
63
+
64
+ def payload(self) -> dict[str, Any]:
65
+ return self.tool_result.model_dump()
66
+
67
+
68
+ class UIComponentEvent(StreamEvent):
69
+ """
70
+ Halt payload for a UI tool — shape is consumer-defined.
71
+ """
72
+
73
+ kind: StreamEventType = StreamEventType.UI_COMPONENT
74
+ tool_call_id: str
75
+ name: str
76
+ component: dict[str, Any]
77
+
78
+
79
+ class UsageEvent(StreamEvent):
80
+ kind: StreamEventType = StreamEventType.USAGE
81
+ total_tokens: int | None = None
82
+ prompt_tokens: int | None = None
83
+ completion_tokens: int | None = None
84
+
85
+
86
+ class StopEvent(StreamEvent):
87
+ kind: StreamEventType = StreamEventType.STOP
88
+ reason: StopReason
89
+
90
+
91
+ class DoneEvent(StreamEvent):
92
+ """
93
+ Normal completion of a streamed turn with no further tool work.
94
+ """
95
+
96
+ kind: StreamEventType = StreamEventType.DONE