coco-framework 0.1.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.
- coco/__init__.py +3 -0
- coco/agents/__init__.py +9 -0
- coco/agents/_subagent_transformer.py +307 -0
- coco/agents/factory.py +2164 -0
- coco/agents/middleware/__init__.py +100 -0
- coco/agents/middleware/_execution.py +385 -0
- coco/agents/middleware/_redaction.py +454 -0
- coco/agents/middleware/_retry.py +134 -0
- coco/agents/middleware/_trace_policy.py +61 -0
- coco/agents/middleware/context_editing.py +306 -0
- coco/agents/middleware/file_search.py +433 -0
- coco/agents/middleware/human_in_the_loop.py +680 -0
- coco/agents/middleware/internal_call_transformer.py +108 -0
- coco/agents/middleware/model_call_limit.py +267 -0
- coco/agents/middleware/model_fallback.py +417 -0
- coco/agents/middleware/model_retry.py +327 -0
- coco/agents/middleware/pii.py +878 -0
- coco/agents/middleware/provider_tool_search.py +307 -0
- coco/agents/middleware/shell_tool.py +949 -0
- coco/agents/middleware/summarization.py +910 -0
- coco/agents/middleware/todo.py +357 -0
- coco/agents/middleware/tool_call_limit.py +495 -0
- coco/agents/middleware/tool_emulator.py +251 -0
- coco/agents/middleware/tool_error.py +209 -0
- coco/agents/middleware/tool_retry.py +421 -0
- coco/agents/middleware/tool_selection.py +515 -0
- coco/agents/middleware/types.py +2201 -0
- coco/agents/structured_output.py +472 -0
- coco/chat_models/__init__.py +7 -0
- coco/chat_models/base.py +1082 -0
- coco/embeddings/__init__.py +18 -0
- coco/embeddings/base.py +279 -0
- coco/mcp/__init__.py +36 -0
- coco/mcp/adapter.py +245 -0
- coco/mcp/elicitation.py +394 -0
- coco/mcp/tools.py +307 -0
- coco/messages/__init__.py +73 -0
- coco/py.typed +0 -0
- coco/rate_limiters/__init__.py +13 -0
- coco/tools/__init__.py +22 -0
- coco/tools/tool_node.py +20 -0
- coco_anthropic/__init__.py +15 -0
- coco_anthropic/_client_utils.py +81 -0
- coco_anthropic/_compat.py +228 -0
- coco_anthropic/_sdk_compat.py +124 -0
- coco_anthropic/_version.py +3 -0
- coco_anthropic/chat_models.py +3349 -0
- coco_anthropic/data/__init__.py +1 -0
- coco_anthropic/data/_profiles.py +491 -0
- coco_anthropic/data/profile_augmentations.toml +69 -0
- coco_anthropic/experimental.py +140 -0
- coco_anthropic/llms.py +428 -0
- coco_anthropic/middleware/__init__.py +25 -0
- coco_anthropic/middleware/anthropic_tools.py +1197 -0
- coco_anthropic/middleware/bash.py +84 -0
- coco_anthropic/middleware/file_search.py +360 -0
- coco_anthropic/middleware/prompt_caching.py +276 -0
- coco_anthropic/output_parsers.py +93 -0
- coco_anthropic/py.typed +0 -0
- coco_core/__init__.py +20 -0
- coco_core/_api/__init__.py +87 -0
- coco_core/_api/beta_decorator.py +266 -0
- coco_core/_api/deprecation.py +637 -0
- coco_core/_api/internal.py +23 -0
- coco_core/_api/path.py +50 -0
- coco_core/_import_utils.py +41 -0
- coco_core/_protocol.py +625 -0
- coco_core/_security/__init__.py +36 -0
- coco_core/_security/_exceptions.py +9 -0
- coco_core/_security/_policy.py +313 -0
- coco_core/_security/_ssrf_protection.py +155 -0
- coco_core/_security/_transport.py +254 -0
- coco_core/agents.py +258 -0
- coco_core/caches.py +272 -0
- coco_core/callbacks/__init__.py +132 -0
- coco_core/callbacks/base.py +1229 -0
- coco_core/callbacks/file.py +266 -0
- coco_core/callbacks/manager.py +2826 -0
- coco_core/callbacks/stdout.py +123 -0
- coco_core/callbacks/streaming_stdout.py +154 -0
- coco_core/callbacks/usage.py +124 -0
- coco_core/chat_history.py +267 -0
- coco_core/chat_loaders.py +26 -0
- coco_core/chat_sessions.py +19 -0
- coco_core/cross_encoders.py +18 -0
- coco_core/document_loaders/__init__.py +36 -0
- coco_core/document_loaders/base.py +155 -0
- coco_core/document_loaders/blob_loaders.py +38 -0
- coco_core/documents/__init__.py +55 -0
- coco_core/documents/base.py +347 -0
- coco_core/documents/compressor.py +74 -0
- coco_core/documents/transformers.py +79 -0
- coco_core/embeddings/__init__.py +31 -0
- coco_core/embeddings/embeddings.py +78 -0
- coco_core/embeddings/fake.py +129 -0
- coco_core/env.py +22 -0
- coco_core/example_selectors/__init__.py +47 -0
- coco_core/example_selectors/base.py +60 -0
- coco_core/example_selectors/length_based.py +131 -0
- coco_core/example_selectors/semantic_similarity.py +366 -0
- coco_core/exceptions.py +166 -0
- coco_core/globals.py +72 -0
- coco_core/indexing/__init__.py +53 -0
- coco_core/indexing/api.py +954 -0
- coco_core/indexing/base.py +661 -0
- coco_core/indexing/in_memory.py +104 -0
- coco_core/language_models/__init__.py +116 -0
- coco_core/language_models/_compat_bridge.py +844 -0
- coco_core/language_models/_utils.py +343 -0
- coco_core/language_models/base.py +500 -0
- coco_core/language_models/chat_model_stream.py +1525 -0
- coco_core/language_models/chat_models.py +2748 -0
- coco_core/language_models/fake.py +137 -0
- coco_core/language_models/fake_chat_models.py +396 -0
- coco_core/language_models/llms.py +1569 -0
- coco_core/language_models/model_profile.py +183 -0
- coco_core/load/__init__.py +44 -0
- coco_core/load/_validation.py +191 -0
- coco_core/load/dump.py +120 -0
- coco_core/load/load.py +828 -0
- coco_core/load/mapping.py +1097 -0
- coco_core/load/serializable.py +406 -0
- coco_core/messages/__init__.py +198 -0
- coco_core/messages/ai.py +854 -0
- coco_core/messages/base.py +518 -0
- coco_core/messages/block_translators/__init__.py +112 -0
- coco_core/messages/block_translators/anthropic.py +534 -0
- coco_core/messages/block_translators/bedrock.py +108 -0
- coco_core/messages/block_translators/bedrock_converse.py +329 -0
- coco_core/messages/block_translators/coco_v0.py +303 -0
- coco_core/messages/block_translators/google_genai.py +610 -0
- coco_core/messages/block_translators/google_vertexai.py +21 -0
- coco_core/messages/block_translators/groq.py +157 -0
- coco_core/messages/block_translators/openai.py +1089 -0
- coco_core/messages/chat.py +64 -0
- coco_core/messages/content.py +1488 -0
- coco_core/messages/function.py +62 -0
- coco_core/messages/human.py +70 -0
- coco_core/messages/modifier.py +33 -0
- coco_core/messages/system.py +70 -0
- coco_core/messages/tool.py +418 -0
- coco_core/messages/utils.py +2442 -0
- coco_core/output_parsers/__init__.py +101 -0
- coco_core/output_parsers/base.py +361 -0
- coco_core/output_parsers/format_instructions.py +16 -0
- coco_core/output_parsers/json.py +139 -0
- coco_core/output_parsers/list.py +249 -0
- coco_core/output_parsers/openai_functions.py +324 -0
- coco_core/output_parsers/openai_tools.py +383 -0
- coco_core/output_parsers/pydantic.py +141 -0
- coco_core/output_parsers/string.py +63 -0
- coco_core/output_parsers/transform.py +175 -0
- coco_core/output_parsers/xml.py +301 -0
- coco_core/outputs/__init__.py +66 -0
- coco_core/outputs/chat_generation.py +147 -0
- coco_core/outputs/chat_result.py +39 -0
- coco_core/outputs/generation.py +80 -0
- coco_core/outputs/llm_result.py +112 -0
- coco_core/outputs/run_info.py +22 -0
- coco_core/prompt_values.py +161 -0
- coco_core/prompts/__init__.py +101 -0
- coco_core/prompts/base.py +508 -0
- coco_core/prompts/chat.py +1495 -0
- coco_core/prompts/dict.py +177 -0
- coco_core/prompts/few_shot.py +483 -0
- coco_core/prompts/few_shot_with_templates.py +239 -0
- coco_core/prompts/image.py +177 -0
- coco_core/prompts/loading.py +296 -0
- coco_core/prompts/message.py +97 -0
- coco_core/prompts/prompt.py +312 -0
- coco_core/prompts/string.py +399 -0
- coco_core/prompts/structured.py +214 -0
- coco_core/py.typed +0 -0
- coco_core/rate_limiters.py +254 -0
- coco_core/retrievers.py +328 -0
- coco_core/runnables/__init__.py +136 -0
- coco_core/runnables/base.py +6725 -0
- coco_core/runnables/branch.py +457 -0
- coco_core/runnables/config.py +712 -0
- coco_core/runnables/configurable.py +710 -0
- coco_core/runnables/fallbacks.py +663 -0
- coco_core/runnables/graph.py +741 -0
- coco_core/runnables/graph_ascii.py +366 -0
- coco_core/runnables/graph_mermaid.py +503 -0
- coco_core/runnables/graph_png.py +215 -0
- coco_core/runnables/history.py +631 -0
- coco_core/runnables/passthrough.py +849 -0
- coco_core/runnables/retry.py +379 -0
- coco_core/runnables/router.py +239 -0
- coco_core/runnables/schema.py +188 -0
- coco_core/runnables/utils.py +798 -0
- coco_core/stores.py +291 -0
- coco_core/structured_query.py +203 -0
- coco_core/sys_info.py +154 -0
- coco_core/tools/__init__.py +95 -0
- coco_core/tools/base.py +1948 -0
- coco_core/tools/convert.py +497 -0
- coco_core/tools/render.py +67 -0
- coco_core/tools/retriever.py +94 -0
- coco_core/tools/simple.py +208 -0
- coco_core/tools/structured.py +322 -0
- coco_core/tracers/__init__.py +47 -0
- coco_core/tracers/_compat.py +95 -0
- coco_core/tracers/_context.py +337 -0
- coco_core/tracers/_streaming.py +53 -0
- coco_core/tracers/base.py +955 -0
- coco_core/tracers/coco.py +279 -0
- coco_core/tracers/context.py +205 -0
- coco_core/tracers/core.py +766 -0
- coco_core/tracers/event_stream.py +1101 -0
- coco_core/tracers/log_stream.py +765 -0
- coco_core/tracers/memory_stream.py +200 -0
- coco_core/tracers/root_listeners.py +130 -0
- coco_core/tracers/run_collector.py +40 -0
- coco_core/tracers/schemas.py +14 -0
- coco_core/tracers/stdout.py +205 -0
- coco_core/utils/__init__.py +111 -0
- coco_core/utils/_gateway.py +274 -0
- coco_core/utils/_merge.py +218 -0
- coco_core/utils/aiter.py +357 -0
- coco_core/utils/env.py +86 -0
- coco_core/utils/formatting.py +80 -0
- coco_core/utils/function_calling.py +869 -0
- coco_core/utils/html.py +132 -0
- coco_core/utils/image.py +15 -0
- coco_core/utils/input.py +82 -0
- coco_core/utils/interactive_env.py +12 -0
- coco_core/utils/iter.py +229 -0
- coco_core/utils/json.py +230 -0
- coco_core/utils/json_schema.py +273 -0
- coco_core/utils/mustache.py +706 -0
- coco_core/utils/pydantic.py +631 -0
- coco_core/utils/strings.py +69 -0
- coco_core/utils/usage.py +61 -0
- coco_core/utils/utils.py +528 -0
- coco_core/utils/uuid.py +57 -0
- coco_core/vectorstores/__init__.py +53 -0
- coco_core/vectorstores/base.py +1111 -0
- coco_core/vectorstores/in_memory.py +546 -0
- coco_core/vectorstores/utils.py +163 -0
- coco_core/version.py +3 -0
- coco_framework-0.1.0.dist-info/METADATA +184 -0
- coco_framework-0.1.0.dist-info/RECORD +400 -0
- coco_framework-0.1.0.dist-info/WHEEL +4 -0
- coco_framework-0.1.0.dist-info/licenses/LICENSE +24 -0
- coco_framework-0.1.0.dist-info/licenses/NOTICE +15 -0
- coco_graph/_internal/__init__.py +4 -0
- coco_graph/_internal/_cache.py +31 -0
- coco_graph/_internal/_config.py +474 -0
- coco_graph/_internal/_constants.py +140 -0
- coco_graph/_internal/_fields.py +213 -0
- coco_graph/_internal/_future.py +220 -0
- coco_graph/_internal/_pydantic.py +275 -0
- coco_graph/_internal/_queue.py +124 -0
- coco_graph/_internal/_replay.py +90 -0
- coco_graph/_internal/_retry.py +29 -0
- coco_graph/_internal/_runnable.py +969 -0
- coco_graph/_internal/_scratchpad.py +19 -0
- coco_graph/_internal/_serde.py +253 -0
- coco_graph/_internal/_timeout.py +25 -0
- coco_graph/_internal/_typing.py +54 -0
- coco_graph/cache/base/__init__.py +48 -0
- coco_graph/cache/base/py.typed +0 -0
- coco_graph/cache/memory/__init__.py +73 -0
- coco_graph/cache/redis/__init__.py +144 -0
- coco_graph/cache/sqlite/__init__.py +120 -0
- coco_graph/callbacks.py +394 -0
- coco_graph/channels/__init__.py +29 -0
- coco_graph/channels/any_value.py +72 -0
- coco_graph/channels/base.py +121 -0
- coco_graph/channels/binop.py +155 -0
- coco_graph/channels/delta.py +202 -0
- coco_graph/channels/ephemeral_value.py +79 -0
- coco_graph/channels/last_value.py +151 -0
- coco_graph/channels/named_barrier_value.py +167 -0
- coco_graph/channels/topic.py +94 -0
- coco_graph/channels/untracked_value.py +73 -0
- coco_graph/checkpoint/base/__init__.py +861 -0
- coco_graph/checkpoint/base/id.py +109 -0
- coco_graph/checkpoint/base/py.typed +0 -0
- coco_graph/checkpoint/memory/__init__.py +698 -0
- coco_graph/checkpoint/memory/py.typed +0 -0
- coco_graph/checkpoint/postgres/__init__.py +602 -0
- coco_graph/checkpoint/postgres/_ainternal.py +23 -0
- coco_graph/checkpoint/postgres/_internal.py +21 -0
- coco_graph/checkpoint/postgres/aio.py +691 -0
- coco_graph/checkpoint/postgres/base.py +666 -0
- coco_graph/checkpoint/postgres/py.typed +0 -0
- coco_graph/checkpoint/postgres/shallow.py +967 -0
- coco_graph/checkpoint/serde/__init__.py +0 -0
- coco_graph/checkpoint/serde/_msgpack.py +97 -0
- coco_graph/checkpoint/serde/base.py +64 -0
- coco_graph/checkpoint/serde/encrypted.py +80 -0
- coco_graph/checkpoint/serde/event_hooks.py +52 -0
- coco_graph/checkpoint/serde/jsonplus.py +883 -0
- coco_graph/checkpoint/serde/py.typed +0 -0
- coco_graph/checkpoint/serde/types.py +68 -0
- coco_graph/checkpoint/sqlite/__init__.py +645 -0
- coco_graph/checkpoint/sqlite/_delta.py +172 -0
- coco_graph/checkpoint/sqlite/aio.py +738 -0
- coco_graph/checkpoint/sqlite/py.typed +0 -0
- coco_graph/checkpoint/sqlite/utils.py +116 -0
- coco_graph/config.py +196 -0
- coco_graph/constants.py +64 -0
- coco_graph/errors.py +241 -0
- coco_graph/func/__init__.py +620 -0
- coco_graph/graph/__init__.py +12 -0
- coco_graph/graph/_branch.py +225 -0
- coco_graph/graph/_node.py +103 -0
- coco_graph/graph/message.py +437 -0
- coco_graph/graph/state.py +1978 -0
- coco_graph/graph/ui.py +227 -0
- coco_graph/managed/__init__.py +3 -0
- coco_graph/managed/base.py +31 -0
- coco_graph/managed/is_last_step.py +24 -0
- coco_graph/prebuilt/__init__.py +23 -0
- coco_graph/prebuilt/_tool_call_stream.py +117 -0
- coco_graph/prebuilt/_tool_call_transformer.py +165 -0
- coco_graph/prebuilt/chat_agent_executor.py +1015 -0
- coco_graph/prebuilt/interrupt.py +105 -0
- coco_graph/prebuilt/py.typed +0 -0
- coco_graph/prebuilt/tool_node.py +2030 -0
- coco_graph/prebuilt/tool_validator.py +221 -0
- coco_graph/pregel/__init__.py +3 -0
- coco_graph/pregel/_algo.py +1460 -0
- coco_graph/pregel/_call.py +298 -0
- coco_graph/pregel/_checkpoint.py +331 -0
- coco_graph/pregel/_config.py +0 -0
- coco_graph/pregel/_draw.py +294 -0
- coco_graph/pregel/_executor.py +223 -0
- coco_graph/pregel/_io.py +174 -0
- coco_graph/pregel/_log.py +3 -0
- coco_graph/pregel/_loop.py +1988 -0
- coco_graph/pregel/_messages.py +461 -0
- coco_graph/pregel/_read.py +312 -0
- coco_graph/pregel/_retry.py +854 -0
- coco_graph/pregel/_runner.py +941 -0
- coco_graph/pregel/_tools.py +268 -0
- coco_graph/pregel/_utils.py +221 -0
- coco_graph/pregel/_validate.py +120 -0
- coco_graph/pregel/_write.py +192 -0
- coco_graph/pregel/debug.py +302 -0
- coco_graph/pregel/main.py +4364 -0
- coco_graph/pregel/protocol.py +288 -0
- coco_graph/pregel/types.py +38 -0
- coco_graph/py.typed +0 -0
- coco_graph/runtime.py +350 -0
- coco_graph/store/base/__init__.py +1322 -0
- coco_graph/store/base/batch.py +371 -0
- coco_graph/store/base/embed.py +436 -0
- coco_graph/store/base/py.typed +0 -0
- coco_graph/store/memory/__init__.py +592 -0
- coco_graph/store/memory/py.typed +0 -0
- coco_graph/store/postgres/__init__.py +4 -0
- coco_graph/store/postgres/aio.py +592 -0
- coco_graph/store/postgres/base.py +1480 -0
- coco_graph/store/postgres/py.typed +0 -0
- coco_graph/store/sqlite/__init__.py +4 -0
- coco_graph/store/sqlite/aio.py +632 -0
- coco_graph/store/sqlite/base.py +1514 -0
- coco_graph/stream/__init__.py +45 -0
- coco_graph/stream/_convert.py +32 -0
- coco_graph/stream/_mux.py +523 -0
- coco_graph/stream/_types.py +330 -0
- coco_graph/stream/run_stream.py +735 -0
- coco_graph/stream/stream_channel.py +341 -0
- coco_graph/stream/transformers.py +1039 -0
- coco_graph/types.py +1079 -0
- coco_graph/typing.py +48 -0
- coco_graph/utils/__init__.py +1 -0
- coco_graph/utils/config.py +4 -0
- coco_graph/utils/runnable.py +3 -0
- coco_graph/version.py +13 -0
- coco_graph/warnings.py +69 -0
- coco_openai/__init__.py +20 -0
- coco_openai/_compat.py +45 -0
- coco_openai/_version.py +3 -0
- coco_openai/chat_models/__init__.py +6 -0
- coco_openai/chat_models/_client_utils.py +684 -0
- coco_openai/chat_models/_compat.py +525 -0
- coco_openai/chat_models/azure.py +1227 -0
- coco_openai/chat_models/base.py +5654 -0
- coco_openai/chat_models/codex.py +557 -0
- coco_openai/chatgpt_oauth.py +1063 -0
- coco_openai/data/__init__.py +1 -0
- coco_openai/data/_profiles.py +1655 -0
- coco_openai/data/profile_augmentations.toml +127 -0
- coco_openai/embeddings/__init__.py +6 -0
- coco_openai/embeddings/azure.py +240 -0
- coco_openai/embeddings/base.py +820 -0
- coco_openai/llms/__init__.py +6 -0
- coco_openai/llms/azure.py +249 -0
- coco_openai/llms/base.py +919 -0
- coco_openai/middleware/__init__.py +11 -0
- coco_openai/middleware/openai_moderation.py +484 -0
- coco_openai/output_parsers/__init__.py +9 -0
- coco_openai/output_parsers/tools.py +9 -0
- coco_openai/py.typed +0 -0
- coco_openai/tools/__init__.py +5 -0
- coco_openai/tools/custom_tool.py +111 -0
coco_core/messages/ai.py
ADDED
|
@@ -0,0 +1,854 @@
|
|
|
1
|
+
"""AI message."""
|
|
2
|
+
|
|
3
|
+
import itertools
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import operator
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from typing import Any, Literal, cast, overload
|
|
9
|
+
|
|
10
|
+
from pydantic import Field, model_validator
|
|
11
|
+
from typing_extensions import NotRequired, Self, TypedDict, override
|
|
12
|
+
|
|
13
|
+
from coco_core.messages import content as types
|
|
14
|
+
from coco_core.messages.base import (
|
|
15
|
+
BaseMessage,
|
|
16
|
+
BaseMessageChunk,
|
|
17
|
+
_extract_reasoning_from_additional_kwargs,
|
|
18
|
+
merge_content,
|
|
19
|
+
)
|
|
20
|
+
from coco_core.messages.content import InvalidToolCall
|
|
21
|
+
from coco_core.messages.tool import (
|
|
22
|
+
ToolCall,
|
|
23
|
+
ToolCallChunk,
|
|
24
|
+
default_tool_chunk_parser,
|
|
25
|
+
default_tool_parser,
|
|
26
|
+
)
|
|
27
|
+
from coco_core.messages.tool import invalid_tool_call as create_invalid_tool_call
|
|
28
|
+
from coco_core.messages.tool import tool_call as create_tool_call
|
|
29
|
+
from coco_core.messages.tool import tool_call_chunk as create_tool_call_chunk
|
|
30
|
+
from coco_core.utils._merge import merge_dicts, merge_lists
|
|
31
|
+
from coco_core.utils.json import parse_partial_json
|
|
32
|
+
from coco_core.utils.usage import _dict_int_op
|
|
33
|
+
from coco_core.utils.utils import LC_AUTO_PREFIX, LC_ID_PREFIX
|
|
34
|
+
|
|
35
|
+
logger = logging.getLogger(__name__)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class InputTokenDetails(TypedDict, total=False):
|
|
39
|
+
"""Breakdown of input token counts.
|
|
40
|
+
|
|
41
|
+
Does *not* need to sum to full input token count. Does *not* need to have all keys.
|
|
42
|
+
|
|
43
|
+
Example:
|
|
44
|
+
```python
|
|
45
|
+
{
|
|
46
|
+
"audio": 10,
|
|
47
|
+
"cache_creation": 200,
|
|
48
|
+
"cache_read": 100,
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
May also hold extra provider-specific keys.
|
|
53
|
+
|
|
54
|
+
!!! version-added "Added in `trustcoco-core` 0.3.9"
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
audio: int
|
|
58
|
+
"""Audio input tokens."""
|
|
59
|
+
|
|
60
|
+
cache_creation: int
|
|
61
|
+
"""Input tokens that were cached and there was a cache miss.
|
|
62
|
+
|
|
63
|
+
Since there was a cache miss, the cache was created from these tokens.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
cache_read: int
|
|
67
|
+
"""Input tokens that were cached and there was a cache hit.
|
|
68
|
+
|
|
69
|
+
Since there was a cache hit, the tokens were read from the cache. More precisely,
|
|
70
|
+
the model state given these tokens was read from the cache.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class OutputTokenDetails(TypedDict, total=False):
|
|
75
|
+
"""Breakdown of output token counts.
|
|
76
|
+
|
|
77
|
+
Does *not* need to sum to full output token count. Does *not* need to have all keys.
|
|
78
|
+
|
|
79
|
+
Example:
|
|
80
|
+
```python
|
|
81
|
+
{
|
|
82
|
+
"audio": 10,
|
|
83
|
+
"reasoning": 200,
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
May also hold extra provider-specific keys.
|
|
88
|
+
|
|
89
|
+
!!! version-added "Added in `trustcoco-core` 0.3.9"
|
|
90
|
+
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
audio: int
|
|
94
|
+
"""Audio output tokens."""
|
|
95
|
+
|
|
96
|
+
reasoning: int
|
|
97
|
+
"""Reasoning output tokens.
|
|
98
|
+
|
|
99
|
+
Tokens generated by the model in a chain of thought process that are not
|
|
100
|
+
returned as part of model output.
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class UsageMetadata(TypedDict):
|
|
105
|
+
"""Usage metadata for a message, such as token counts.
|
|
106
|
+
|
|
107
|
+
This is a standard representation of token usage that is consistent across models.
|
|
108
|
+
|
|
109
|
+
Example:
|
|
110
|
+
```python
|
|
111
|
+
{
|
|
112
|
+
"input_tokens": 350,
|
|
113
|
+
"output_tokens": 240,
|
|
114
|
+
"total_tokens": 590,
|
|
115
|
+
"input_token_details": {
|
|
116
|
+
"audio": 10,
|
|
117
|
+
"cache_creation": 200,
|
|
118
|
+
"cache_read": 100,
|
|
119
|
+
},
|
|
120
|
+
"output_token_details": {
|
|
121
|
+
"audio": 10,
|
|
122
|
+
"reasoning": 200,
|
|
123
|
+
},
|
|
124
|
+
}
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
!!! warning "Behavior changed in `trustcoco-core` 0.3.9"
|
|
128
|
+
|
|
129
|
+
Added `input_token_details` and `output_token_details`.
|
|
130
|
+
|
|
131
|
+
!!! note "LangSmith SDK"
|
|
132
|
+
|
|
133
|
+
The LangSmith SDK also has a `UsageMetadata` class. While the two share fields,
|
|
134
|
+
LangSmith's `UsageMetadata` has additional fields to capture cost information
|
|
135
|
+
used by the LangSmith platform.
|
|
136
|
+
"""
|
|
137
|
+
|
|
138
|
+
input_tokens: int
|
|
139
|
+
"""Count of input (or prompt) tokens. Sum of all input token types."""
|
|
140
|
+
|
|
141
|
+
output_tokens: int
|
|
142
|
+
"""Count of output (or completion) tokens. Sum of all output token types."""
|
|
143
|
+
|
|
144
|
+
total_tokens: int
|
|
145
|
+
"""Total token count. Sum of `input_tokens` + `output_tokens`."""
|
|
146
|
+
|
|
147
|
+
input_token_details: NotRequired[InputTokenDetails]
|
|
148
|
+
"""Breakdown of input token counts.
|
|
149
|
+
|
|
150
|
+
Does *not* need to sum to full input token count. Does *not* need to have all keys.
|
|
151
|
+
"""
|
|
152
|
+
|
|
153
|
+
output_token_details: NotRequired[OutputTokenDetails]
|
|
154
|
+
"""Breakdown of output token counts.
|
|
155
|
+
|
|
156
|
+
Does *not* need to sum to full output token count. Does *not* need to have all keys.
|
|
157
|
+
"""
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class AIMessage(BaseMessage):
|
|
161
|
+
"""Message from an AI.
|
|
162
|
+
|
|
163
|
+
An `AIMessage` is returned from a chat model as a response to a prompt.
|
|
164
|
+
|
|
165
|
+
This message represents the output of the model and consists of both
|
|
166
|
+
the raw output as returned by the model and standardized fields
|
|
167
|
+
(e.g., tool calls, usage metadata) added by the Coco framework.
|
|
168
|
+
"""
|
|
169
|
+
|
|
170
|
+
tool_calls: list[ToolCall] = Field(default_factory=list)
|
|
171
|
+
"""If present, tool calls associated with the message."""
|
|
172
|
+
|
|
173
|
+
invalid_tool_calls: list[InvalidToolCall] = Field(default_factory=list)
|
|
174
|
+
"""If present, tool calls with parsing errors associated with the message."""
|
|
175
|
+
|
|
176
|
+
usage_metadata: UsageMetadata | None = None
|
|
177
|
+
"""If present, usage metadata for a message, such as token counts.
|
|
178
|
+
|
|
179
|
+
This is a standard representation of token usage that is consistent across models.
|
|
180
|
+
"""
|
|
181
|
+
|
|
182
|
+
type: Literal["ai"] = "ai"
|
|
183
|
+
"""The type of the message (used for deserialization)."""
|
|
184
|
+
|
|
185
|
+
@overload
|
|
186
|
+
def __init__(
|
|
187
|
+
self,
|
|
188
|
+
content: str | list[str | dict[Any, Any]],
|
|
189
|
+
**kwargs: Any,
|
|
190
|
+
) -> None: ...
|
|
191
|
+
|
|
192
|
+
@overload
|
|
193
|
+
def __init__(
|
|
194
|
+
self,
|
|
195
|
+
content: str | list[str | dict[Any, Any]] | None = None,
|
|
196
|
+
content_blocks: list[types.ContentBlock] | None = None,
|
|
197
|
+
**kwargs: Any,
|
|
198
|
+
) -> None: ...
|
|
199
|
+
|
|
200
|
+
def __init__(
|
|
201
|
+
self,
|
|
202
|
+
content: str | list[str | dict[Any, Any]] | None = None,
|
|
203
|
+
content_blocks: list[types.ContentBlock] | None = None,
|
|
204
|
+
**kwargs: Any,
|
|
205
|
+
) -> None:
|
|
206
|
+
"""Initialize an `AIMessage`.
|
|
207
|
+
|
|
208
|
+
Specify `content` as positional arg or `content_blocks` for typing.
|
|
209
|
+
|
|
210
|
+
Args:
|
|
211
|
+
content: The content of the message.
|
|
212
|
+
content_blocks: Typed standard content.
|
|
213
|
+
**kwargs: Additional arguments to pass to the parent class.
|
|
214
|
+
"""
|
|
215
|
+
if content_blocks is not None:
|
|
216
|
+
# If there are tool calls in content_blocks, but not in tool_calls, add them
|
|
217
|
+
content_tool_calls = [
|
|
218
|
+
block for block in content_blocks if block.get("type") == "tool_call"
|
|
219
|
+
]
|
|
220
|
+
if content_tool_calls and "tool_calls" not in kwargs:
|
|
221
|
+
kwargs["tool_calls"] = content_tool_calls
|
|
222
|
+
|
|
223
|
+
super().__init__(
|
|
224
|
+
content=cast("list[str | dict[Any, Any]]", content_blocks),
|
|
225
|
+
**kwargs,
|
|
226
|
+
)
|
|
227
|
+
else:
|
|
228
|
+
super().__init__(content=content, **kwargs)
|
|
229
|
+
|
|
230
|
+
@property
|
|
231
|
+
def lc_attributes(self) -> dict[str, Any]:
|
|
232
|
+
"""Attributes to be serialized.
|
|
233
|
+
|
|
234
|
+
Includes all attributes, even if they are derived from other initialization
|
|
235
|
+
arguments.
|
|
236
|
+
"""
|
|
237
|
+
return {
|
|
238
|
+
"tool_calls": self.tool_calls,
|
|
239
|
+
"invalid_tool_calls": self.invalid_tool_calls,
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
@property
|
|
243
|
+
def content_blocks(self) -> list[types.ContentBlock]:
|
|
244
|
+
"""Return standard, typed `ContentBlock` dicts from the message.
|
|
245
|
+
|
|
246
|
+
If the message has a known model provider, use the provider-specific translator
|
|
247
|
+
first before falling back to best-effort parsing. For details, see the property
|
|
248
|
+
on `BaseMessage`.
|
|
249
|
+
"""
|
|
250
|
+
if self.response_metadata.get("output_version") == "v1" and isinstance(
|
|
251
|
+
self.content, list
|
|
252
|
+
):
|
|
253
|
+
# Only short-circuit when content is a list (assumed under v1 to
|
|
254
|
+
# already hold ContentBlock dicts; the cast is unchecked). See
|
|
255
|
+
# AIMessageChunk.content_blocks for full rationale.
|
|
256
|
+
return cast("list[types.ContentBlock]", self.content)
|
|
257
|
+
|
|
258
|
+
model_provider = self.response_metadata.get("model_provider")
|
|
259
|
+
if model_provider:
|
|
260
|
+
from coco_core.messages.block_translators import ( # noqa: PLC0415
|
|
261
|
+
get_translator,
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
translator = get_translator(model_provider)
|
|
265
|
+
if translator:
|
|
266
|
+
try:
|
|
267
|
+
return translator["translate_content"](self)
|
|
268
|
+
except NotImplementedError:
|
|
269
|
+
pass
|
|
270
|
+
|
|
271
|
+
# Otherwise, use best-effort parsing
|
|
272
|
+
blocks = super().content_blocks
|
|
273
|
+
|
|
274
|
+
if self.tool_calls:
|
|
275
|
+
# Add from tool_calls if missing from content
|
|
276
|
+
content_tool_call_ids = {
|
|
277
|
+
block.get("id")
|
|
278
|
+
for block in self.content
|
|
279
|
+
if isinstance(block, dict) and block.get("type") == "tool_call"
|
|
280
|
+
}
|
|
281
|
+
for tool_call in self.tool_calls:
|
|
282
|
+
if (id_ := tool_call.get("id")) and id_ not in content_tool_call_ids:
|
|
283
|
+
tool_call_block: types.ToolCall = {
|
|
284
|
+
"type": "tool_call",
|
|
285
|
+
"id": id_,
|
|
286
|
+
"name": tool_call["name"],
|
|
287
|
+
"args": tool_call["args"],
|
|
288
|
+
}
|
|
289
|
+
if "index" in tool_call:
|
|
290
|
+
tool_call_block["index"] = tool_call["index"] # type: ignore[typeddict-item]
|
|
291
|
+
if "extras" in tool_call:
|
|
292
|
+
tool_call_block["extras"] = tool_call["extras"] # type: ignore[typeddict-item]
|
|
293
|
+
blocks.append(tool_call_block)
|
|
294
|
+
|
|
295
|
+
# Best-effort reasoning extraction from additional_kwargs
|
|
296
|
+
# Only add reasoning if not already present
|
|
297
|
+
# Insert before all other blocks to keep reasoning at the start
|
|
298
|
+
has_reasoning = any(block.get("type") == "reasoning" for block in blocks)
|
|
299
|
+
if not has_reasoning and (
|
|
300
|
+
reasoning_block := _extract_reasoning_from_additional_kwargs(self)
|
|
301
|
+
):
|
|
302
|
+
blocks.insert(0, reasoning_block)
|
|
303
|
+
|
|
304
|
+
return blocks
|
|
305
|
+
|
|
306
|
+
# TODO: remove this logic if possible, reducing breaking nature of changes
|
|
307
|
+
@model_validator(mode="before")
|
|
308
|
+
@classmethod
|
|
309
|
+
def _backwards_compat_tool_calls(cls, values: dict[str, Any]) -> Any:
|
|
310
|
+
check_additional_kwargs = not any(
|
|
311
|
+
values.get(k)
|
|
312
|
+
for k in ("tool_calls", "invalid_tool_calls", "tool_call_chunks")
|
|
313
|
+
)
|
|
314
|
+
if check_additional_kwargs and (
|
|
315
|
+
raw_tool_calls := values.get("additional_kwargs", {}).get("tool_calls")
|
|
316
|
+
):
|
|
317
|
+
try:
|
|
318
|
+
if issubclass(cls, AIMessageChunk):
|
|
319
|
+
values["tool_call_chunks"] = default_tool_chunk_parser(
|
|
320
|
+
raw_tool_calls
|
|
321
|
+
)
|
|
322
|
+
else:
|
|
323
|
+
parsed_tool_calls, parsed_invalid_tool_calls = default_tool_parser(
|
|
324
|
+
raw_tool_calls
|
|
325
|
+
)
|
|
326
|
+
values["tool_calls"] = parsed_tool_calls
|
|
327
|
+
values["invalid_tool_calls"] = parsed_invalid_tool_calls
|
|
328
|
+
except Exception:
|
|
329
|
+
logger.debug("Failed to parse tool calls", exc_info=True)
|
|
330
|
+
|
|
331
|
+
# Ensure "type" is properly set on all tool call-like dicts.
|
|
332
|
+
if tool_calls := values.get("tool_calls"):
|
|
333
|
+
values["tool_calls"] = [
|
|
334
|
+
create_tool_call(
|
|
335
|
+
**{k: v for k, v in tc.items() if k not in {"type", "extras"}}
|
|
336
|
+
)
|
|
337
|
+
for tc in tool_calls
|
|
338
|
+
]
|
|
339
|
+
if invalid_tool_calls := values.get("invalid_tool_calls"):
|
|
340
|
+
values["invalid_tool_calls"] = [
|
|
341
|
+
create_invalid_tool_call(**{k: v for k, v in tc.items() if k != "type"})
|
|
342
|
+
for tc in invalid_tool_calls
|
|
343
|
+
]
|
|
344
|
+
|
|
345
|
+
if tool_call_chunks := values.get("tool_call_chunks"):
|
|
346
|
+
values["tool_call_chunks"] = [
|
|
347
|
+
create_tool_call_chunk(**{k: v for k, v in tc.items() if k != "type"})
|
|
348
|
+
for tc in tool_call_chunks
|
|
349
|
+
]
|
|
350
|
+
|
|
351
|
+
return values
|
|
352
|
+
|
|
353
|
+
@override
|
|
354
|
+
def pretty_repr(self, html: bool = False) -> str:
|
|
355
|
+
"""Return a pretty representation of the message for display.
|
|
356
|
+
|
|
357
|
+
Args:
|
|
358
|
+
html: Whether to return an HTML-formatted string.
|
|
359
|
+
|
|
360
|
+
Returns:
|
|
361
|
+
A pretty representation of the message.
|
|
362
|
+
|
|
363
|
+
Example:
|
|
364
|
+
```python
|
|
365
|
+
from coco_core.messages import AIMessage
|
|
366
|
+
|
|
367
|
+
msg = AIMessage(
|
|
368
|
+
content="Let me check the weather.",
|
|
369
|
+
tool_calls=[
|
|
370
|
+
{"name": "get_weather", "args": {"city": "Paris"}, "id": "1"}
|
|
371
|
+
],
|
|
372
|
+
)
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
Results in:
|
|
376
|
+
```python
|
|
377
|
+
>>> print(msg.pretty_repr())
|
|
378
|
+
================================== Ai Message ==================================
|
|
379
|
+
|
|
380
|
+
Let me check the weather.
|
|
381
|
+
Tool Calls:
|
|
382
|
+
get_weather (1)
|
|
383
|
+
Call ID: 1
|
|
384
|
+
Args:
|
|
385
|
+
city: Paris
|
|
386
|
+
```
|
|
387
|
+
""" # noqa: E501
|
|
388
|
+
base = super().pretty_repr(html=html)
|
|
389
|
+
lines = []
|
|
390
|
+
|
|
391
|
+
def _format_tool_args(tc: ToolCall | InvalidToolCall) -> list[str]:
|
|
392
|
+
lines = [
|
|
393
|
+
f" {tc.get('name', 'Tool')} ({tc.get('id')})",
|
|
394
|
+
f" Call ID: {tc.get('id')}",
|
|
395
|
+
]
|
|
396
|
+
if tc.get("error"):
|
|
397
|
+
lines.append(f" Error: {tc.get('error')}")
|
|
398
|
+
lines.append(" Args:")
|
|
399
|
+
args = tc.get("args")
|
|
400
|
+
if isinstance(args, str):
|
|
401
|
+
lines.append(f" {args}")
|
|
402
|
+
elif isinstance(args, dict):
|
|
403
|
+
for arg, value in args.items():
|
|
404
|
+
lines.append(f" {arg}: {value}")
|
|
405
|
+
return lines
|
|
406
|
+
|
|
407
|
+
if self.tool_calls:
|
|
408
|
+
lines.append("Tool Calls:")
|
|
409
|
+
for tc in self.tool_calls:
|
|
410
|
+
lines.extend(_format_tool_args(tc))
|
|
411
|
+
if self.invalid_tool_calls:
|
|
412
|
+
lines.append("Invalid Tool Calls:")
|
|
413
|
+
for itc in self.invalid_tool_calls:
|
|
414
|
+
lines.extend(_format_tool_args(itc))
|
|
415
|
+
return (base.strip() + "\n" + "\n".join(lines)).strip()
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
class AIMessageChunk(AIMessage, BaseMessageChunk):
|
|
419
|
+
"""Message chunk from an AI (yielded when streaming)."""
|
|
420
|
+
|
|
421
|
+
# Ignoring mypy re-assignment here since we're overriding the value
|
|
422
|
+
# to make sure that the chunk variant can be discriminated from the
|
|
423
|
+
# non-chunk variant.
|
|
424
|
+
type: Literal["AIMessageChunk"] = "AIMessageChunk" # type: ignore[assignment]
|
|
425
|
+
"""The type of the message (used for deserialization)."""
|
|
426
|
+
|
|
427
|
+
tool_call_chunks: list[ToolCallChunk] = Field(default_factory=list)
|
|
428
|
+
"""If provided, tool call chunks associated with the message."""
|
|
429
|
+
|
|
430
|
+
chunk_position: Literal["last"] | None = None
|
|
431
|
+
"""Optional span represented by an aggregated `AIMessageChunk`.
|
|
432
|
+
|
|
433
|
+
If a chunk with `chunk_position="last"` is aggregated into a stream,
|
|
434
|
+
`tool_call_chunks` in message content will be parsed into `tool_calls`.
|
|
435
|
+
"""
|
|
436
|
+
|
|
437
|
+
@property
|
|
438
|
+
@override
|
|
439
|
+
def lc_attributes(self) -> dict[str, Any]:
|
|
440
|
+
return {
|
|
441
|
+
"tool_calls": self.tool_calls,
|
|
442
|
+
"invalid_tool_calls": self.invalid_tool_calls,
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
@property
|
|
446
|
+
def content_blocks(self) -> list[types.ContentBlock]:
|
|
447
|
+
"""Return standard, typed `ContentBlock` dicts from the message."""
|
|
448
|
+
if self.response_metadata.get("output_version") == "v1" and isinstance(
|
|
449
|
+
self.content, list
|
|
450
|
+
):
|
|
451
|
+
# Only short-circuit when content is already a list of ContentBlock
|
|
452
|
+
# dicts. Some streaming implementations keep content as a string
|
|
453
|
+
# even when output_version="v1" is set (e.g., OpenAI Chat
|
|
454
|
+
# Completions), so it must fall through to the model_provider
|
|
455
|
+
# translator which builds ContentBlock dicts from tool_calls /
|
|
456
|
+
# tool_call_chunks. Without this guard, string content would be
|
|
457
|
+
# returned directly, silently dropping tool calls.
|
|
458
|
+
return cast("list[types.ContentBlock]", self.content)
|
|
459
|
+
|
|
460
|
+
model_provider = self.response_metadata.get("model_provider")
|
|
461
|
+
if model_provider:
|
|
462
|
+
from coco_core.messages.block_translators import ( # noqa: PLC0415
|
|
463
|
+
get_translator,
|
|
464
|
+
)
|
|
465
|
+
|
|
466
|
+
translator = get_translator(model_provider)
|
|
467
|
+
if translator:
|
|
468
|
+
try:
|
|
469
|
+
return translator["translate_content_chunk"](self)
|
|
470
|
+
except NotImplementedError:
|
|
471
|
+
pass
|
|
472
|
+
|
|
473
|
+
# Otherwise, use best-effort parsing
|
|
474
|
+
blocks = super().content_blocks
|
|
475
|
+
|
|
476
|
+
if (
|
|
477
|
+
self.tool_call_chunks
|
|
478
|
+
and not self.content
|
|
479
|
+
and self.chunk_position != "last" # keep tool_calls if aggregated
|
|
480
|
+
):
|
|
481
|
+
blocks = [
|
|
482
|
+
block
|
|
483
|
+
for block in blocks
|
|
484
|
+
if block["type"] not in {"tool_call", "invalid_tool_call"}
|
|
485
|
+
]
|
|
486
|
+
for tool_call_chunk in self.tool_call_chunks:
|
|
487
|
+
tc: types.ToolCallChunk = {
|
|
488
|
+
"type": "tool_call_chunk",
|
|
489
|
+
"id": tool_call_chunk.get("id"),
|
|
490
|
+
"name": tool_call_chunk.get("name"),
|
|
491
|
+
"args": tool_call_chunk.get("args"),
|
|
492
|
+
}
|
|
493
|
+
if (idx := tool_call_chunk.get("index")) is not None:
|
|
494
|
+
tc["index"] = idx
|
|
495
|
+
blocks.append(tc)
|
|
496
|
+
|
|
497
|
+
# Best-effort reasoning extraction from additional_kwargs
|
|
498
|
+
# Only add reasoning if not already present
|
|
499
|
+
# Insert before all other blocks to keep reasoning at the start
|
|
500
|
+
has_reasoning = any(block.get("type") == "reasoning" for block in blocks)
|
|
501
|
+
if not has_reasoning and (
|
|
502
|
+
reasoning_block := _extract_reasoning_from_additional_kwargs(self)
|
|
503
|
+
):
|
|
504
|
+
blocks.insert(0, reasoning_block)
|
|
505
|
+
|
|
506
|
+
return blocks
|
|
507
|
+
|
|
508
|
+
@model_validator(mode="after")
|
|
509
|
+
def init_tool_calls(self) -> Self:
|
|
510
|
+
"""Initialize tool calls from tool call chunks.
|
|
511
|
+
|
|
512
|
+
Returns:
|
|
513
|
+
The values with tool calls initialized.
|
|
514
|
+
|
|
515
|
+
Raises:
|
|
516
|
+
ValueError: If the tool call chunks are malformed.
|
|
517
|
+
"""
|
|
518
|
+
if not self.tool_call_chunks:
|
|
519
|
+
if self.tool_calls:
|
|
520
|
+
self.tool_call_chunks = [
|
|
521
|
+
create_tool_call_chunk(
|
|
522
|
+
name=tc["name"],
|
|
523
|
+
args=json.dumps(tc["args"]),
|
|
524
|
+
id=tc["id"],
|
|
525
|
+
index=None,
|
|
526
|
+
)
|
|
527
|
+
for tc in self.tool_calls
|
|
528
|
+
]
|
|
529
|
+
if self.invalid_tool_calls:
|
|
530
|
+
tool_call_chunks = self.tool_call_chunks
|
|
531
|
+
tool_call_chunks.extend(
|
|
532
|
+
[
|
|
533
|
+
create_tool_call_chunk(
|
|
534
|
+
name=tc["name"], args=tc["args"], id=tc["id"], index=None
|
|
535
|
+
)
|
|
536
|
+
for tc in self.invalid_tool_calls
|
|
537
|
+
]
|
|
538
|
+
)
|
|
539
|
+
self.tool_call_chunks = tool_call_chunks
|
|
540
|
+
|
|
541
|
+
return self
|
|
542
|
+
tool_calls = []
|
|
543
|
+
invalid_tool_calls = []
|
|
544
|
+
|
|
545
|
+
def add_chunk_to_invalid_tool_calls(chunk: ToolCallChunk) -> None:
|
|
546
|
+
invalid_tool_calls.append(
|
|
547
|
+
create_invalid_tool_call(
|
|
548
|
+
name=chunk["name"],
|
|
549
|
+
args=chunk["args"],
|
|
550
|
+
id=chunk["id"],
|
|
551
|
+
error=None,
|
|
552
|
+
)
|
|
553
|
+
)
|
|
554
|
+
|
|
555
|
+
for chunk in self.tool_call_chunks:
|
|
556
|
+
try:
|
|
557
|
+
args_ = parse_partial_json(chunk["args"]) if chunk["args"] else {}
|
|
558
|
+
if isinstance(args_, dict):
|
|
559
|
+
tool_calls.append(
|
|
560
|
+
create_tool_call(
|
|
561
|
+
name=chunk["name"] or "",
|
|
562
|
+
args=args_,
|
|
563
|
+
id=chunk["id"],
|
|
564
|
+
)
|
|
565
|
+
)
|
|
566
|
+
else:
|
|
567
|
+
add_chunk_to_invalid_tool_calls(chunk)
|
|
568
|
+
except Exception:
|
|
569
|
+
add_chunk_to_invalid_tool_calls(chunk)
|
|
570
|
+
self.tool_calls = tool_calls
|
|
571
|
+
self.invalid_tool_calls = invalid_tool_calls
|
|
572
|
+
|
|
573
|
+
if (
|
|
574
|
+
self.chunk_position == "last"
|
|
575
|
+
and self.tool_call_chunks
|
|
576
|
+
and self.response_metadata.get("output_version") == "v1"
|
|
577
|
+
and isinstance(self.content, list)
|
|
578
|
+
):
|
|
579
|
+
id_to_tc: dict[str, types.ToolCall] = {
|
|
580
|
+
cast("str", tc.get("id")): {
|
|
581
|
+
"type": "tool_call",
|
|
582
|
+
"name": tc["name"],
|
|
583
|
+
"args": tc["args"],
|
|
584
|
+
"id": tc.get("id"),
|
|
585
|
+
}
|
|
586
|
+
for tc in self.tool_calls
|
|
587
|
+
if "id" in tc
|
|
588
|
+
}
|
|
589
|
+
for idx, block in enumerate(self.content):
|
|
590
|
+
if (
|
|
591
|
+
isinstance(block, dict)
|
|
592
|
+
and block.get("type") == "tool_call_chunk"
|
|
593
|
+
and (call_id := block.get("id"))
|
|
594
|
+
and call_id in id_to_tc
|
|
595
|
+
):
|
|
596
|
+
self.content[idx] = cast("dict[str, Any]", id_to_tc[call_id])
|
|
597
|
+
if "extras" in block:
|
|
598
|
+
# mypy does not account for instance check for dict above
|
|
599
|
+
self.content[idx]["extras"] = block["extras"] # type: ignore[index]
|
|
600
|
+
|
|
601
|
+
return self
|
|
602
|
+
|
|
603
|
+
@model_validator(mode="after")
|
|
604
|
+
def init_server_tool_calls(self) -> Self:
|
|
605
|
+
"""Initialize server tool calls.
|
|
606
|
+
|
|
607
|
+
Parse `server_tool_call_chunks` from
|
|
608
|
+
[`ServerToolCallChunk`][coco.messages.ServerToolCallChunk] objects.
|
|
609
|
+
"""
|
|
610
|
+
if (
|
|
611
|
+
self.chunk_position == "last"
|
|
612
|
+
and self.response_metadata.get("output_version") == "v1"
|
|
613
|
+
and isinstance(self.content, list)
|
|
614
|
+
):
|
|
615
|
+
for idx, block in enumerate(self.content):
|
|
616
|
+
if (
|
|
617
|
+
isinstance(block, dict)
|
|
618
|
+
and block.get("type")
|
|
619
|
+
in {"server_tool_call", "server_tool_call_chunk"}
|
|
620
|
+
and (args_str := block.get("args"))
|
|
621
|
+
and isinstance(args_str, str)
|
|
622
|
+
):
|
|
623
|
+
try:
|
|
624
|
+
args = json.loads(args_str)
|
|
625
|
+
if isinstance(args, dict):
|
|
626
|
+
self.content[idx]["type"] = "server_tool_call" # type: ignore[index]
|
|
627
|
+
self.content[idx]["args"] = args # type: ignore[index]
|
|
628
|
+
except json.JSONDecodeError:
|
|
629
|
+
pass
|
|
630
|
+
return self
|
|
631
|
+
|
|
632
|
+
@overload # type: ignore[override] # summing BaseMessages gives ChatPromptTemplate
|
|
633
|
+
def __add__(self, other: "AIMessageChunk") -> "AIMessageChunk": ...
|
|
634
|
+
|
|
635
|
+
@overload
|
|
636
|
+
def __add__(self, other: Sequence["AIMessageChunk"]) -> "AIMessageChunk": ...
|
|
637
|
+
|
|
638
|
+
@overload
|
|
639
|
+
def __add__(self, other: Any) -> BaseMessageChunk: ...
|
|
640
|
+
|
|
641
|
+
@override
|
|
642
|
+
def __add__(self, other: Any) -> BaseMessageChunk:
|
|
643
|
+
if isinstance(other, AIMessageChunk):
|
|
644
|
+
return add_ai_message_chunks(self, other)
|
|
645
|
+
if isinstance(other, (list, tuple)) and all(
|
|
646
|
+
isinstance(o, AIMessageChunk) for o in other
|
|
647
|
+
):
|
|
648
|
+
return add_ai_message_chunks(self, *other)
|
|
649
|
+
return super().__add__(other)
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
def add_ai_message_chunks(
|
|
653
|
+
left: AIMessageChunk, *others: AIMessageChunk
|
|
654
|
+
) -> AIMessageChunk:
|
|
655
|
+
"""Add multiple `AIMessageChunk`s together.
|
|
656
|
+
|
|
657
|
+
Args:
|
|
658
|
+
left: The first `AIMessageChunk`.
|
|
659
|
+
*others: Other `AIMessageChunk`s to add.
|
|
660
|
+
|
|
661
|
+
Returns:
|
|
662
|
+
The resulting `AIMessageChunk`.
|
|
663
|
+
|
|
664
|
+
"""
|
|
665
|
+
content = merge_content(left.content, *(o.content for o in others))
|
|
666
|
+
additional_kwargs = merge_dicts(
|
|
667
|
+
left.additional_kwargs, *(o.additional_kwargs for o in others)
|
|
668
|
+
)
|
|
669
|
+
response_metadata = merge_dicts(
|
|
670
|
+
left.response_metadata, *(o.response_metadata for o in others)
|
|
671
|
+
)
|
|
672
|
+
|
|
673
|
+
# Merge tool call chunks
|
|
674
|
+
if raw_tool_calls := merge_lists(
|
|
675
|
+
left.tool_call_chunks, *(o.tool_call_chunks for o in others)
|
|
676
|
+
):
|
|
677
|
+
tool_call_chunks = [
|
|
678
|
+
create_tool_call_chunk(
|
|
679
|
+
name=rtc.get("name"),
|
|
680
|
+
args=rtc.get("args"),
|
|
681
|
+
index=rtc.get("index"),
|
|
682
|
+
id=rtc.get("id"),
|
|
683
|
+
)
|
|
684
|
+
for rtc in raw_tool_calls
|
|
685
|
+
]
|
|
686
|
+
else:
|
|
687
|
+
tool_call_chunks = []
|
|
688
|
+
|
|
689
|
+
# Token usage
|
|
690
|
+
if left.usage_metadata or any(o.usage_metadata is not None for o in others):
|
|
691
|
+
usage_metadata: UsageMetadata | None = left.usage_metadata
|
|
692
|
+
for other in others:
|
|
693
|
+
usage_metadata = add_usage(usage_metadata, other.usage_metadata)
|
|
694
|
+
else:
|
|
695
|
+
usage_metadata = None
|
|
696
|
+
|
|
697
|
+
# Ranks are defined by the order of preference. Higher is better:
|
|
698
|
+
# 2. Provider-assigned IDs (non lc_* and non lc_run-*)
|
|
699
|
+
# 1. lc_run-* IDs
|
|
700
|
+
# 0. lc_* and other remaining IDs
|
|
701
|
+
best_rank = -1
|
|
702
|
+
chunk_id = None
|
|
703
|
+
candidates = itertools.chain([left.id], (o.id for o in others))
|
|
704
|
+
|
|
705
|
+
for id_ in candidates:
|
|
706
|
+
if not id_:
|
|
707
|
+
continue
|
|
708
|
+
|
|
709
|
+
if not id_.startswith(LC_ID_PREFIX) and not id_.startswith(LC_AUTO_PREFIX):
|
|
710
|
+
chunk_id = id_
|
|
711
|
+
# Highest rank, return instantly
|
|
712
|
+
break
|
|
713
|
+
|
|
714
|
+
rank = 1 if id_.startswith(LC_ID_PREFIX) else 0
|
|
715
|
+
|
|
716
|
+
if rank > best_rank:
|
|
717
|
+
best_rank = rank
|
|
718
|
+
chunk_id = id_
|
|
719
|
+
|
|
720
|
+
chunk_position: Literal["last"] | None = (
|
|
721
|
+
"last" if any(x.chunk_position == "last" for x in [left, *others]) else None
|
|
722
|
+
)
|
|
723
|
+
|
|
724
|
+
return left.__class__(
|
|
725
|
+
content=content,
|
|
726
|
+
additional_kwargs=additional_kwargs,
|
|
727
|
+
tool_call_chunks=tool_call_chunks,
|
|
728
|
+
response_metadata=response_metadata,
|
|
729
|
+
usage_metadata=usage_metadata,
|
|
730
|
+
id=chunk_id,
|
|
731
|
+
chunk_position=chunk_position,
|
|
732
|
+
)
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
def add_usage(left: UsageMetadata | None, right: UsageMetadata | None) -> UsageMetadata:
|
|
736
|
+
"""Recursively add two UsageMetadata objects.
|
|
737
|
+
|
|
738
|
+
Example:
|
|
739
|
+
```python
|
|
740
|
+
from coco_core.messages.ai import add_usage
|
|
741
|
+
|
|
742
|
+
left = UsageMetadata(
|
|
743
|
+
input_tokens=5,
|
|
744
|
+
output_tokens=0,
|
|
745
|
+
total_tokens=5,
|
|
746
|
+
input_token_details=InputTokenDetails(cache_read=3),
|
|
747
|
+
)
|
|
748
|
+
right = UsageMetadata(
|
|
749
|
+
input_tokens=0,
|
|
750
|
+
output_tokens=10,
|
|
751
|
+
total_tokens=10,
|
|
752
|
+
output_token_details=OutputTokenDetails(reasoning=4),
|
|
753
|
+
)
|
|
754
|
+
|
|
755
|
+
add_usage(left, right)
|
|
756
|
+
```
|
|
757
|
+
|
|
758
|
+
results in
|
|
759
|
+
|
|
760
|
+
```python
|
|
761
|
+
UsageMetadata(
|
|
762
|
+
input_tokens=5,
|
|
763
|
+
output_tokens=10,
|
|
764
|
+
total_tokens=15,
|
|
765
|
+
input_token_details=InputTokenDetails(cache_read=3),
|
|
766
|
+
output_token_details=OutputTokenDetails(reasoning=4),
|
|
767
|
+
)
|
|
768
|
+
```
|
|
769
|
+
Args:
|
|
770
|
+
left: The first `UsageMetadata` object.
|
|
771
|
+
right: The second `UsageMetadata` object.
|
|
772
|
+
|
|
773
|
+
Returns:
|
|
774
|
+
The sum of the two `UsageMetadata` objects.
|
|
775
|
+
|
|
776
|
+
"""
|
|
777
|
+
if not (left or right):
|
|
778
|
+
return UsageMetadata(input_tokens=0, output_tokens=0, total_tokens=0)
|
|
779
|
+
if not (left and right):
|
|
780
|
+
return cast("UsageMetadata", left or right)
|
|
781
|
+
|
|
782
|
+
return UsageMetadata(
|
|
783
|
+
**cast(
|
|
784
|
+
"UsageMetadata",
|
|
785
|
+
_dict_int_op(
|
|
786
|
+
cast("dict[str, Any]", left),
|
|
787
|
+
cast("dict[str, Any]", right),
|
|
788
|
+
operator.add,
|
|
789
|
+
),
|
|
790
|
+
)
|
|
791
|
+
)
|
|
792
|
+
|
|
793
|
+
|
|
794
|
+
def subtract_usage(
|
|
795
|
+
left: UsageMetadata | None, right: UsageMetadata | None
|
|
796
|
+
) -> UsageMetadata:
|
|
797
|
+
"""Recursively subtract two `UsageMetadata` objects.
|
|
798
|
+
|
|
799
|
+
Token counts cannot be negative so the actual operation is `max(left - right, 0)`.
|
|
800
|
+
|
|
801
|
+
Example:
|
|
802
|
+
```python
|
|
803
|
+
from coco_core.messages.ai import subtract_usage
|
|
804
|
+
|
|
805
|
+
left = UsageMetadata(
|
|
806
|
+
input_tokens=5,
|
|
807
|
+
output_tokens=10,
|
|
808
|
+
total_tokens=15,
|
|
809
|
+
input_token_details=InputTokenDetails(cache_read=4),
|
|
810
|
+
)
|
|
811
|
+
right = UsageMetadata(
|
|
812
|
+
input_tokens=3,
|
|
813
|
+
output_tokens=8,
|
|
814
|
+
total_tokens=11,
|
|
815
|
+
output_token_details=OutputTokenDetails(reasoning=4),
|
|
816
|
+
)
|
|
817
|
+
|
|
818
|
+
subtract_usage(left, right)
|
|
819
|
+
```
|
|
820
|
+
|
|
821
|
+
results in
|
|
822
|
+
|
|
823
|
+
```python
|
|
824
|
+
UsageMetadata(
|
|
825
|
+
input_tokens=2,
|
|
826
|
+
output_tokens=2,
|
|
827
|
+
total_tokens=4,
|
|
828
|
+
input_token_details=InputTokenDetails(cache_read=4),
|
|
829
|
+
output_token_details=OutputTokenDetails(reasoning=0),
|
|
830
|
+
)
|
|
831
|
+
```
|
|
832
|
+
Args:
|
|
833
|
+
left: The first `UsageMetadata` object.
|
|
834
|
+
right: The second `UsageMetadata` object.
|
|
835
|
+
|
|
836
|
+
Returns:
|
|
837
|
+
The resulting `UsageMetadata` after subtraction.
|
|
838
|
+
|
|
839
|
+
"""
|
|
840
|
+
if not (left or right):
|
|
841
|
+
return UsageMetadata(input_tokens=0, output_tokens=0, total_tokens=0)
|
|
842
|
+
if not (left and right):
|
|
843
|
+
return cast("UsageMetadata", left or right)
|
|
844
|
+
|
|
845
|
+
return UsageMetadata(
|
|
846
|
+
**cast(
|
|
847
|
+
"UsageMetadata",
|
|
848
|
+
_dict_int_op(
|
|
849
|
+
cast("dict[str, Any]", left),
|
|
850
|
+
cast("dict[str, Any]", right),
|
|
851
|
+
(lambda le, ri: max(le - ri, 0)),
|
|
852
|
+
),
|
|
853
|
+
)
|
|
854
|
+
)
|