nicegui-ai 0.2.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.
- nicegui_ai/__init__.py +96 -0
- nicegui_ai/adapters/__init__.py +15 -0
- nicegui_ai/adapters/agui.py +77 -0
- nicegui_ai/adapters/base.py +103 -0
- nicegui_ai/adapters/gemini.py +366 -0
- nicegui_ai/adapters/opencode.py +214 -0
- nicegui_ai/adapters/openrouter.py +301 -0
- nicegui_ai/approval_modal.py +144 -0
- nicegui_ai/artifact.py +182 -0
- nicegui_ai/artifact_viewer.py +319 -0
- nicegui_ai/branch.py +87 -0
- nicegui_ai/code_block.py +94 -0
- nicegui_ai/composer.py +268 -0
- nicegui_ai/demo.py +638 -0
- nicegui_ai/drawer.py +107 -0
- nicegui_ai/gallery.py +705 -0
- nicegui_ai/header.py +128 -0
- nicegui_ai/icons.py +218 -0
- nicegui_ai/markdown.py +152 -0
- nicegui_ai/message.py +467 -0
- nicegui_ai/model_selector.py +449 -0
- nicegui_ai/py.typed +0 -0
- nicegui_ai/queued_messages.py +176 -0
- nicegui_ai/reasoning.py +103 -0
- nicegui_ai/schema.py +179 -0
- nicegui_ai/stream.py +250 -0
- nicegui_ai/task_tray.py +135 -0
- nicegui_ai/theme.py +129 -0
- nicegui_ai/thread.py +163 -0
- nicegui_ai/tool_call.py +257 -0
- nicegui_ai/voice_pill.py +116 -0
- nicegui_ai-0.2.0.dist-info/METADATA +207 -0
- nicegui_ai-0.2.0.dist-info/RECORD +35 -0
- nicegui_ai-0.2.0.dist-info/WHEEL +4 -0
- nicegui_ai-0.2.0.dist-info/entry_points.txt +4 -0
nicegui_ai/__init__.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""nicegui-ai: Modern AI agent UI primitives for NiceGUI."""
|
|
2
|
+
|
|
3
|
+
from nicegui_ai.adapters import (
|
|
4
|
+
AgUiStreamAdapter,
|
|
5
|
+
BaseStreamAdapter,
|
|
6
|
+
GeminiStreamAdapter,
|
|
7
|
+
OpenCodeStreamAdapter,
|
|
8
|
+
OpenRouterStreamAdapter,
|
|
9
|
+
)
|
|
10
|
+
from nicegui_ai.approval_modal import ApprovalModal
|
|
11
|
+
from nicegui_ai.artifact import ArtifactCard
|
|
12
|
+
from nicegui_ai.artifact_viewer import ArtifactViewerDrawer
|
|
13
|
+
from nicegui_ai.branch import BranchPicker
|
|
14
|
+
from nicegui_ai.code_block import CodeBlock
|
|
15
|
+
from nicegui_ai.composer import AiComposer
|
|
16
|
+
from nicegui_ai.drawer import SlideOverDrawer
|
|
17
|
+
from nicegui_ai.header import FloatingHeader, TokenRing
|
|
18
|
+
from nicegui_ai.icons import LucideIcon, get_lucide_svg
|
|
19
|
+
from nicegui_ai.markdown import AiMarkdown, parse_markdown_blocks
|
|
20
|
+
from nicegui_ai.message import AgentMessage, UserMessage
|
|
21
|
+
from nicegui_ai.model_selector import (
|
|
22
|
+
ModelOption,
|
|
23
|
+
ModelSelector,
|
|
24
|
+
ReasoningEffortSelector,
|
|
25
|
+
)
|
|
26
|
+
from nicegui_ai.queued_messages import QueuedMessagesTray
|
|
27
|
+
from nicegui_ai.reasoning import ReasoningCard
|
|
28
|
+
from nicegui_ai.schema import (
|
|
29
|
+
AgUiEvent,
|
|
30
|
+
AgUiEventType,
|
|
31
|
+
ChatMessage,
|
|
32
|
+
MessageBranch,
|
|
33
|
+
MessageRole,
|
|
34
|
+
QueuedMessage,
|
|
35
|
+
ReasoningStep,
|
|
36
|
+
RunningTask,
|
|
37
|
+
SuggestionPrompt,
|
|
38
|
+
ToolCall,
|
|
39
|
+
ToolStatus,
|
|
40
|
+
)
|
|
41
|
+
from nicegui_ai.stream import StreamBridge, StreamResult
|
|
42
|
+
from nicegui_ai.task_tray import TaskHandle, TaskTray
|
|
43
|
+
from nicegui_ai.theme import THEME_CSS, setup_ai_theme
|
|
44
|
+
from nicegui_ai.thread import AiThread
|
|
45
|
+
from nicegui_ai.tool_call import ToolCallCard
|
|
46
|
+
from nicegui_ai.voice_pill import VoicePill
|
|
47
|
+
|
|
48
|
+
__version__ = "0.2.0"
|
|
49
|
+
|
|
50
|
+
__all__ = [
|
|
51
|
+
"AgUiEvent",
|
|
52
|
+
"AgUiEventType",
|
|
53
|
+
"AgUiStreamAdapter",
|
|
54
|
+
"AgentMessage",
|
|
55
|
+
"AiComposer",
|
|
56
|
+
"AiMarkdown",
|
|
57
|
+
"AiThread",
|
|
58
|
+
"ApprovalModal",
|
|
59
|
+
"ArtifactCard",
|
|
60
|
+
"ArtifactViewerDrawer",
|
|
61
|
+
"BaseStreamAdapter",
|
|
62
|
+
"BranchPicker",
|
|
63
|
+
"ChatMessage",
|
|
64
|
+
"CodeBlock",
|
|
65
|
+
"FloatingHeader",
|
|
66
|
+
"GeminiStreamAdapter",
|
|
67
|
+
"LucideIcon",
|
|
68
|
+
"MessageBranch",
|
|
69
|
+
"MessageRole",
|
|
70
|
+
"ModelOption",
|
|
71
|
+
"ModelSelector",
|
|
72
|
+
"OpenCodeStreamAdapter",
|
|
73
|
+
"OpenRouterStreamAdapter",
|
|
74
|
+
"QueuedMessage",
|
|
75
|
+
"QueuedMessagesTray",
|
|
76
|
+
"ReasoningCard",
|
|
77
|
+
"ReasoningEffortSelector",
|
|
78
|
+
"ReasoningStep",
|
|
79
|
+
"RunningTask",
|
|
80
|
+
"SlideOverDrawer",
|
|
81
|
+
"StreamBridge",
|
|
82
|
+
"StreamResult",
|
|
83
|
+
"SuggestionPrompt",
|
|
84
|
+
"THEME_CSS",
|
|
85
|
+
"TaskHandle",
|
|
86
|
+
"TaskTray",
|
|
87
|
+
"TokenRing",
|
|
88
|
+
"ToolCall",
|
|
89
|
+
"ToolCallCard",
|
|
90
|
+
"ToolStatus",
|
|
91
|
+
"UserMessage",
|
|
92
|
+
"VoicePill",
|
|
93
|
+
"get_lucide_svg",
|
|
94
|
+
"parse_markdown_blocks",
|
|
95
|
+
"setup_ai_theme",
|
|
96
|
+
]
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""AG-UI stream adapters for OpenRouter, Gemini, OpenCode, and native AG-UI sources."""
|
|
2
|
+
|
|
3
|
+
from nicegui_ai.adapters.agui import AgUiStreamAdapter
|
|
4
|
+
from nicegui_ai.adapters.base import BaseStreamAdapter
|
|
5
|
+
from nicegui_ai.adapters.gemini import GeminiStreamAdapter
|
|
6
|
+
from nicegui_ai.adapters.opencode import OpenCodeStreamAdapter
|
|
7
|
+
from nicegui_ai.adapters.openrouter import OpenRouterStreamAdapter
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"AgUiStreamAdapter",
|
|
11
|
+
"BaseStreamAdapter",
|
|
12
|
+
"GeminiStreamAdapter",
|
|
13
|
+
"OpenCodeStreamAdapter",
|
|
14
|
+
"OpenRouterStreamAdapter",
|
|
15
|
+
]
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""AG-UI native stream adapter supporting all AG-UI protocol events."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from collections.abc import AsyncIterable, AsyncIterator
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from nicegui_ai.adapters.base import BaseStreamAdapter
|
|
8
|
+
from nicegui_ai.schema import AgUiEvent, AgUiEventType
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class AgUiStreamAdapter(BaseStreamAdapter):
|
|
12
|
+
"""Adapter for native AG-UI streaming protocol sources."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, source: AsyncIterable[AgUiEvent | dict[str, Any] | str]) -> None:
|
|
15
|
+
super().__init__(source)
|
|
16
|
+
|
|
17
|
+
async def stream_events(self) -> AsyncIterator[AgUiEvent]:
|
|
18
|
+
"""Yield AG-UI events directly or parse from dict / JSON representation."""
|
|
19
|
+
async for raw_item in self.source:
|
|
20
|
+
event = self._normalize_item(raw_item)
|
|
21
|
+
if event is not None:
|
|
22
|
+
yield event
|
|
23
|
+
|
|
24
|
+
def _normalize_item(self, item: Any) -> AgUiEvent | None:
|
|
25
|
+
if isinstance(item, AgUiEvent):
|
|
26
|
+
return item
|
|
27
|
+
|
|
28
|
+
if isinstance(item, str):
|
|
29
|
+
item_str = item.strip()
|
|
30
|
+
if item_str.startswith("data:"):
|
|
31
|
+
item_str = item_str[5:].strip()
|
|
32
|
+
if not item_str:
|
|
33
|
+
return None
|
|
34
|
+
try:
|
|
35
|
+
item = json.loads(item_str)
|
|
36
|
+
except Exception:
|
|
37
|
+
# Text fallback chunk
|
|
38
|
+
return AgUiEvent(
|
|
39
|
+
type=AgUiEventType.TEXT_MESSAGE_CONTENT,
|
|
40
|
+
content=item,
|
|
41
|
+
raw_event=item,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
if isinstance(item, dict):
|
|
45
|
+
# Parse type
|
|
46
|
+
type_val = item.get("type", "TEXT_MESSAGE_CONTENT")
|
|
47
|
+
try:
|
|
48
|
+
event_type = AgUiEventType(type_val)
|
|
49
|
+
except ValueError:
|
|
50
|
+
event_type = AgUiEventType.CUSTOM
|
|
51
|
+
|
|
52
|
+
return AgUiEvent(
|
|
53
|
+
type=event_type,
|
|
54
|
+
timestamp=item.get("timestamp"),
|
|
55
|
+
raw_event=item.get("rawEvent") or item,
|
|
56
|
+
metadata=item.get("metadata", {}),
|
|
57
|
+
subagent_run_id=item.get("subagentRunId"),
|
|
58
|
+
run_id=item.get("runId"),
|
|
59
|
+
step_id=item.get("stepId"),
|
|
60
|
+
step_name=item.get("stepName"),
|
|
61
|
+
message_id=item.get("messageId"),
|
|
62
|
+
role=item.get("role"),
|
|
63
|
+
content=item.get("content") or item.get("text"),
|
|
64
|
+
tool_call_id=item.get("toolCallId") or item.get("id"),
|
|
65
|
+
tool_name=item.get("toolName") or item.get("name"),
|
|
66
|
+
args=item.get("args") or item.get("arguments"),
|
|
67
|
+
result=item.get("result"),
|
|
68
|
+
is_error=bool(item.get("isError")),
|
|
69
|
+
error=item.get("error"),
|
|
70
|
+
code=item.get("code"),
|
|
71
|
+
snapshot=item.get("snapshot"),
|
|
72
|
+
delta=item.get("delta"),
|
|
73
|
+
activity_id=item.get("activityId"),
|
|
74
|
+
custom_type=item.get("customType", type_val),
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
return None
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Abstract base class for all AG-UI streaming adapters adhering 100% to OOP principles."""
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from collections.abc import AsyncIterator
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from nicegui_ai.schema import AgUiEvent, AgUiEventType, ToolCall, ToolStatus
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class BaseStreamAdapter(ABC):
|
|
11
|
+
"""Abstract object-oriented stream adapter converting provider streams into AG-UI events."""
|
|
12
|
+
|
|
13
|
+
def __init__(self, source: Any) -> None:
|
|
14
|
+
self.source = source
|
|
15
|
+
self.text: str = ""
|
|
16
|
+
self.thought: str = ""
|
|
17
|
+
self.tool_calls: list[ToolCall] = []
|
|
18
|
+
self._tool_calls_by_id: dict[str, ToolCall] = {}
|
|
19
|
+
self.tool_results: dict[str, Any] = {}
|
|
20
|
+
self.usage: dict[str, int] = {}
|
|
21
|
+
self.finish_reason: str | None = None
|
|
22
|
+
self.error: Any | None = None
|
|
23
|
+
self.metadata: dict[str, Any] = {}
|
|
24
|
+
self.events: list[AgUiEvent] = []
|
|
25
|
+
|
|
26
|
+
@abstractmethod
|
|
27
|
+
def stream_events(self) -> AsyncIterator[AgUiEvent]:
|
|
28
|
+
"""Asynchronously yield standardized AG-UI events from the underlying stream."""
|
|
29
|
+
...
|
|
30
|
+
|
|
31
|
+
async def __aiter__(self) -> AsyncIterator[AgUiEvent]:
|
|
32
|
+
"""Asynchronously iterate over AG-UI events, tracking state accumulation."""
|
|
33
|
+
async for event in self.stream_events():
|
|
34
|
+
self._accumulate_state(event)
|
|
35
|
+
self.events.append(event)
|
|
36
|
+
yield event
|
|
37
|
+
|
|
38
|
+
def _accumulate_state(self, event: AgUiEvent) -> None:
|
|
39
|
+
"""Update internal state snapshot from event properties."""
|
|
40
|
+
if event.metadata:
|
|
41
|
+
self.metadata.update(event.metadata)
|
|
42
|
+
if "usage" in event.metadata and isinstance(event.metadata["usage"], dict):
|
|
43
|
+
self.usage.update(event.metadata["usage"])
|
|
44
|
+
|
|
45
|
+
match event.type:
|
|
46
|
+
case AgUiEventType.TEXT_MESSAGE_CONTENT | AgUiEventType.TEXT_MESSAGE_CHUNK:
|
|
47
|
+
if event.content:
|
|
48
|
+
self.text += event.content
|
|
49
|
+
|
|
50
|
+
case (
|
|
51
|
+
AgUiEventType.REASONING_MESSAGE_CONTENT
|
|
52
|
+
| AgUiEventType.REASONING_MESSAGE_CHUNK
|
|
53
|
+
):
|
|
54
|
+
if event.content:
|
|
55
|
+
self.thought += event.content
|
|
56
|
+
|
|
57
|
+
case AgUiEventType.TOOL_CALL_START:
|
|
58
|
+
if event.tool_call_id:
|
|
59
|
+
tool = ToolCall(
|
|
60
|
+
id=event.tool_call_id,
|
|
61
|
+
name=event.tool_name or "",
|
|
62
|
+
args=event.args if isinstance(event.args, dict) else {},
|
|
63
|
+
status=ToolStatus.EXECUTING,
|
|
64
|
+
)
|
|
65
|
+
self._tool_calls_by_id[event.tool_call_id] = tool
|
|
66
|
+
if tool not in self.tool_calls:
|
|
67
|
+
self.tool_calls.append(tool)
|
|
68
|
+
|
|
69
|
+
case AgUiEventType.TOOL_CALL_ARGS:
|
|
70
|
+
if event.tool_call_id and event.tool_call_id in self._tool_calls_by_id:
|
|
71
|
+
tool = self._tool_calls_by_id[event.tool_call_id]
|
|
72
|
+
if isinstance(event.args, dict):
|
|
73
|
+
tool.args.update(event.args)
|
|
74
|
+
|
|
75
|
+
case AgUiEventType.TOOL_CALL_END:
|
|
76
|
+
if event.tool_call_id and event.tool_call_id in self._tool_calls_by_id:
|
|
77
|
+
tool = self._tool_calls_by_id[event.tool_call_id]
|
|
78
|
+
if isinstance(event.args, dict):
|
|
79
|
+
tool.args = event.args
|
|
80
|
+
|
|
81
|
+
case AgUiEventType.TOOL_CALL_RESULT:
|
|
82
|
+
if event.tool_call_id:
|
|
83
|
+
self.tool_results[event.tool_call_id] = event.result
|
|
84
|
+
if event.tool_call_id in self._tool_calls_by_id:
|
|
85
|
+
tool = self._tool_calls_by_id[event.tool_call_id]
|
|
86
|
+
tool.result = event.result
|
|
87
|
+
tool.status = (
|
|
88
|
+
ToolStatus.FAILED if event.is_error else ToolStatus.RESOLVED
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
case AgUiEventType.RUN_FINISHED:
|
|
92
|
+
if "finish_reason" in event.metadata:
|
|
93
|
+
self.finish_reason = str(event.metadata["finish_reason"])
|
|
94
|
+
|
|
95
|
+
case AgUiEventType.RUN_ERROR:
|
|
96
|
+
self.error = event.error or event.code or "Execution failed"
|
|
97
|
+
|
|
98
|
+
async def collect(self) -> list[AgUiEvent]:
|
|
99
|
+
"""Consume and collect all events into an in-memory list."""
|
|
100
|
+
collected: list[AgUiEvent] = []
|
|
101
|
+
async for event in self:
|
|
102
|
+
collected.append(event)
|
|
103
|
+
return collected
|
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
"""Google GenAI (Gemini) streaming protocol adapter mapping 100% of provider events to AG-UI."""
|
|
2
|
+
|
|
3
|
+
import uuid
|
|
4
|
+
from collections.abc import AsyncIterable, AsyncIterator
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from nicegui_ai.adapters.base import BaseStreamAdapter
|
|
8
|
+
from nicegui_ai.schema import AgUiEvent, AgUiEventType
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class GeminiStreamAdapter(BaseStreamAdapter):
|
|
12
|
+
"""Adapter for Google GenAI SDK (client.aio.models.generate_content_stream)."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, source: AsyncIterable[Any]) -> None:
|
|
15
|
+
super().__init__(source)
|
|
16
|
+
self._text_started: bool = False
|
|
17
|
+
self._reasoning_started: bool = False
|
|
18
|
+
self._model_version: str | None = None
|
|
19
|
+
self._run_id: str = f"gemini-{uuid.uuid4().hex[:8]}"
|
|
20
|
+
|
|
21
|
+
async def stream_events(self) -> AsyncIterator[AgUiEvent]:
|
|
22
|
+
"""Convert Google GenAI stream chunks into complete AG-UI events."""
|
|
23
|
+
yield AgUiEvent(
|
|
24
|
+
type=AgUiEventType.RUN_STARTED,
|
|
25
|
+
run_id=self._run_id,
|
|
26
|
+
metadata={"source": "gemini"},
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
async for chunk in self.source:
|
|
30
|
+
for event in self._process_chunk(chunk):
|
|
31
|
+
yield event
|
|
32
|
+
|
|
33
|
+
# Close any active streams
|
|
34
|
+
if self._reasoning_started:
|
|
35
|
+
yield AgUiEvent(
|
|
36
|
+
type=AgUiEventType.REASONING_END,
|
|
37
|
+
run_id=self._run_id,
|
|
38
|
+
)
|
|
39
|
+
self._reasoning_started = False
|
|
40
|
+
|
|
41
|
+
if self._text_started:
|
|
42
|
+
yield AgUiEvent(
|
|
43
|
+
type=AgUiEventType.TEXT_MESSAGE_END,
|
|
44
|
+
run_id=self._run_id,
|
|
45
|
+
)
|
|
46
|
+
self._text_started = False
|
|
47
|
+
|
|
48
|
+
yield AgUiEvent(
|
|
49
|
+
type=AgUiEventType.RUN_FINISHED,
|
|
50
|
+
run_id=self._run_id,
|
|
51
|
+
metadata={
|
|
52
|
+
"finish_reason": self.finish_reason or "STOP",
|
|
53
|
+
"model_version": self._model_version,
|
|
54
|
+
"usage": self.usage,
|
|
55
|
+
},
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
def _process_chunk(self, chunk: Any) -> list[AgUiEvent]:
|
|
59
|
+
events: list[AgUiEvent] = []
|
|
60
|
+
|
|
61
|
+
model_version = getattr(chunk, "model_version", None) or (
|
|
62
|
+
chunk.get("model_version") if isinstance(chunk, dict) else None
|
|
63
|
+
)
|
|
64
|
+
if model_version:
|
|
65
|
+
self._model_version = str(model_version)
|
|
66
|
+
|
|
67
|
+
# 1. Usage metadata
|
|
68
|
+
usage = getattr(chunk, "usage_metadata", None) or (
|
|
69
|
+
chunk.get("usage_metadata") if isinstance(chunk, dict) else None
|
|
70
|
+
)
|
|
71
|
+
if usage:
|
|
72
|
+
prompt_tokens = getattr(usage, "prompt_token_count", 0) or (
|
|
73
|
+
usage.get("prompt_token_count", 0) if isinstance(usage, dict) else 0
|
|
74
|
+
)
|
|
75
|
+
candidates_tokens = getattr(usage, "candidates_token_count", 0) or (
|
|
76
|
+
usage.get("candidates_token_count", 0) if isinstance(usage, dict) else 0
|
|
77
|
+
)
|
|
78
|
+
total_tokens = getattr(usage, "total_token_count", 0) or (
|
|
79
|
+
usage.get("total_token_count", 0) if isinstance(usage, dict) else 0
|
|
80
|
+
)
|
|
81
|
+
cached_tokens = getattr(usage, "cached_content_token_count", 0) or (
|
|
82
|
+
usage.get("cached_content_token_count", 0)
|
|
83
|
+
if isinstance(usage, dict)
|
|
84
|
+
else 0
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
self.usage.update(
|
|
88
|
+
{
|
|
89
|
+
"prompt_tokens": int(prompt_tokens or 0),
|
|
90
|
+
"completion_tokens": int(candidates_tokens or 0),
|
|
91
|
+
"total_tokens": int(total_tokens or 0),
|
|
92
|
+
"cached_tokens": int(cached_tokens or 0),
|
|
93
|
+
}
|
|
94
|
+
)
|
|
95
|
+
events.append(
|
|
96
|
+
AgUiEvent(
|
|
97
|
+
type=AgUiEventType.STATE_DELTA,
|
|
98
|
+
delta={"usage": self.usage},
|
|
99
|
+
metadata={"usage": self.usage},
|
|
100
|
+
raw_event=usage,
|
|
101
|
+
)
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
# 2. Candidates
|
|
105
|
+
candidates = getattr(chunk, "candidates", None) or (
|
|
106
|
+
chunk.get("candidates") if isinstance(chunk, dict) else []
|
|
107
|
+
)
|
|
108
|
+
if not candidates:
|
|
109
|
+
# Fallback for direct text chunks
|
|
110
|
+
direct_text = getattr(chunk, "text", None)
|
|
111
|
+
if direct_text:
|
|
112
|
+
if not self._text_started:
|
|
113
|
+
self._text_started = True
|
|
114
|
+
events.append(
|
|
115
|
+
AgUiEvent(
|
|
116
|
+
type=AgUiEventType.TEXT_MESSAGE_START,
|
|
117
|
+
role="model",
|
|
118
|
+
run_id=self._run_id,
|
|
119
|
+
)
|
|
120
|
+
)
|
|
121
|
+
events.append(
|
|
122
|
+
AgUiEvent(
|
|
123
|
+
type=AgUiEventType.TEXT_MESSAGE_CONTENT,
|
|
124
|
+
content=str(direct_text),
|
|
125
|
+
raw_event=chunk,
|
|
126
|
+
)
|
|
127
|
+
)
|
|
128
|
+
return events
|
|
129
|
+
|
|
130
|
+
for cand in candidates:
|
|
131
|
+
finish_reason = getattr(cand, "finish_reason", None) or (
|
|
132
|
+
cand.get("finish_reason") if isinstance(cand, dict) else None
|
|
133
|
+
)
|
|
134
|
+
if finish_reason:
|
|
135
|
+
self.finish_reason = str(finish_reason)
|
|
136
|
+
|
|
137
|
+
# Safety ratings
|
|
138
|
+
safety_ratings = getattr(cand, "safety_ratings", None) or (
|
|
139
|
+
cand.get("safety_ratings") if isinstance(cand, dict) else None
|
|
140
|
+
)
|
|
141
|
+
if safety_ratings:
|
|
142
|
+
events.append(
|
|
143
|
+
AgUiEvent(
|
|
144
|
+
type=AgUiEventType.CUSTOM,
|
|
145
|
+
custom_type="safety_ratings",
|
|
146
|
+
snapshot=safety_ratings,
|
|
147
|
+
raw_event=safety_ratings,
|
|
148
|
+
)
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
# Grounding metadata (Google Search citations and queries)
|
|
152
|
+
grounding = getattr(cand, "grounding_metadata", None) or (
|
|
153
|
+
cand.get("grounding_metadata") if isinstance(cand, dict) else None
|
|
154
|
+
)
|
|
155
|
+
if grounding:
|
|
156
|
+
events.append(
|
|
157
|
+
AgUiEvent(
|
|
158
|
+
type=AgUiEventType.CUSTOM,
|
|
159
|
+
custom_type="grounding_metadata",
|
|
160
|
+
snapshot=grounding,
|
|
161
|
+
raw_event=grounding,
|
|
162
|
+
)
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
# Citation metadata
|
|
166
|
+
citations = getattr(cand, "citation_metadata", None) or (
|
|
167
|
+
cand.get("citation_metadata") if isinstance(cand, dict) else None
|
|
168
|
+
)
|
|
169
|
+
if citations:
|
|
170
|
+
events.append(
|
|
171
|
+
AgUiEvent(
|
|
172
|
+
type=AgUiEventType.CUSTOM,
|
|
173
|
+
custom_type="citation_metadata",
|
|
174
|
+
snapshot=citations,
|
|
175
|
+
raw_event=citations,
|
|
176
|
+
)
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
# Content parts
|
|
180
|
+
content = getattr(cand, "content", None) or (
|
|
181
|
+
cand.get("content") if isinstance(cand, dict) else None
|
|
182
|
+
)
|
|
183
|
+
if not content:
|
|
184
|
+
continue
|
|
185
|
+
|
|
186
|
+
raw_parts = getattr(content, "parts", None) or (
|
|
187
|
+
content.get("parts") if isinstance(content, dict) else None
|
|
188
|
+
)
|
|
189
|
+
parts = raw_parts if isinstance(raw_parts, list) else []
|
|
190
|
+
for part in parts:
|
|
191
|
+
events.extend(self._process_part(part))
|
|
192
|
+
|
|
193
|
+
return events
|
|
194
|
+
|
|
195
|
+
def _process_part(self, part: Any) -> list[AgUiEvent]:
|
|
196
|
+
events: list[AgUiEvent] = []
|
|
197
|
+
|
|
198
|
+
# Check if thought / reasoning block
|
|
199
|
+
is_thought = getattr(part, "thought", False) or (
|
|
200
|
+
part.get("thought", False) if isinstance(part, dict) else False
|
|
201
|
+
)
|
|
202
|
+
text = getattr(part, "text", None) or (
|
|
203
|
+
part.get("text") if isinstance(part, dict) else None
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
if is_thought and text:
|
|
207
|
+
if not self._reasoning_started:
|
|
208
|
+
self._reasoning_started = True
|
|
209
|
+
events.append(
|
|
210
|
+
AgUiEvent(
|
|
211
|
+
type=AgUiEventType.REASONING_START,
|
|
212
|
+
run_id=self._run_id,
|
|
213
|
+
)
|
|
214
|
+
)
|
|
215
|
+
events.append(
|
|
216
|
+
AgUiEvent(
|
|
217
|
+
type=AgUiEventType.REASONING_MESSAGE_CONTENT,
|
|
218
|
+
content=str(text),
|
|
219
|
+
run_id=self._run_id,
|
|
220
|
+
raw_event=part,
|
|
221
|
+
)
|
|
222
|
+
)
|
|
223
|
+
return events
|
|
224
|
+
|
|
225
|
+
# Standard text part
|
|
226
|
+
if text:
|
|
227
|
+
if self._reasoning_started:
|
|
228
|
+
self._reasoning_started = False
|
|
229
|
+
events.append(
|
|
230
|
+
AgUiEvent(
|
|
231
|
+
type=AgUiEventType.REASONING_END,
|
|
232
|
+
run_id=self._run_id,
|
|
233
|
+
)
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
if not self._text_started:
|
|
237
|
+
self._text_started = True
|
|
238
|
+
events.append(
|
|
239
|
+
AgUiEvent(
|
|
240
|
+
type=AgUiEventType.TEXT_MESSAGE_START,
|
|
241
|
+
role="model",
|
|
242
|
+
run_id=self._run_id,
|
|
243
|
+
)
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
events.append(
|
|
247
|
+
AgUiEvent(
|
|
248
|
+
type=AgUiEventType.TEXT_MESSAGE_CONTENT,
|
|
249
|
+
content=str(text),
|
|
250
|
+
run_id=self._run_id,
|
|
251
|
+
raw_event=part,
|
|
252
|
+
)
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
# Function / Tool Call
|
|
256
|
+
fn_call = getattr(part, "function_call", None) or (
|
|
257
|
+
part.get("function_call") if isinstance(part, dict) else None
|
|
258
|
+
)
|
|
259
|
+
if fn_call:
|
|
260
|
+
fn_name = getattr(fn_call, "name", "") or (
|
|
261
|
+
fn_call.get("name", "") if isinstance(fn_call, dict) else ""
|
|
262
|
+
)
|
|
263
|
+
fn_args = getattr(fn_call, "args", {}) or (
|
|
264
|
+
fn_call.get("args", {}) if isinstance(fn_call, dict) else {}
|
|
265
|
+
)
|
|
266
|
+
call_id = (
|
|
267
|
+
getattr(fn_call, "id", None)
|
|
268
|
+
or (fn_call.get("id") if isinstance(fn_call, dict) else None)
|
|
269
|
+
or f"gemini-fn-{uuid.uuid4().hex[:6]}"
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
# Convert map/protobuf struct to dict if needed
|
|
273
|
+
args_dict = (
|
|
274
|
+
dict(fn_args)
|
|
275
|
+
if isinstance(fn_args, dict)
|
|
276
|
+
else (getattr(fn_args, "__dict__", {}) if fn_args else {})
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
events.append(
|
|
280
|
+
AgUiEvent(
|
|
281
|
+
type=AgUiEventType.TOOL_CALL_START,
|
|
282
|
+
tool_call_id=call_id,
|
|
283
|
+
tool_name=str(fn_name),
|
|
284
|
+
args=args_dict,
|
|
285
|
+
raw_event=fn_call,
|
|
286
|
+
)
|
|
287
|
+
)
|
|
288
|
+
events.append(
|
|
289
|
+
AgUiEvent(
|
|
290
|
+
type=AgUiEventType.TOOL_CALL_ARGS,
|
|
291
|
+
tool_call_id=call_id,
|
|
292
|
+
tool_name=str(fn_name),
|
|
293
|
+
args=args_dict,
|
|
294
|
+
raw_event=fn_call,
|
|
295
|
+
)
|
|
296
|
+
)
|
|
297
|
+
events.append(
|
|
298
|
+
AgUiEvent(
|
|
299
|
+
type=AgUiEventType.TOOL_CALL_END,
|
|
300
|
+
tool_call_id=call_id,
|
|
301
|
+
tool_name=str(fn_name),
|
|
302
|
+
args=args_dict,
|
|
303
|
+
raw_event=fn_call,
|
|
304
|
+
)
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
# Function Response (Tool Execution Result)
|
|
308
|
+
fn_resp = getattr(part, "function_response", None) or (
|
|
309
|
+
part.get("function_response") if isinstance(part, dict) else None
|
|
310
|
+
)
|
|
311
|
+
if fn_resp:
|
|
312
|
+
resp_name = getattr(fn_resp, "name", "") or (
|
|
313
|
+
fn_resp.get("name", "") if isinstance(fn_resp, dict) else ""
|
|
314
|
+
)
|
|
315
|
+
resp_val = getattr(fn_resp, "response", None) or (
|
|
316
|
+
fn_resp.get("response") if isinstance(fn_resp, dict) else None
|
|
317
|
+
)
|
|
318
|
+
call_id = (
|
|
319
|
+
getattr(fn_resp, "id", None)
|
|
320
|
+
or (fn_resp.get("id") if isinstance(fn_resp, dict) else None)
|
|
321
|
+
or f"gemini-fn-{resp_name}"
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
events.append(
|
|
325
|
+
AgUiEvent(
|
|
326
|
+
type=AgUiEventType.TOOL_CALL_RESULT,
|
|
327
|
+
tool_call_id=call_id,
|
|
328
|
+
tool_name=str(resp_name),
|
|
329
|
+
result=resp_val,
|
|
330
|
+
raw_event=fn_resp,
|
|
331
|
+
)
|
|
332
|
+
)
|
|
333
|
+
|
|
334
|
+
# Executable Code (Code Execution Tool Invocation)
|
|
335
|
+
exec_code = getattr(part, "executable_code", None) or (
|
|
336
|
+
part.get("executable_code") if isinstance(part, dict) else None
|
|
337
|
+
)
|
|
338
|
+
if exec_code:
|
|
339
|
+
lang = getattr(exec_code, "language", "python")
|
|
340
|
+
code = getattr(exec_code, "code", "")
|
|
341
|
+
events.append(
|
|
342
|
+
AgUiEvent(
|
|
343
|
+
type=AgUiEventType.CUSTOM,
|
|
344
|
+
custom_type="code_execution_call",
|
|
345
|
+
snapshot={"language": lang, "code": code},
|
|
346
|
+
raw_event=exec_code,
|
|
347
|
+
)
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
# Code Execution Result
|
|
351
|
+
code_result = getattr(part, "code_execution_result", None) or (
|
|
352
|
+
part.get("code_execution_result") if isinstance(part, dict) else None
|
|
353
|
+
)
|
|
354
|
+
if code_result:
|
|
355
|
+
outcome = getattr(code_result, "outcome", "")
|
|
356
|
+
output = getattr(code_result, "output", "")
|
|
357
|
+
events.append(
|
|
358
|
+
AgUiEvent(
|
|
359
|
+
type=AgUiEventType.CUSTOM,
|
|
360
|
+
custom_type="code_execution_result",
|
|
361
|
+
snapshot={"outcome": outcome, "output": output},
|
|
362
|
+
raw_event=code_result,
|
|
363
|
+
)
|
|
364
|
+
)
|
|
365
|
+
|
|
366
|
+
return events
|