@nhtio/adk 1.20260607.2 → 1.20260609.1
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.
- package/CHANGELOG.md +230 -0
- package/batteries/embeddings/openai/adapter.cjs +1 -1
- package/batteries/embeddings/openai/adapter.mjs +1 -1
- package/batteries/embeddings/openai/exceptions.cjs +1 -1
- package/batteries/embeddings/openai/exceptions.mjs +1 -1
- package/batteries/embeddings/openai/types.d.ts +7 -0
- package/batteries/embeddings/webllm/adapter.cjs +1 -1
- package/batteries/embeddings/webllm/adapter.mjs +1 -1
- package/batteries/embeddings/webllm/exceptions.cjs +1 -1
- package/batteries/embeddings/webllm/exceptions.mjs +1 -1
- package/batteries/llm/chat_common/helpers.d.ts +165 -0
- package/batteries/llm/chat_common/types.d.ts +309 -0
- package/batteries/llm/index.d.ts +5 -0
- package/batteries/llm/ollama/adapter.cjs +736 -0
- package/batteries/llm/ollama/adapter.cjs.map +1 -0
- package/batteries/llm/ollama/adapter.d.ts +64 -0
- package/batteries/llm/ollama/adapter.mjs +734 -0
- package/batteries/llm/ollama/adapter.mjs.map +1 -0
- package/batteries/llm/ollama/exceptions.cjs +105 -0
- package/batteries/llm/ollama/exceptions.cjs.map +1 -0
- package/batteries/llm/ollama/exceptions.d.ts +112 -0
- package/batteries/llm/ollama/exceptions.mjs +96 -0
- package/batteries/llm/ollama/exceptions.mjs.map +1 -0
- package/batteries/llm/ollama/helpers.cjs +487 -0
- package/batteries/llm/ollama/helpers.cjs.map +1 -0
- package/batteries/llm/ollama/helpers.d.ts +158 -0
- package/batteries/llm/ollama/helpers.mjs +450 -0
- package/batteries/llm/ollama/helpers.mjs.map +1 -0
- package/batteries/llm/ollama/index.d.ts +29 -0
- package/batteries/llm/ollama/types.cjs +2 -0
- package/batteries/llm/ollama/types.d.ts +334 -0
- package/batteries/llm/ollama/types.mjs +0 -0
- package/batteries/llm/ollama/validation.cjs +130 -0
- package/batteries/llm/ollama/validation.cjs.map +1 -0
- package/batteries/llm/ollama/validation.d.ts +31 -0
- package/batteries/llm/ollama/validation.mjs +127 -0
- package/batteries/llm/ollama/validation.mjs.map +1 -0
- package/batteries/llm/ollama.cjs +54 -0
- package/batteries/llm/ollama.mjs +6 -0
- package/batteries/llm/openai_chat_completions/adapter.cjs +36 -19
- package/batteries/llm/openai_chat_completions/adapter.cjs.map +1 -1
- package/batteries/llm/openai_chat_completions/adapter.mjs +23 -6
- package/batteries/llm/openai_chat_completions/adapter.mjs.map +1 -1
- package/batteries/llm/openai_chat_completions/exceptions.cjs +1 -1
- package/batteries/llm/openai_chat_completions/exceptions.mjs +1 -1
- package/batteries/llm/openai_chat_completions/helpers.cjs +80 -320
- package/batteries/llm/openai_chat_completions/helpers.cjs.map +1 -1
- package/batteries/llm/openai_chat_completions/helpers.d.ts +68 -144
- package/batteries/llm/openai_chat_completions/helpers.mjs +40 -280
- package/batteries/llm/openai_chat_completions/helpers.mjs.map +1 -1
- package/batteries/llm/openai_chat_completions/types.d.ts +273 -181
- package/batteries/llm/openai_chat_completions/validation.cjs +2 -2
- package/batteries/llm/openai_chat_completions/validation.cjs.map +1 -1
- package/batteries/llm/openai_chat_completions/validation.mjs +2 -2
- package/batteries/llm/openai_chat_completions/validation.mjs.map +1 -1
- package/batteries/llm/openai_chat_completions.cjs +29 -28
- package/batteries/llm/openai_chat_completions.mjs +2 -1
- package/batteries/llm/webllm_chat_completions/adapter.cjs +38 -19
- package/batteries/llm/webllm_chat_completions/adapter.cjs.map +1 -1
- package/batteries/llm/webllm_chat_completions/adapter.d.ts +18 -0
- package/batteries/llm/webllm_chat_completions/adapter.mjs +25 -6
- package/batteries/llm/webllm_chat_completions/adapter.mjs.map +1 -1
- package/batteries/llm/webllm_chat_completions/exceptions.cjs +1 -1
- package/batteries/llm/webllm_chat_completions/exceptions.mjs +1 -1
- package/batteries/llm/webllm_chat_completions/helpers.cjs +29 -28
- package/batteries/llm/webllm_chat_completions/helpers.mjs +2 -1
- package/batteries/llm/webllm_chat_completions/types.d.ts +21 -0
- package/batteries/llm/webllm_chat_completions/validation.cjs +13 -1
- package/batteries/llm/webllm_chat_completions/validation.cjs.map +1 -1
- package/batteries/llm/webllm_chat_completions/validation.d.ts +12 -0
- package/batteries/llm/webllm_chat_completions/validation.mjs +13 -1
- package/batteries/llm/webllm_chat_completions/validation.mjs.map +1 -1
- package/batteries/llm/webllm_chat_completions.cjs +29 -28
- package/batteries/llm/webllm_chat_completions.mjs +2 -1
- package/batteries/llm.cjs +44 -28
- package/batteries/llm.mjs +9 -4
- package/batteries/storage/flydrive.cjs +1 -1
- package/batteries/storage/flydrive.mjs +1 -1
- package/batteries/storage/in_memory/index.d.ts +1 -1
- package/batteries/storage/in_memory.cjs +2 -2
- package/batteries/storage/in_memory.cjs.map +1 -1
- package/batteries/storage/in_memory.mjs +2 -2
- package/batteries/storage/in_memory.mjs.map +1 -1
- package/batteries/storage/opfs/index.d.ts +19 -0
- package/batteries/storage/opfs.cjs +1 -1
- package/batteries/storage/opfs.cjs.map +1 -1
- package/batteries/storage/opfs.mjs +1 -1
- package/batteries/storage/opfs.mjs.map +1 -1
- package/batteries/tools/_shared/index.d.ts +121 -0
- package/batteries/tools/_shared.cjs +157 -0
- package/batteries/tools/_shared.cjs.map +1 -0
- package/batteries/tools/_shared.mjs +149 -0
- package/batteries/tools/_shared.mjs.map +1 -0
- package/batteries/tools/color.cjs +3 -2
- package/batteries/tools/color.cjs.map +1 -1
- package/batteries/tools/color.mjs +3 -2
- package/batteries/tools/color.mjs.map +1 -1
- package/batteries/tools/comparison.cjs +4 -3
- package/batteries/tools/comparison.cjs.map +1 -1
- package/batteries/tools/comparison.mjs +4 -3
- package/batteries/tools/comparison.mjs.map +1 -1
- package/batteries/tools/data_structure.cjs +30 -10
- package/batteries/tools/data_structure.cjs.map +1 -1
- package/batteries/tools/data_structure.mjs +30 -10
- package/batteries/tools/data_structure.mjs.map +1 -1
- package/batteries/tools/datetime_extended.cjs +5 -10
- package/batteries/tools/datetime_extended.cjs.map +1 -1
- package/batteries/tools/datetime_extended.mjs +5 -10
- package/batteries/tools/datetime_extended.mjs.map +1 -1
- package/batteries/tools/datetime_math.cjs +2 -2
- package/batteries/tools/datetime_math.mjs +2 -2
- package/batteries/tools/encoding.cjs +13 -4
- package/batteries/tools/encoding.cjs.map +1 -1
- package/batteries/tools/encoding.mjs +13 -4
- package/batteries/tools/encoding.mjs.map +1 -1
- package/batteries/tools/formatting.cjs +4 -4
- package/batteries/tools/formatting.cjs.map +1 -1
- package/batteries/tools/formatting.mjs +4 -4
- package/batteries/tools/formatting.mjs.map +1 -1
- package/batteries/tools/geo_basics.cjs +2 -2
- package/batteries/tools/geo_basics.mjs +2 -2
- package/batteries/tools/index.d.ts +3 -0
- package/batteries/tools/math.cjs +10 -8
- package/batteries/tools/math.cjs.map +1 -1
- package/batteries/tools/math.mjs +10 -8
- package/batteries/tools/math.mjs.map +1 -1
- package/batteries/tools/memory.cjs +5 -5
- package/batteries/tools/memory.mjs +5 -5
- package/batteries/tools/parsing.cjs +9 -5
- package/batteries/tools/parsing.cjs.map +1 -1
- package/batteries/tools/parsing.mjs +9 -5
- package/batteries/tools/parsing.mjs.map +1 -1
- package/batteries/tools/retrievables.cjs +4 -4
- package/batteries/tools/retrievables.mjs +4 -4
- package/batteries/tools/scrapper/exceptions.d.ts +21 -0
- package/batteries/tools/scrapper/index.d.ts +172 -0
- package/batteries/tools/scrapper/shared.d.ts +139 -0
- package/batteries/tools/scrapper.cjs +8 -0
- package/batteries/tools/scrapper.mjs +2 -0
- package/batteries/tools/searxng/exceptions.d.ts +21 -0
- package/batteries/tools/searxng/index.d.ts +177 -0
- package/batteries/tools/searxng.cjs +6 -0
- package/batteries/tools/searxng.mjs +2 -0
- package/batteries/tools/standing_instructions.cjs +4 -4
- package/batteries/tools/standing_instructions.mjs +4 -4
- package/batteries/tools/statistics.cjs +54 -43
- package/batteries/tools/statistics.cjs.map +1 -1
- package/batteries/tools/statistics.mjs +54 -43
- package/batteries/tools/statistics.mjs.map +1 -1
- package/batteries/tools/string_processing.cjs +5 -5
- package/batteries/tools/string_processing.cjs.map +1 -1
- package/batteries/tools/string_processing.mjs +5 -5
- package/batteries/tools/string_processing.mjs.map +1 -1
- package/batteries/tools/structured_data.cjs +8 -13
- package/batteries/tools/structured_data.cjs.map +1 -1
- package/batteries/tools/structured_data.mjs +8 -13
- package/batteries/tools/structured_data.mjs.map +1 -1
- package/batteries/tools/text_analysis.cjs +3 -3
- package/batteries/tools/text_analysis.mjs +3 -3
- package/batteries/tools/text_comparison.cjs +2 -2
- package/batteries/tools/text_comparison.mjs +2 -2
- package/batteries/tools/time.cjs +2 -2
- package/batteries/tools/time.mjs +2 -2
- package/batteries/tools/unit_conversion.cjs +10 -8
- package/batteries/tools/unit_conversion.cjs.map +1 -1
- package/batteries/tools/unit_conversion.mjs +10 -8
- package/batteries/tools/unit_conversion.mjs.map +1 -1
- package/batteries/tools/web_retrieval/index.d.ts +186 -0
- package/batteries/tools/web_retrieval.cjs +206 -0
- package/batteries/tools/web_retrieval.cjs.map +1 -0
- package/batteries/tools/web_retrieval.mjs +201 -0
- package/batteries/tools/web_retrieval.mjs.map +1 -0
- package/batteries/tools.cjs +15 -0
- package/batteries/tools.mjs +4 -1
- package/batteries/vector/arangodb/index.d.ts +2 -0
- package/batteries/vector/arangodb.cjs +2 -1
- package/batteries/vector/arangodb.cjs.map +1 -1
- package/batteries/vector/arangodb.mjs +2 -1
- package/batteries/vector/arangodb.mjs.map +1 -1
- package/batteries/vector/builder.cjs +31 -0
- package/batteries/vector/builder.cjs.map +1 -1
- package/batteries/vector/builder.d.ts +58 -0
- package/batteries/vector/builder.mjs +31 -0
- package/batteries/vector/builder.mjs.map +1 -1
- package/batteries/vector/chroma/index.d.ts +4 -0
- package/batteries/vector/chroma.cjs +3 -0
- package/batteries/vector/chroma.cjs.map +1 -1
- package/batteries/vector/chroma.mjs +3 -0
- package/batteries/vector/chroma.mjs.map +1 -1
- package/batteries/vector/clickhouse/index.d.ts +2 -0
- package/batteries/vector/clickhouse.cjs +2 -1
- package/batteries/vector/clickhouse.cjs.map +1 -1
- package/batteries/vector/clickhouse.mjs +2 -1
- package/batteries/vector/clickhouse.mjs.map +1 -1
- package/batteries/vector/cloudflare/index.d.ts +2 -0
- package/batteries/vector/cloudflare.cjs +2 -1
- package/batteries/vector/cloudflare.cjs.map +1 -1
- package/batteries/vector/cloudflare.mjs +2 -1
- package/batteries/vector/cloudflare.mjs.map +1 -1
- package/batteries/vector/conformance/index.d.ts +22 -0
- package/batteries/vector/conformance.cjs +22 -0
- package/batteries/vector/conformance.cjs.map +1 -1
- package/batteries/vector/conformance.mjs +22 -0
- package/batteries/vector/conformance.mjs.map +1 -1
- package/batteries/vector/contract.cjs +22 -0
- package/batteries/vector/contract.cjs.map +1 -1
- package/batteries/vector/contract.d.ts +51 -0
- package/batteries/vector/contract.mjs +22 -0
- package/batteries/vector/contract.mjs.map +1 -1
- package/batteries/vector/couchbase/index.d.ts +2 -0
- package/batteries/vector/couchbase.cjs +2 -1
- package/batteries/vector/couchbase.cjs.map +1 -1
- package/batteries/vector/couchbase.mjs +2 -1
- package/batteries/vector/couchbase.mjs.map +1 -1
- package/batteries/vector/duckdb/index.d.ts +2 -0
- package/batteries/vector/duckdb.cjs +2 -1
- package/batteries/vector/duckdb.cjs.map +1 -1
- package/batteries/vector/duckdb.mjs +2 -1
- package/batteries/vector/duckdb.mjs.map +1 -1
- package/batteries/vector/elasticsearch/index.d.ts +2 -0
- package/batteries/vector/elasticsearch.cjs +2 -1
- package/batteries/vector/elasticsearch.cjs.map +1 -1
- package/batteries/vector/elasticsearch.mjs +2 -1
- package/batteries/vector/elasticsearch.mjs.map +1 -1
- package/batteries/vector/exceptions.cjs +1 -1
- package/batteries/vector/exceptions.mjs +1 -1
- package/batteries/vector/factory.cjs +6 -0
- package/batteries/vector/factory.cjs.map +1 -1
- package/batteries/vector/factory.d.ts +14 -0
- package/batteries/vector/factory.mjs +6 -0
- package/batteries/vector/factory.mjs.map +1 -1
- package/batteries/vector/filters.cjs +22 -1
- package/batteries/vector/filters.cjs.map +1 -1
- package/batteries/vector/filters.d.ts +38 -0
- package/batteries/vector/filters.mjs +22 -1
- package/batteries/vector/filters.mjs.map +1 -1
- package/batteries/vector/helpers.cjs +13 -0
- package/batteries/vector/helpers.cjs.map +1 -1
- package/batteries/vector/helpers.d.ts +14 -0
- package/batteries/vector/helpers.mjs +13 -0
- package/batteries/vector/helpers.mjs.map +1 -1
- package/batteries/vector/hnswlib/index.d.ts +2 -0
- package/batteries/vector/hnswlib.cjs +2 -1
- package/batteries/vector/hnswlib.cjs.map +1 -1
- package/batteries/vector/hnswlib.mjs +2 -1
- package/batteries/vector/hnswlib.mjs.map +1 -1
- package/batteries/vector/in_memory/index.d.ts +1 -0
- package/batteries/vector/in_memory.cjs +1 -0
- package/batteries/vector/in_memory.cjs.map +1 -1
- package/batteries/vector/in_memory.mjs +1 -0
- package/batteries/vector/in_memory.mjs.map +1 -1
- package/batteries/vector/lancedb/index.d.ts +2 -0
- package/batteries/vector/lancedb.cjs +2 -1
- package/batteries/vector/lancedb.cjs.map +1 -1
- package/batteries/vector/lancedb.mjs +2 -1
- package/batteries/vector/lancedb.mjs.map +1 -1
- package/batteries/vector/mariadb/index.d.ts +2 -0
- package/batteries/vector/mariadb.cjs +2 -1
- package/batteries/vector/mariadb.cjs.map +1 -1
- package/batteries/vector/mariadb.mjs +2 -1
- package/batteries/vector/mariadb.mjs.map +1 -1
- package/batteries/vector/meilisearch/index.d.ts +2 -0
- package/batteries/vector/meilisearch.cjs +2 -1
- package/batteries/vector/meilisearch.cjs.map +1 -1
- package/batteries/vector/meilisearch.mjs +2 -1
- package/batteries/vector/meilisearch.mjs.map +1 -1
- package/batteries/vector/migrate.cjs +18 -1
- package/batteries/vector/migrate.cjs.map +1 -1
- package/batteries/vector/migrate.d.ts +31 -0
- package/batteries/vector/migrate.mjs +18 -1
- package/batteries/vector/migrate.mjs.map +1 -1
- package/batteries/vector/milvus/index.d.ts +5 -0
- package/batteries/vector/milvus.cjs +4 -0
- package/batteries/vector/milvus.cjs.map +1 -1
- package/batteries/vector/milvus.mjs +4 -0
- package/batteries/vector/milvus.mjs.map +1 -1
- package/batteries/vector/mongodb/index.d.ts +2 -0
- package/batteries/vector/mongodb.cjs +2 -1
- package/batteries/vector/mongodb.cjs.map +1 -1
- package/batteries/vector/mongodb.mjs +2 -1
- package/batteries/vector/mongodb.mjs.map +1 -1
- package/batteries/vector/neo4j/index.d.ts +2 -0
- package/batteries/vector/neo4j.cjs +2 -1
- package/batteries/vector/neo4j.cjs.map +1 -1
- package/batteries/vector/neo4j.mjs +2 -1
- package/batteries/vector/neo4j.mjs.map +1 -1
- package/batteries/vector/opensearch/index.d.ts +2 -0
- package/batteries/vector/opensearch.cjs +2 -1
- package/batteries/vector/opensearch.cjs.map +1 -1
- package/batteries/vector/opensearch.mjs +2 -1
- package/batteries/vector/opensearch.mjs.map +1 -1
- package/batteries/vector/oracle23ai/index.d.ts +2 -0
- package/batteries/vector/oracle23ai.cjs +2 -1
- package/batteries/vector/oracle23ai.cjs.map +1 -1
- package/batteries/vector/oracle23ai.mjs +2 -1
- package/batteries/vector/oracle23ai.mjs.map +1 -1
- package/batteries/vector/orama/index.d.ts +1 -0
- package/batteries/vector/orama.cjs +1 -0
- package/batteries/vector/orama.cjs.map +1 -1
- package/batteries/vector/orama.mjs +1 -0
- package/batteries/vector/orama.mjs.map +1 -1
- package/batteries/vector/pgvector/index.d.ts +9 -2
- package/batteries/vector/pgvector.cjs +4 -0
- package/batteries/vector/pgvector.cjs.map +1 -1
- package/batteries/vector/pgvector.mjs +4 -0
- package/batteries/vector/pgvector.mjs.map +1 -1
- package/batteries/vector/pinecone/index.d.ts +5 -0
- package/batteries/vector/pinecone.cjs +3 -1
- package/batteries/vector/pinecone.cjs.map +1 -1
- package/batteries/vector/pinecone.mjs +3 -1
- package/batteries/vector/pinecone.mjs.map +1 -1
- package/batteries/vector/plan.d.ts +27 -0
- package/batteries/vector/qdrant/index.d.ts +5 -0
- package/batteries/vector/qdrant.cjs +4 -0
- package/batteries/vector/qdrant.cjs.map +1 -1
- package/batteries/vector/qdrant.mjs +4 -0
- package/batteries/vector/qdrant.mjs.map +1 -1
- package/batteries/vector/redis/index.d.ts +2 -0
- package/batteries/vector/redis.cjs +2 -1
- package/batteries/vector/redis.cjs.map +1 -1
- package/batteries/vector/redis.mjs +2 -1
- package/batteries/vector/redis.mjs.map +1 -1
- package/batteries/vector/retrievable.cjs +9 -1
- package/batteries/vector/retrievable.cjs.map +1 -1
- package/batteries/vector/retrievable.mjs +9 -1
- package/batteries/vector/retrievable.mjs.map +1 -1
- package/batteries/vector/retrievable_glue.d.ts +21 -0
- package/batteries/vector/s3vectors/index.d.ts +2 -0
- package/batteries/vector/s3vectors.cjs +2 -1
- package/batteries/vector/s3vectors.cjs.map +1 -1
- package/batteries/vector/s3vectors.mjs +2 -1
- package/batteries/vector/s3vectors.mjs.map +1 -1
- package/batteries/vector/schema.cjs +28 -0
- package/batteries/vector/schema.cjs.map +1 -1
- package/batteries/vector/schema.d.ts +39 -0
- package/batteries/vector/schema.mjs +28 -0
- package/batteries/vector/schema.mjs.map +1 -1
- package/batteries/vector/solr/index.d.ts +2 -0
- package/batteries/vector/solr.cjs +2 -1
- package/batteries/vector/solr.cjs.map +1 -1
- package/batteries/vector/solr.mjs +2 -1
- package/batteries/vector/solr.mjs.map +1 -1
- package/batteries/vector/sqlite_vec/index.d.ts +6 -3
- package/batteries/vector/sqlite_vec.cjs +2 -0
- package/batteries/vector/sqlite_vec.cjs.map +1 -1
- package/batteries/vector/sqlite_vec.mjs +2 -0
- package/batteries/vector/sqlite_vec.mjs.map +1 -1
- package/batteries/vector/surrealdb/index.d.ts +2 -0
- package/batteries/vector/surrealdb.cjs +2 -1
- package/batteries/vector/surrealdb.cjs.map +1 -1
- package/batteries/vector/surrealdb.mjs +2 -1
- package/batteries/vector/surrealdb.mjs.map +1 -1
- package/batteries/vector/types.d.ts +27 -0
- package/batteries/vector/typesense/index.d.ts +2 -0
- package/batteries/vector/typesense.cjs +2 -1
- package/batteries/vector/typesense.cjs.map +1 -1
- package/batteries/vector/typesense.mjs +2 -1
- package/batteries/vector/typesense.mjs.map +1 -1
- package/batteries/vector/validation.cjs +14 -0
- package/batteries/vector/validation.cjs.map +1 -1
- package/batteries/vector/validation.d.ts +14 -0
- package/batteries/vector/validation.mjs +14 -0
- package/batteries/vector/validation.mjs.map +1 -1
- package/batteries/vector/vector_store_constructor.cjs +1 -1
- package/batteries/vector/vector_store_constructor.cjs.map +1 -1
- package/batteries/vector/vector_store_constructor.d.ts +1 -1
- package/batteries/vector/vector_store_constructor.mjs +1 -1
- package/batteries/vector/vector_store_constructor.mjs.map +1 -1
- package/batteries/vector/vespa/index.d.ts +2 -0
- package/batteries/vector/vespa.cjs +2 -1
- package/batteries/vector/vespa.cjs.map +1 -1
- package/batteries/vector/vespa.mjs +2 -1
- package/batteries/vector/vespa.mjs.map +1 -1
- package/batteries/vector/weaviate/index.d.ts +2 -0
- package/batteries/vector/weaviate.cjs +2 -1
- package/batteries/vector/weaviate.cjs.map +1 -1
- package/batteries/vector/weaviate.mjs +2 -1
- package/batteries/vector/weaviate.mjs.map +1 -1
- package/batteries.cjs +58 -28
- package/batteries.mjs +12 -5
- package/{common-BT0nfCi9.mjs → common-DYDUi99O.mjs} +9 -9
- package/common-DYDUi99O.mjs.map +1 -0
- package/{common-Cj8TaQ9U.js → common-DZl3ADJs.js} +9 -9
- package/common-DZl3ADJs.js.map +1 -0
- package/common.cjs +7 -7
- package/common.mjs +7 -7
- package/{dispatch_runner-DPcS7Y_M.mjs → dispatch_runner--ZhdDWRZ.mjs} +27 -5
- package/{dispatch_runner-DPcS7Y_M.mjs.map → dispatch_runner--ZhdDWRZ.mjs.map} +1 -1
- package/{dispatch_runner-BHBNupqp.js → dispatch_runner-nHDKkxye.js} +27 -5
- package/{dispatch_runner-BHBNupqp.js.map → dispatch_runner-nHDKkxye.js.map} +1 -1
- package/dispatch_runner.cjs +1 -1
- package/dispatch_runner.d.ts +1 -1
- package/dispatch_runner.mjs +1 -1
- package/eslint/rules/artifact_tool_forbids_artifact_constructor.cjs +1 -0
- package/eslint/rules/artifact_tool_forbids_artifact_constructor.cjs.map +1 -1
- package/eslint/rules/artifact_tool_forbids_artifact_constructor.d.ts +1 -0
- package/eslint/rules/artifact_tool_forbids_artifact_constructor.mjs +1 -0
- package/eslint/rules/artifact_tool_forbids_artifact_constructor.mjs.map +1 -1
- package/eslint/rules/no_model_in_tool_handler.cjs +1 -0
- package/eslint/rules/no_model_in_tool_handler.cjs.map +1 -1
- package/eslint/rules/no_model_in_tool_handler.d.ts +1 -0
- package/eslint/rules/no_model_in_tool_handler.mjs +1 -0
- package/eslint/rules/no_model_in_tool_handler.mjs.map +1 -1
- package/eslint/rules/require_validator_any_required.cjs +1 -0
- package/eslint/rules/require_validator_any_required.cjs.map +1 -1
- package/eslint/rules/require_validator_any_required.d.ts +1 -0
- package/eslint/rules/require_validator_any_required.mjs +1 -0
- package/eslint/rules/require_validator_any_required.mjs.map +1 -1
- package/eslint/rules/thought_payload_requires_replay_tag.cjs +1 -0
- package/eslint/rules/thought_payload_requires_replay_tag.cjs.map +1 -1
- package/eslint/rules/thought_payload_requires_replay_tag.d.ts +1 -0
- package/eslint/rules/thought_payload_requires_replay_tag.mjs +1 -0
- package/eslint/rules/thought_payload_requires_replay_tag.mjs.map +1 -1
- package/eslint/rules/token_encoding_requires_context_window.cjs +1 -0
- package/eslint/rules/token_encoding_requires_context_window.cjs.map +1 -1
- package/eslint/rules/token_encoding_requires_context_window.d.ts +1 -0
- package/eslint/rules/token_encoding_requires_context_window.mjs +1 -0
- package/eslint/rules/token_encoding_requires_context_window.mjs.map +1 -1
- package/eslint/rules.cjs +1 -1
- package/eslint/rules.mjs +1 -1
- package/eslint.cjs +2 -2
- package/eslint.mjs +2 -2
- package/{exceptions-BeWH2FwP.mjs → exceptions-BDhN0Xzr.mjs} +3 -2
- package/exceptions-BDhN0Xzr.mjs.map +1 -0
- package/{exceptions-CitH5wZI.js → exceptions-BRXrUKiW.js} +3 -2
- package/exceptions-BRXrUKiW.js.map +1 -0
- package/exceptions.cjs +2 -2
- package/exceptions.mjs +2 -2
- package/factories.cjs +1 -1
- package/factories.mjs +1 -1
- package/forge.cjs +4 -4
- package/forge.d.ts +1 -1
- package/forge.mjs +4 -4
- package/guards.cjs +9 -9
- package/guards.mjs +9 -9
- package/helpers-DSTFxTiC.js +497 -0
- package/helpers-DSTFxTiC.js.map +1 -0
- package/helpers-xhrQbMAG.mjs +306 -0
- package/helpers-xhrQbMAG.mjs.map +1 -0
- package/index.cjs +12 -12
- package/index.mjs +12 -12
- package/lib/classes/base_exception.d.ts +1 -0
- package/lib/classes/media.d.ts +10 -0
- package/lib/classes/retrievable.d.ts +1 -1
- package/lib/classes/spooled_json_artifact.d.ts +1 -1
- package/lib/classes/spooled_markdown_artifact.d.ts +1 -0
- package/lib/classes/tokenizable.d.ts +3 -0
- package/lib/classes/tool.d.ts +8 -0
- package/lib/classes/turn_gate.d.ts +6 -0
- package/lib/dispatch_runner.d.ts +4 -32
- package/lib/helpers/bignum.cjs +82 -0
- package/lib/helpers/bignum.cjs.map +1 -0
- package/lib/helpers/bignum.d.ts +52 -0
- package/lib/helpers/bignum.mjs +74 -0
- package/lib/helpers/bignum.mjs.map +1 -0
- package/lib/turn_runner.d.ts +1 -1
- package/lib/types/dispatch_runner.d.ts +83 -0
- package/lib/utils/exceptions.d.ts +1 -1
- package/lib/utils/retry.cjs.map +1 -1
- package/lib/utils/retry.d.ts +2 -0
- package/lib/utils/retry.mjs.map +1 -1
- package/mcp/adk-docs-corpus.json +1 -1
- package/package.json +259 -204
- package/{runtime-j92CNi5z.mjs → runtime-Bz5zA8wc.mjs} +2 -2
- package/{runtime-j92CNi5z.mjs.map → runtime-Bz5zA8wc.mjs.map} +1 -1
- package/{runtime-MFFcJrRv.js → runtime-DslE1aBw.js} +2 -2
- package/{runtime-MFFcJrRv.js.map → runtime-DslE1aBw.js.map} +1 -1
- package/scrapper-BHM1mCde.mjs +432 -0
- package/scrapper-BHM1mCde.mjs.map +1 -0
- package/scrapper-BeweWurk.js +462 -0
- package/scrapper-BeweWurk.js.map +1 -0
- package/searxng-BJFulNcK.mjs +247 -0
- package/searxng-BJFulNcK.mjs.map +1 -0
- package/searxng-B_D--V5q.js +265 -0
- package/searxng-B_D--V5q.js.map +1 -0
- package/skills/adk-assembly/SKILL.md +2 -2
- package/{spooled_artifact-CHoZgWwI.mjs → spooled_artifact-7eePq7JA.mjs} +5 -5
- package/{spooled_artifact-CHoZgWwI.mjs.map → spooled_artifact-7eePq7JA.mjs.map} +1 -1
- package/{spooled_artifact-BTq6Nzfy.js → spooled_artifact-DX8LLyUX.js} +5 -5
- package/{spooled_artifact-BTq6Nzfy.js.map → spooled_artifact-DX8LLyUX.js.map} +1 -1
- package/spooled_artifact.cjs +2 -2
- package/spooled_artifact.mjs +2 -2
- package/{spooled_markdown_artifact-CALSDxIx.js → spooled_markdown_artifact-ClX72lek.js} +4 -4
- package/spooled_markdown_artifact-ClX72lek.js.map +1 -0
- package/{spooled_markdown_artifact-Ci5UL7l4.mjs → spooled_markdown_artifact-wkrBF3oX.mjs} +4 -4
- package/spooled_markdown_artifact-wkrBF3oX.mjs.map +1 -0
- package/{thought-D34QQZZ9.mjs → thought-B_vxAiKU.mjs} +5 -5
- package/{thought-D34QQZZ9.mjs.map → thought-B_vxAiKU.mjs.map} +1 -1
- package/{thought-BbwhJ1wb.js → thought-DLwpF7MI.js} +5 -5
- package/{thought-BbwhJ1wb.js.map → thought-DLwpF7MI.js.map} +1 -1
- package/{tool-CVyZkFC7.js → tool-D5WGVIcI.js} +4 -4
- package/{tool-CVyZkFC7.js.map → tool-D5WGVIcI.js.map} +1 -1
- package/{tool-CMhaDRNd.mjs → tool-wMYMVl60.mjs} +4 -4
- package/{tool-CMhaDRNd.mjs.map → tool-wMYMVl60.mjs.map} +1 -1
- package/{tool_call-CV5qVNlb.mjs → tool_call-B4-_-vjG.mjs} +5 -5
- package/tool_call-B4-_-vjG.mjs.map +1 -0
- package/{tool_call-Db68hB7y.js → tool_call-DixVlW40.js} +5 -5
- package/tool_call-DixVlW40.js.map +1 -0
- package/{tool_registry-D1pSSlsd.mjs → tool_registry-791Vrjtf.mjs} +4 -3
- package/tool_registry-791Vrjtf.mjs.map +1 -0
- package/{tool_registry-DYUYqXvo.js → tool_registry-CKJPze3j.js} +4 -3
- package/tool_registry-CKJPze3j.js.map +1 -0
- package/{turn_runner-DqWHNP80.js → turn_runner-HXImLGIn.js} +7 -7
- package/turn_runner-HXImLGIn.js.map +1 -0
- package/{turn_runner-fg1Wc3dK.mjs → turn_runner-ZyYO-Kti.mjs} +7 -7
- package/turn_runner-ZyYO-Kti.mjs.map +1 -0
- package/turn_runner.cjs +1 -1
- package/turn_runner.mjs +1 -1
- package/types.d.ts +1 -1
- package/common-BT0nfCi9.mjs.map +0 -1
- package/common-Cj8TaQ9U.js.map +0 -1
- package/exceptions-BeWH2FwP.mjs.map +0 -1
- package/exceptions-CitH5wZI.js.map +0 -1
- package/spooled_markdown_artifact-CALSDxIx.js.map +0 -1
- package/spooled_markdown_artifact-Ci5UL7l4.mjs.map +0 -1
- package/tool_call-CV5qVNlb.mjs.map +0 -1
- package/tool_call-Db68hB7y.js.map +0 -1
- package/tool_registry-D1pSSlsd.mjs.map +0 -1
- package/tool_registry-DYUYqXvo.js.map +0 -1
- package/turn_runner-DqWHNP80.js.map +0 -1
- package/turn_runner-fg1Wc3dK.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"helpers.mjs","names":[],"sources":["../../../../src/batteries/llm/ollama/helpers.ts"],"sourcesContent":["/**\n * Swappable translation helpers for rendering ADK state into native Ollama `/api/chat` requests.\n *\n * @module @nhtio/adk/batteries/llm/ollama/helpers\n *\n * @remarks\n * The wire-shape-agnostic helpers (`renderUntrustedContent`, `renderMemories`,\n * `renderChatCompletionsSystemPrompt`, `toolsToChatCompletionsTools`, …) are shared with the OpenAI\n * battery via the internal `../chat_common/helpers` submodule and re-exported here under their\n * original names. Only the Ollama-WIRE-SPECIFIC helpers are defined here:\n * `renderOllamaTimelineMessage` (flat `content` + base64 `images[]` + `thinking`),\n * `renderOllamaToolCallResult` (string-only result content), `buildOllamaHistory` (synthetic\n * `assistant.tool_calls` with object-form `arguments` + `tool`-role messages labelled by\n * `tool_name`), and `ollamaToolsFromTools` (alias of the shared tool-definition renderer — native\n * `/api/chat` uses the same function-tool wire shape).\n *\n * Native `/api/chat` supports only base64 `images[]`; every non-image modality routes through the\n * `unsupportedMediaPolicy` fallback (stash text / synthetic description) or throws.\n */\n\nimport { Media } from '@nhtio/adk/common'\nimport { isInstanceOf } from '@nhtio/adk/guards'\nimport { E_OLLAMA_UNSUPPORTED_MEDIA_MODALITY } from './exceptions'\nimport {\n escapeXmlAttribute,\n memoryToAttrs,\n retrievableToAttrs,\n renderTrustedContent,\n renderUntrustedContent,\n toolsToChatCompletionsTools,\n} from '../chat_common/helpers'\nimport type { ChatHelpersCommon } from '../chat_common/types'\nimport type {\n OllamaMessage,\n OllamaTool,\n OllamaHelpers,\n MemoryAttrs,\n RetrievableAttrs,\n ChatCompletionsBucketOrder,\n UnsupportedMediaPolicy,\n} from './types'\nimport type {\n Tool,\n ArtifactTool,\n ToolRegistry,\n Tokenizable,\n Memory,\n Message,\n Thought,\n ToolCall,\n Retrievable,\n SpooledArtifact,\n MediaModalityHazard,\n MediaStashEntry,\n} from '@nhtio/adk/common'\n\n// ─── Re-exported wire-shape-agnostic helpers (shared submodule) ───────────────\nexport {\n descriptionToChatCompletionsJsonSchema,\n defaultDescriptionToChatCompletionsJsonSchema,\n renderUntrustedContent,\n defaultRenderUntrustedContent,\n renderTrustedContent,\n defaultRenderTrustedContent,\n renderStandingInstructions,\n defaultRenderStandingInstructions,\n renderMemories,\n defaultRenderMemories,\n renderRetrievableSafetyDirective,\n defaultRenderRetrievableSafetyDirective,\n renderFirstPartyRetrievables,\n defaultRenderFirstPartyRetrievables,\n renderThirdPartyPublicRetrievables,\n defaultRenderThirdPartyPublicRetrievables,\n renderThirdPartyPrivateRetrievables,\n defaultRenderThirdPartyPrivateRetrievables,\n renderRetrievables,\n defaultRenderRetrievables,\n renderThought,\n defaultRenderThought,\n filterThoughts,\n defaultFilterThoughts,\n toolsToChatCompletionsTools,\n defaultToolsToChatCompletionsTools,\n renderChatCompletionsSystemPrompt,\n defaultRenderChatCompletionsSystemPrompt,\n} from '../chat_common/helpers'\n\n// ─── ollamaToolsFromTools (alias — native tool wire == Chat Completions wire) ──\n\n/**\n * Convert ADK tools to the native Ollama `tools[]` wire. Native `/api/chat` uses the identical\n * `{ type: 'function', function: { name, description, parameters } }` shape as Chat Completions, so\n * this is an alias of the shared renderer.\n */\nexport const ollamaToolsFromTools = (\n tools: ReadonlyArray<Tool | ArtifactTool>,\n deps: Parameters<typeof toolsToChatCompletionsTools>[1]\n): OllamaTool[] => toolsToChatCompletionsTools(tools, deps)\n/** Default implementation of {@link OllamaHelpers}-style tool translation; alias of {@link ollamaToolsFromTools}. */\nexport const defaultOllamaToolsFromTools = ollamaToolsFromTools\n\n// ─── Media rendering (Ollama native — images only) ────────────────────────────\n\nconst DEFAULT_STASH_FALLBACK_KEYS: ReadonlyArray<string> = [\n 'text:transcript',\n 'text:caption',\n 'text:description',\n]\n\nconst modalityHazardToAttr = (h: MediaModalityHazard): 'inert' | 'extractable' | 'opaque' => {\n if (h === 'inert') return 'inert'\n if (h === 'extractable-instructions') return 'extractable'\n return 'opaque'\n}\n\nconst formatBytesHumanReadable = (bytes: number | undefined): string => {\n if (bytes === undefined || !Number.isFinite(bytes)) return 'unknown size'\n if (bytes < 1024) return `${bytes} B`\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`\n if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`\n return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`\n}\n\nconst isMediaTextStashEntry = (e: unknown): e is MediaStashEntry => {\n if (!e || typeof e !== 'object') return false\n const r = e as Record<string, unknown>\n return typeof r.value === 'string' && typeof r.trustTier === 'string'\n}\n\nconst resolveFallbackStash = (\n media: Media,\n keys: ReadonlyArray<string>\n): { text: string; entryTier: MediaStashEntry['trustTier'] } | undefined => {\n for (const key of keys) {\n const entry = media.stash.get(key)\n if (isMediaTextStashEntry(entry)) {\n return { text: entry.value as string, entryTier: entry.trustTier }\n }\n }\n return undefined\n}\n\nconst renderTextInEnvelope = (\n text: string,\n args: {\n trustTier: MediaStashEntry['trustTier']\n modality: 'inert' | 'extractable' | 'opaque'\n nonce: string\n toolName: string | undefined\n renderTrustedContent: ChatHelpersCommon['renderTrustedContent']\n renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent']\n }\n): string => {\n if (args.trustTier === 'first-party') {\n return args.renderTrustedContent(text, {\n nonce: args.nonce,\n kind: 'media-fallback',\n tool: args.toolName,\n modality: args.modality,\n })\n }\n return args.renderUntrustedContent(text, {\n nonce: args.nonce,\n kind: 'media-fallback',\n tool: args.toolName,\n modality: args.modality,\n })\n}\n\nconst renderSyntheticMediaDescription = (media: Media, byteLen: number | undefined): string =>\n `[media: ${media.filename}, ${media.mimeType}, ${formatBytesHumanReadable(byteLen)}]`\n\n/**\n * Render a single {@link Media} for the native Ollama wire. Images become a base64 entry pushed to\n * the message's `images[]` array (returned via `image`); every other modality is unsupported and\n * routes through `unsupportedMediaPolicy` to a text envelope (returned via `text`) or throws.\n */\nconst renderMediaForOllama = async (input: {\n media: Media\n toolName: string | undefined\n nonce: string\n unsupportedMediaPolicy: UnsupportedMediaPolicy\n renderTrustedContent: ChatHelpersCommon['renderTrustedContent']\n renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent']\n warn?: (msg: string) => void\n}): Promise<{ image?: string; text?: string }> => {\n const { media, toolName, nonce, unsupportedMediaPolicy, warn } = input\n const modality = modalityHazardToAttr(media.modalityHazard)\n\n if (media.kind === 'image') {\n const b64 = await media.asBase64()\n return { image: b64 }\n }\n\n // Non-image modality — native /api/chat has no representation for it.\n const fallbackText = async (\n keys: ReadonlyArray<string>,\n allowSyntheticFallthrough: boolean\n ): Promise<{ text: string }> => {\n const fallback = resolveFallbackStash(media, keys)\n if (fallback) {\n return {\n text: renderTextInEnvelope(fallback.text, {\n trustTier: fallback.entryTier,\n modality,\n nonce,\n toolName,\n renderTrustedContent: input.renderTrustedContent,\n renderUntrustedContent: input.renderUntrustedContent,\n }),\n }\n }\n if (!allowSyntheticFallthrough) {\n warn?.(\n `unsupportedMediaPolicy='fallback-stash' for ${media.filename}: no matching stash entry — falling through to synthetic description.`\n )\n }\n const byteLen = await media.byteLength()\n return {\n text: renderTextInEnvelope(renderSyntheticMediaDescription(media, byteLen), {\n trustTier: media.trustTier,\n modality,\n nonce,\n toolName,\n renderTrustedContent: input.renderTrustedContent,\n renderUntrustedContent: input.renderUntrustedContent,\n }),\n }\n }\n\n if (unsupportedMediaPolicy === 'throw') {\n throw new E_OLLAMA_UNSUPPORTED_MEDIA_MODALITY([media.kind, media.mimeType, media.filename])\n }\n if (\n unsupportedMediaPolicy === 'fallback-stash' ||\n (typeof unsupportedMediaPolicy === 'object' && unsupportedMediaPolicy.mode === 'fallback-stash')\n ) {\n const keys =\n typeof unsupportedMediaPolicy === 'object'\n ? unsupportedMediaPolicy.stashKeys\n : DEFAULT_STASH_FALLBACK_KEYS\n return fallbackText(keys, false)\n }\n return fallbackText([], true)\n}\n\n// ─── renderOllamaTimelineMessage ──────────────────────────────────────────────\n\n/**\n * Renders a single timeline {@link @nhtio/adk!Message} into a native Ollama message — flattening any\n * media into the base64 `images[]` array, surfacing reasoning as `thinking`, and wrapping textual\n * bodies in the appropriate trust envelope.\n */\nexport const renderOllamaTimelineMessage = async (input: {\n message: Message\n selfIdentity: string\n unsupportedMediaPolicy: UnsupportedMediaPolicy\n warn?: (msg: string) => void\n}): Promise<OllamaMessage> => {\n const { message, selfIdentity, unsupportedMediaPolicy, warn } = input\n const identifier =\n message.identity?.identifier !== undefined && message.identity?.identifier !== null\n ? String(message.identity.identifier)\n : ''\n const representationRaw =\n message.identity?.representation !== undefined && message.identity?.representation !== null\n ? message.identity.representation.toString()\n : ''\n const representation = representationRaw.length > 0 ? representationRaw : identifier\n const text = message.content !== undefined ? message.content.toString() : ''\n const createdAtStr = message.createdAt.toISO?.() ?? ''\n const createdAtAttr = createdAtStr ? ` createdAt=\"${escapeXmlAttribute(createdAtStr)}\"` : ''\n const attachments = message.attachments\n\n // Build the text envelope (same identity logic as the OpenAI battery — wire-agnostic).\n let envelopeText: string\n let role: 'user' | 'assistant'\n if (message.role === 'user') {\n role = 'user'\n if (identifier.length === 0) {\n envelopeText = text\n } else {\n const fromAttr = escapeXmlAttribute(representation)\n envelopeText = `<message_${message.id} from=\"${fromAttr}\" role=\"user\"${createdAtAttr}>\\n${text}\\n</message_${message.id}>`\n }\n } else {\n role = 'assistant'\n if (identifier.length === 0 || identifier === selfIdentity) {\n envelopeText = text\n } else {\n const fromAttr = escapeXmlAttribute(representation)\n envelopeText = `<peer_agent_output_${message.id} from=\"${fromAttr}\"${createdAtAttr}>\\n${text}\\n</peer_agent_output_${message.id}>`\n }\n }\n\n const images: string[] = []\n const extraTexts: string[] = []\n for (const media of attachments) {\n const rendered = await renderMediaForOllama({\n media,\n toolName: undefined,\n nonce: message.id,\n unsupportedMediaPolicy,\n renderTrustedContent,\n renderUntrustedContent,\n warn,\n })\n if (rendered.image !== undefined) images.push(rendered.image)\n if (rendered.text !== undefined) extraTexts.push(rendered.text)\n }\n\n // Non-image fallbacks (text envelopes) are appended to the message content; images ride in the\n // separate native `images[]` field.\n const contentParts: string[] = []\n if (envelopeText.length > 0) contentParts.push(envelopeText)\n for (const t of extraTexts) contentParts.push(t)\n const out: OllamaMessage = { role, content: contentParts.join('\\n') }\n if (images.length > 0) out.images = images\n return out\n}\n/** Default timeline-message renderer; alias of {@link renderOllamaTimelineMessage}. */\nexport const defaultRenderOllamaTimelineMessage = renderOllamaTimelineMessage\n\n// ─── renderOllamaToolCallResult ───────────────────────────────────────────────\n\nconst looksLikeSpooledArtifact = (value: unknown): value is SpooledArtifact => {\n if (!value || typeof value !== 'object') return false\n const v = value as Record<string, unknown>\n return (\n typeof v.asString === 'function' &&\n typeof v.byteLength === 'function' &&\n typeof v.lineCount === 'function' &&\n typeof v.estimateTokens === 'function'\n )\n}\n\nconst renderArtifactHandleBody = (\n toolCall: ToolCall,\n artifact: SpooledArtifact,\n byteLength: number,\n lineCount: number\n): string => {\n const ctor = (\n artifact as unknown as {\n constructor: { toolMethods?: ReadonlyArray<{ name: string; description?: string }> }\n }\n ).constructor\n const methods = ctor?.toolMethods ?? []\n const lines: string[] = []\n lines.push(`This tool returned a large artifact that was not inlined to preserve context budget.`)\n lines.push(``)\n lines.push(`Artifact metadata:`)\n lines.push(`- callId: ${toolCall.id}`)\n lines.push(`- kind: ${ctor?.constructor?.name ?? 'SpooledArtifact'}`)\n lines.push(`- byteLength: ${byteLength}`)\n lines.push(`- lineCount: ${lineCount}`)\n lines.push(``)\n lines.push(`To read this artifact in this turn, call one of the following tools with`)\n lines.push(`callId=${toolCall.id}:`)\n for (const m of methods) {\n if (m.description) {\n lines.push(`- ${m.name} — ${m.description}`)\n } else {\n lines.push(`- ${m.name}`)\n }\n }\n lines.push(``)\n lines.push(\n `The artifact persists in this turn's context — multiple queries against the same callId are allowed and efficient. Do not assume the body has been inlined anywhere else.`\n )\n return lines.join('\\n')\n}\n\n/**\n * Render a tool-call result to native Ollama tool-message content (always a string). Media results\n * are routed through the internal media renderer: images cannot ride on a tool-role message's\n * `content`, so an image result is replaced with a short text marker (the image bytes are not\n * re-sent on a tool message); non-image media use the same fallback-text path as elsewhere.\n */\nexport const renderOllamaToolCallResult = async (input: {\n toolCall: ToolCall\n results: Tokenizable | SpooledArtifact | SpooledArtifact[] | Media | Media[]\n tool: Tool | ArtifactTool | undefined\n renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent']\n renderTrustedContent: ChatHelpersCommon['renderTrustedContent']\n unsupportedMediaPolicy: UnsupportedMediaPolicy\n warn?: (msg: string) => void\n}): Promise<string> => {\n const { toolCall, results, tool, warn, unsupportedMediaPolicy } = input\n const isTrusted =\n tool !== null && tool !== undefined && (tool as { trusted?: boolean }).trusted === true\n\n if (tool === undefined) {\n warn?.(\n `Tool \"${toolCall.tool}\" is not present in the bound tool registry at render time; defaulting to untrusted envelope.`\n )\n }\n\n // Media silo — bypasses Tool.trusted (Trust-Is-Content rule).\n const isMediaResult = Media.isMedia(results)\n const isMediaArrayResult =\n Array.isArray(results) && results.length > 0 && results.every((r) => Media.isMedia(r))\n if (isMediaResult || isMediaArrayResult) {\n const mediaList = isMediaResult ? [results as Media] : (results as Media[])\n const parts: string[] = []\n for (const media of mediaList) {\n const rendered = await renderMediaForOllama({\n media,\n toolName: toolCall.tool,\n nonce: toolCall.checksum,\n unsupportedMediaPolicy,\n renderTrustedContent: input.renderTrustedContent,\n renderUntrustedContent: input.renderUntrustedContent,\n warn,\n })\n if (rendered.text !== undefined) {\n parts.push(rendered.text)\n } else {\n // An image tool-result cannot be carried on a tool-role message's string content; emit a\n // text marker in its place so the model knows an image was produced.\n const byteLen = await media.byteLength()\n parts.push(\n input.renderUntrustedContent(renderSyntheticMediaDescription(media, byteLen), {\n nonce: toolCall.checksum,\n kind: 'tool-result-image',\n tool: toolCall.tool,\n modality: modalityHazardToAttr(media.modalityHazard),\n })\n )\n }\n }\n return parts.join('\\n')\n }\n\n // SpooledArtifact[] silo.\n if (Array.isArray(results)) {\n const parts: string[] = []\n for (const a of results) {\n parts.push(await (a as SpooledArtifact).asString())\n }\n const joined = parts.join('\\n\\n')\n return isTrusted\n ? input.renderTrustedContent(joined, {\n nonce: toolCall.checksum,\n kind: 'trusted-tool-result',\n tool: toolCall.tool,\n })\n : input.renderUntrustedContent(joined, {\n nonce: toolCall.checksum,\n kind: 'tool-result',\n tool: toolCall.tool,\n })\n }\n\n const isSpooled = looksLikeSpooledArtifact(results)\n\n // Handle-pattern branch: spooled + inline=false → always untrusted (queryable-data).\n if (isSpooled && toolCall.inline === false) {\n const artifact = results as SpooledArtifact\n let byteLength = 0\n let lineCount = 0\n try {\n byteLength = await artifact.byteLength()\n } catch {\n byteLength = 0\n }\n try {\n lineCount = await artifact.lineCount()\n } catch {\n lineCount = 0\n }\n const body = renderArtifactHandleBody(toolCall, artifact, byteLength, lineCount)\n return input.renderUntrustedContent(body, {\n nonce: toolCall.checksum,\n kind: 'artifact-handle',\n tool: toolCall.tool,\n })\n }\n\n if (!isSpooled && toolCall.inline === false) {\n warn?.(\n `Tool call ${toolCall.id} has inline=false but results is a Tokenizable (not a SpooledArtifact); rendering inline anyway.`\n )\n }\n\n const body = isSpooled\n ? await (results as SpooledArtifact).asString()\n : (results as Tokenizable).toString()\n\n return isTrusted\n ? input.renderTrustedContent(body, {\n nonce: toolCall.checksum,\n kind: 'trusted-tool-result',\n tool: toolCall.tool,\n })\n : input.renderUntrustedContent(body, {\n nonce: toolCall.checksum,\n kind: 'tool-result',\n tool: toolCall.tool,\n })\n}\n/** Default tool-call-result renderer; alias of {@link renderOllamaToolCallResult}. */\nexport const defaultRenderOllamaToolCallResult = renderOllamaToolCallResult\n\n// ─── buildOllamaHistory ───────────────────────────────────────────────────────\n\ntype TimelineItem =\n | { kind: 'message'; createdAt: number; value: Message }\n | { kind: 'thought'; createdAt: number; value: Thought }\n | { kind: 'toolCall'; createdAt: number; value: ToolCall }\n\n/**\n * Assembles the complete native Ollama message history for a dispatch — system prompt and content\n * buckets, the interleaved timeline of messages/thoughts/tool calls, and the collected opaque\n * reasoning payloads — by delegating to the injected sub-renderers.\n */\nexport const buildOllamaHistory = async (input: {\n systemPrompt: Tokenizable\n standingInstructions: Iterable<Tokenizable>\n memories: Iterable<Memory>\n retrievables: Iterable<Retrievable>\n messages: Iterable<Message>\n thoughts: Iterable<Thought>\n toolCalls: Iterable<ToolCall>\n tools: ToolRegistry\n renderedToolCallResults: Map<string, string>\n bucketOrder: ChatCompletionsBucketOrder\n selfIdentity: string\n thoughtSurfacing: 'all-self' | 'latest-self' | 'all'\n replayCompatibility: ReadonlyArray<string>\n unsupportedMediaPolicy: UnsupportedMediaPolicy\n renderOllamaToolCallResult: OllamaHelpers['renderOllamaToolCallResult']\n renderChatCompletionsSystemPrompt: ChatHelpersCommon['renderChatCompletionsSystemPrompt']\n renderStandingInstructions: ChatHelpersCommon['renderStandingInstructions']\n renderMemories: ChatHelpersCommon['renderMemories']\n renderRetrievables: ChatHelpersCommon['renderRetrievables']\n renderRetrievableSafetyDirective: ChatHelpersCommon['renderRetrievableSafetyDirective']\n renderFirstPartyRetrievables: ChatHelpersCommon['renderFirstPartyRetrievables']\n renderThirdPartyPublicRetrievables: ChatHelpersCommon['renderThirdPartyPublicRetrievables']\n renderThirdPartyPrivateRetrievables: ChatHelpersCommon['renderThirdPartyPrivateRetrievables']\n renderOllamaTimelineMessage: OllamaHelpers['renderOllamaTimelineMessage']\n renderThought: ChatHelpersCommon['renderThought']\n filterThoughts: ChatHelpersCommon['filterThoughts']\n renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent']\n renderTrustedContent: ChatHelpersCommon['renderTrustedContent']\n warn?: (msg: string) => void\n}): Promise<{\n messages: OllamaMessage[]\n reasoningPayloads: Array<{ id: string; replayCompatibility: string; payload: unknown }>\n}> => {\n const out: OllamaMessage[] = []\n const reasoningPayloads: Array<{ id: string; replayCompatibility: string; payload: unknown }> = []\n\n const buckets = input.bucketOrder\n const timelineIdx = buckets.indexOf('timeline')\n\n const leadingSystem = await input.renderChatCompletionsSystemPrompt({\n systemPrompt: input.systemPrompt,\n standingInstructions: input.standingInstructions,\n memories: input.memories,\n retrievables: input.retrievables,\n bucketOrder: buckets,\n renderStandingInstructions: input.renderStandingInstructions,\n renderMemories: input.renderMemories,\n renderRetrievables: input.renderRetrievables,\n renderRetrievableSafetyDirective: input.renderRetrievableSafetyDirective,\n renderFirstPartyRetrievables: input.renderFirstPartyRetrievables,\n renderThirdPartyPublicRetrievables: input.renderThirdPartyPublicRetrievables,\n renderThirdPartyPrivateRetrievables: input.renderThirdPartyPrivateRetrievables,\n renderUntrustedContent: input.renderUntrustedContent,\n })\n if (leadingSystem.length > 0) {\n out.push({ role: 'system', content: leadingSystem })\n }\n\n const includesTimeline = timelineIdx !== -1\n if (includesTimeline) {\n const survivingThoughts = input.filterThoughts(\n input.thoughts,\n input.thoughtSurfacing,\n input.selfIdentity,\n input.replayCompatibility\n )\n\n const items: TimelineItem[] = []\n for (const m of input.messages) {\n items.push({ kind: 'message', createdAt: m.createdAt.toMillis(), value: m })\n }\n for (const t of survivingThoughts) {\n items.push({ kind: 'thought', createdAt: t.createdAt.toMillis(), value: t })\n }\n for (const tc of input.toolCalls) {\n items.push({ kind: 'toolCall', createdAt: tc.createdAt.toMillis(), value: tc })\n }\n items.sort((a, b) => a.createdAt - b.createdAt)\n\n const replaySet = new Set<string>([...input.replayCompatibility])\n\n for (const item of items) {\n if (item.kind === 'message') {\n out.push(\n await input.renderOllamaTimelineMessage({\n message: item.value,\n selfIdentity: input.selfIdentity,\n unsupportedMediaPolicy: input.unsupportedMediaPolicy,\n warn: input.warn,\n })\n )\n } else if (item.kind === 'thought') {\n const t = item.value\n const identifier = String(t.identity?.identifier ?? '')\n const isSelf = identifier === input.selfIdentity\n const hasPayload = t.payload !== undefined\n const compatTag = t.replayCompatibility\n\n if (hasPayload && compatTag && replaySet.has(compatTag)) {\n reasoningPayloads.push({ id: t.id, replayCompatibility: compatTag, payload: t.payload })\n const envelope = input.renderThought(\n t.content.toString(),\n {\n nonce: t.id,\n kind: 'opaque-reasoning',\n from: identifier,\n createdAt: t.createdAt?.toISO?.() ?? undefined,\n replayCompatibility: compatTag,\n },\n t.payload\n )\n out.push({ role: 'assistant', content: envelope })\n } else if (!hasPayload) {\n const envelope = input.renderThought(t.content.toString(), {\n nonce: t.id,\n kind: isSelf ? 'self-reasoning' : 'peer-reasoning',\n from: identifier,\n createdAt: t.createdAt?.toISO?.() ?? undefined,\n })\n out.push({ role: 'assistant', content: envelope })\n }\n // else: opaque, non-matching → elided.\n } else {\n // tool call: synthetic assistant message carrying tool_calls[] (object-form arguments),\n // followed by a tool-role message labelled by `tool_name` (NOT tool_call_id).\n const tc = item.value\n const args =\n tc.args !== null && typeof tc.args === 'object' && !Array.isArray(tc.args)\n ? (tc.args as Record<string, unknown>)\n : {}\n out.push({\n role: 'assistant',\n content: '',\n tool_calls: [{ function: { name: tc.tool, arguments: args } }],\n })\n\n let rendered = input.renderedToolCallResults.get(tc.id)\n if (rendered === undefined) {\n const tool = input.tools.get?.(tc.tool)\n rendered = await input.renderOllamaToolCallResult({\n toolCall: tc,\n results: tc.results as\n | Tokenizable\n | SpooledArtifact\n | SpooledArtifact[]\n | Media\n | Media[],\n tool: tool as Tool | ArtifactTool | undefined,\n renderUntrustedContent: input.renderUntrustedContent,\n renderTrustedContent: input.renderTrustedContent,\n unsupportedMediaPolicy: input.unsupportedMediaPolicy,\n warn: input.warn,\n })\n }\n out.push({ role: 'tool', content: rendered, tool_name: tc.tool })\n }\n }\n }\n\n if (includesTimeline) {\n const trailingParts: string[] = []\n for (let i = timelineIdx + 1; i < buckets.length; i++) {\n const label = buckets[i]!\n if (label === 'standingInstructions') {\n const block = input.renderStandingInstructions(input.standingInstructions)\n if (block.length > 0) trailingParts.push(block)\n } else if (label === 'memories') {\n const wrapped: Array<{ memory: Memory; attrs: MemoryAttrs }> = []\n for (const m of input.memories) {\n wrapped.push(memoryToAttrs(m))\n }\n const block = input.renderMemories(wrapped)\n if (block.length > 0) trailingParts.push(block)\n } else if (label === 'retrievables') {\n const wrapped: Array<{ retrievable: Retrievable; attrs: RetrievableAttrs }> = []\n for (const r of input.retrievables) {\n wrapped.push(retrievableToAttrs(r))\n }\n const block = await input.renderRetrievables(wrapped, {\n renderRetrievableSafetyDirective: input.renderRetrievableSafetyDirective,\n renderFirstPartyRetrievables: input.renderFirstPartyRetrievables,\n renderThirdPartyPublicRetrievables: input.renderThirdPartyPublicRetrievables,\n renderThirdPartyPrivateRetrievables: input.renderThirdPartyPrivateRetrievables,\n renderUntrustedContent: input.renderUntrustedContent,\n })\n if (block.length > 0) trailingParts.push(block)\n }\n }\n if (trailingParts.length > 0) {\n out.push({ role: 'system', content: trailingParts.join('\\n\\n') })\n }\n }\n\n return { messages: out, reasoningPayloads }\n}\n/** Default native-history assembler; alias of {@link buildOllamaHistory}. */\nexport const defaultBuildOllamaHistory = buildOllamaHistory\n\n// suppress unused\nvoid isInstanceOf\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+FA,IAAa,wBACX,OACA,SACiB,4BAA4B,OAAO,IAAI;;AAE1D,IAAa,8BAA8B;AAI3C,IAAM,8BAAqD;CACzD;CACA;CACA;AACF;AAEA,IAAM,wBAAwB,MAA+D;CAC3F,IAAI,MAAM,SAAS,OAAO;CAC1B,IAAI,MAAM,4BAA4B,OAAO;CAC7C,OAAO;AACT;AAEA,IAAM,4BAA4B,UAAsC;CACtE,IAAI,UAAU,KAAA,KAAa,CAAC,OAAO,SAAS,KAAK,GAAG,OAAO;CAC3D,IAAI,QAAQ,MAAM,OAAO,GAAG,MAAM;CAClC,IAAI,QAAQ,OAAO,MAAM,OAAO,IAAI,QAAQ,MAAM,QAAQ,CAAC,EAAE;CAC7D,IAAI,QAAQ,OAAO,OAAO,MAAM,OAAO,IAAI,SAAS,OAAO,OAAO,QAAQ,CAAC,EAAE;CAC7E,OAAO,IAAI,SAAS,OAAO,OAAO,OAAO,QAAQ,CAAC,EAAE;AACtD;AAEA,IAAM,yBAAyB,MAAqC;CAClE,IAAI,CAAC,KAAK,OAAO,MAAM,UAAU,OAAO;CACxC,MAAM,IAAI;CACV,OAAO,OAAO,EAAE,UAAU,YAAY,OAAO,EAAE,cAAc;AAC/D;AAEA,IAAM,wBACJ,OACA,SAC0E;CAC1E,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,QAAQ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
|
+
*
|
|
6
|
+
* @remarks
|
|
7
|
+
* Opinionated native Ollama LLM battery. Ships an `OllamaAdapter` that targets Ollama's NATIVE
|
|
8
|
+
* `/api/chat` endpoint (NOT the OpenAI-compat `/v1` layer — for that, point the
|
|
9
|
+
* `openai_chat_completions` battery at `<host>/v1`). Works with both local Ollama
|
|
10
|
+
* (`http://localhost:11434`, no auth) and cloud Ollama (`https://ollama.com`, `Authorization:
|
|
11
|
+
* Bearer <apiKey>`); the only difference is `baseURL` plus the auth header. Native Ollama is
|
|
12
|
+
* HTTP-only — a Unix-socket deployment is reached via a custom `fetch` or an external bridge.
|
|
13
|
+
*
|
|
14
|
+
* Native `/api/chat` unlocks capabilities the `/v1` compat layer cannot express: per-request
|
|
15
|
+
* context size (`options.num_ctx`), native reasoning (`think` + `message.thinking`), structured
|
|
16
|
+
* output (`format`), model lifecycle (`keep_alive`), object-form tool-call arguments, NDJSON
|
|
17
|
+
* streaming, and native generation stats (surfaced via the runner's `generationStats` observability
|
|
18
|
+
* channel).
|
|
19
|
+
*
|
|
20
|
+
* Re-exports the adapter class, every translation helper (wire-shape-agnostic helpers are shared
|
|
21
|
+
* with the OpenAI battery via the internal `chat_common` submodule and re-exported here under their
|
|
22
|
+
* original names, each with a `default*` alias), the option / wire-shape types, the validation
|
|
23
|
+
* schema + `validateOptions` wrapper, and the battery-scoped exception classes.
|
|
24
|
+
*/
|
|
25
|
+
export { OllamaAdapter } from "./adapter";
|
|
26
|
+
export { descriptionToChatCompletionsJsonSchema, defaultDescriptionToChatCompletionsJsonSchema, renderUntrustedContent, defaultRenderUntrustedContent, renderTrustedContent, defaultRenderTrustedContent, renderStandingInstructions, defaultRenderStandingInstructions, renderMemories, defaultRenderMemories, renderRetrievables, defaultRenderRetrievables, renderRetrievableSafetyDirective, defaultRenderRetrievableSafetyDirective, renderFirstPartyRetrievables, defaultRenderFirstPartyRetrievables, renderThirdPartyPublicRetrievables, defaultRenderThirdPartyPublicRetrievables, renderThirdPartyPrivateRetrievables, defaultRenderThirdPartyPrivateRetrievables, renderThought, defaultRenderThought, filterThoughts, defaultFilterThoughts, toolsToChatCompletionsTools, defaultToolsToChatCompletionsTools, renderChatCompletionsSystemPrompt, defaultRenderChatCompletionsSystemPrompt, ollamaToolsFromTools, defaultOllamaToolsFromTools, renderOllamaTimelineMessage, defaultRenderOllamaTimelineMessage, renderOllamaToolCallResult, defaultRenderOllamaToolCallResult, buildOllamaHistory, defaultBuildOllamaHistory, } from "./helpers";
|
|
27
|
+
export type { DescriptionLike, JsonSchema, UntrustedContentAttrs, TrustedContentAttrs, StandingInstructionAttrs, MemoryAttrs, RetrievableAttrs, ThoughtAttrs, ChatCompletionsBucketLabel, ChatCompletionsBucketOrder, ChatCompletionsTool, UnsupportedMediaPolicy, ChatCompletionsRetryConfig, ChatHelpersCommon, OllamaThink, OllamaFormat, OllamaRuntimeOptions, OllamaToolCall, OllamaMessage, OllamaTool, OllamaChatRequestBody, OllamaChatStreamChunk, OllamaChatResponse, OllamaHelpers, OllamaAdapterOptions, } from "./types";
|
|
28
|
+
export { ollamaOptionsSchema, validateOptions } from "./validation";
|
|
29
|
+
export { E_INVALID_OLLAMA_OPTIONS, E_OLLAMA_CONTEXT_OVERFLOW, E_OLLAMA_HTTP_ERROR, E_OLLAMA_STREAM_ERROR, E_OLLAMA_STREAM_STALLED, E_OLLAMA_REQUEST_TIMEOUT, E_OLLAMA_INVALID_TOOL_CALL_ARGS, E_OLLAMA_UNSUPPORTED_MEDIA_MODALITY, } from "./exceptions";
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TypeScript wire shapes, helper contracts, and option types for the native Ollama battery.
|
|
3
|
+
*
|
|
4
|
+
* @module @nhtio/adk/batteries/llm/ollama/types
|
|
5
|
+
*
|
|
6
|
+
* @remarks
|
|
7
|
+
* Type aliases for the native Ollama `/api/chat` adapter — the native wire shapes (which differ
|
|
8
|
+
* from OpenAI Chat Completions: flat string `content` + separate base64 `images[]`, `thinking` for
|
|
9
|
+
* reasoning, object-form tool-call `arguments`, `tool_name` on tool-role messages, NDJSON
|
|
10
|
+
* streaming terminated by `done: true`), the adapter's options shape, and the {@link OllamaHelpers}
|
|
11
|
+
* contract. Runtime validation lives in `validation.ts` (`ollamaOptionsSchema`).
|
|
12
|
+
*
|
|
13
|
+
* Wire-shape-agnostic types (`JsonSchema`, the attribute envelopes, `UnsupportedMediaPolicy`, the
|
|
14
|
+
* bucket order, the retry config, the function-tool wire) are imported from the shared, internal
|
|
15
|
+
* `../chat_common/types` submodule and re-exported here so consumers of
|
|
16
|
+
* `@nhtio/adk/batteries/llm/ollama` get a self-contained type surface.
|
|
17
|
+
*/
|
|
18
|
+
import type { TokenEncoding } from "../../../common";
|
|
19
|
+
import type { SpooledArtifact, Media, SpoolStore } from "../../../common";
|
|
20
|
+
import type { Tokenizable, Memory, Message, Thought, ToolCall, Retrievable, Tool, ArtifactTool, ToolRegistry } from "../../../common";
|
|
21
|
+
import type { JsonSchema, ChatCompletionsBucketOrder, ChatCompletionsTool, UnsupportedMediaPolicy, ChatCompletionsRetryConfig, ChatHelpersCommon } from "../chat_common/types";
|
|
22
|
+
export type { DescriptionLike, JsonSchema, UntrustedContentAttrs, TrustedContentAttrs, StandingInstructionAttrs, MemoryAttrs, RetrievableAttrs, ThoughtAttrs, ChatCompletionsBucketLabel, ChatCompletionsBucketOrder, ChatCompletionsTool, UnsupportedMediaPolicy, ChatCompletionsRetryConfig, ChatHelpersCommon, } from "../chat_common/types";
|
|
23
|
+
/**
|
|
24
|
+
* Native `think` control for thinking-capable models. `true`/`false` toggle reasoning; the effort
|
|
25
|
+
* strings request a reasoning budget on models that support graded thinking.
|
|
26
|
+
*/
|
|
27
|
+
export type OllamaThink = boolean | 'low' | 'medium' | 'high';
|
|
28
|
+
/**
|
|
29
|
+
* Native `format` control. `'json'` requests free-form JSON; a {@link JsonSchema} object requests
|
|
30
|
+
* schema-constrained structured output (the model's `content` is then a JSON string matching it).
|
|
31
|
+
*/
|
|
32
|
+
export type OllamaFormat = 'json' | JsonSchema;
|
|
33
|
+
/**
|
|
34
|
+
* Native Ollama runtime/sampling parameters — sent NESTED under the request body's `options` key,
|
|
35
|
+
* NOT at the top level (this is the key structural divergence from the OpenAI wire, where these
|
|
36
|
+
* sit at the top level). All fields are optional; set only the ones you want to override. An
|
|
37
|
+
* index signature allows forward-compatible passthrough of llama.cpp parameters this type has not
|
|
38
|
+
* yet enumerated.
|
|
39
|
+
*/
|
|
40
|
+
export interface OllamaRuntimeOptions {
|
|
41
|
+
/** Context window (KV-cache) size in tokens. Independent of the ADK `contextWindow` guard. */
|
|
42
|
+
num_ctx?: number;
|
|
43
|
+
/** Sampling temperature. */
|
|
44
|
+
temperature?: number;
|
|
45
|
+
/** Nucleus sampling cutoff. */
|
|
46
|
+
top_p?: number;
|
|
47
|
+
/** Top-k sampling cutoff. */
|
|
48
|
+
top_k?: number;
|
|
49
|
+
/** Min-p sampling cutoff. */
|
|
50
|
+
min_p?: number;
|
|
51
|
+
/** Typical-p sampling cutoff. */
|
|
52
|
+
typical_p?: number;
|
|
53
|
+
/** RNG seed for reproducible outputs. */
|
|
54
|
+
seed?: number;
|
|
55
|
+
/** Stop sequence(s). */
|
|
56
|
+
stop?: string | string[];
|
|
57
|
+
/** Max tokens to predict (`-1` = infinite, `-2` = fill context). */
|
|
58
|
+
num_predict?: number;
|
|
59
|
+
/** Tokens to keep from the initial prompt when context is exceeded. */
|
|
60
|
+
num_keep?: number;
|
|
61
|
+
/** Penalty applied to repeated tokens. */
|
|
62
|
+
repeat_penalty?: number;
|
|
63
|
+
/** Look-back window for repeat penalty. */
|
|
64
|
+
repeat_last_n?: number;
|
|
65
|
+
/** Presence penalty. */
|
|
66
|
+
presence_penalty?: number;
|
|
67
|
+
/** Frequency penalty. */
|
|
68
|
+
frequency_penalty?: number;
|
|
69
|
+
/** Penalize newline tokens. */
|
|
70
|
+
penalize_newline?: boolean;
|
|
71
|
+
/** Prompt-processing batch size. */
|
|
72
|
+
num_batch?: number;
|
|
73
|
+
/** Number of layers to offload to GPU(s). */
|
|
74
|
+
num_gpu?: number;
|
|
75
|
+
/** Primary GPU index. */
|
|
76
|
+
main_gpu?: number;
|
|
77
|
+
/** CPU thread count. */
|
|
78
|
+
num_thread?: number;
|
|
79
|
+
/** Enable NUMA support. */
|
|
80
|
+
numa?: boolean;
|
|
81
|
+
/** Memory-map the model. */
|
|
82
|
+
use_mmap?: boolean;
|
|
83
|
+
/** Forward-compatible passthrough for additional llama.cpp parameters. */
|
|
84
|
+
[key: string]: unknown;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* A native Ollama tool call as returned on a response/stream `message`. Note: `arguments` is a
|
|
88
|
+
* parsed JSON OBJECT (not a string), and there is no `id` or `type` field — the adapter
|
|
89
|
+
* synthesizes a correlation id.
|
|
90
|
+
*/
|
|
91
|
+
export interface OllamaToolCall {
|
|
92
|
+
/** The called function: its name and its parsed-JSON-object arguments. */
|
|
93
|
+
function: {
|
|
94
|
+
name: string;
|
|
95
|
+
arguments: Record<string, unknown>;
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* A native Ollama chat message. Flat shape: `content` is always a string; image attachments ride
|
|
100
|
+
* in a separate base64 `images[]` array (no content blocks); `thinking` carries reasoning; a
|
|
101
|
+
* tool-role result message labels its origin with `tool_name` (NOT a `tool_call_id`).
|
|
102
|
+
*/
|
|
103
|
+
export interface OllamaMessage {
|
|
104
|
+
/** Author role of the message. */
|
|
105
|
+
role: 'system' | 'user' | 'assistant' | 'tool';
|
|
106
|
+
/** Flat text body of the message (never a content-block array). */
|
|
107
|
+
content: string;
|
|
108
|
+
/** Reasoning/thinking text emitted by thinking-capable models. */
|
|
109
|
+
thinking?: string;
|
|
110
|
+
/** Base64-encoded image attachments, sent out-of-band from `content`. */
|
|
111
|
+
images?: string[];
|
|
112
|
+
/** Tool calls the model emitted on this (assistant) message. */
|
|
113
|
+
tool_calls?: OllamaToolCall[];
|
|
114
|
+
/** Name of the tool a tool-role result message corresponds to. */
|
|
115
|
+
tool_name?: string;
|
|
116
|
+
}
|
|
117
|
+
/** Native function-tool definition (structurally identical to the Chat Completions tool wire). */
|
|
118
|
+
export type OllamaTool = ChatCompletionsTool;
|
|
119
|
+
/** The native `/api/chat` request body. */
|
|
120
|
+
export interface OllamaChatRequestBody {
|
|
121
|
+
/** Ollama model name to run. */
|
|
122
|
+
model: string;
|
|
123
|
+
/** The conversation history sent to the model. */
|
|
124
|
+
messages: OllamaMessage[];
|
|
125
|
+
/** Whether the response is streamed as NDJSON chunks. */
|
|
126
|
+
stream: boolean;
|
|
127
|
+
/** Function tools advertised to the model. */
|
|
128
|
+
tools?: OllamaTool[];
|
|
129
|
+
/** Native reasoning control for thinking-capable models. */
|
|
130
|
+
think?: OllamaThink;
|
|
131
|
+
/** Structured-output control: `'json'` or a JSON schema. */
|
|
132
|
+
format?: OllamaFormat;
|
|
133
|
+
/** Native sampling/runtime parameters, nested under this key. */
|
|
134
|
+
options?: OllamaRuntimeOptions;
|
|
135
|
+
/** How long the model stays resident after the request. */
|
|
136
|
+
keep_alive?: string | number;
|
|
137
|
+
/**
|
|
138
|
+
* Side-channel for opaque vendor reasoning payloads. Vanilla Ollama ignores unknown top-level
|
|
139
|
+
* keys; gateways that understand it can forward it. Only set when non-empty.
|
|
140
|
+
*/
|
|
141
|
+
_adk_reasoning_payloads?: Array<{
|
|
142
|
+
id: string;
|
|
143
|
+
replayCompatibility: string;
|
|
144
|
+
payload: unknown;
|
|
145
|
+
}>;
|
|
146
|
+
[key: string]: unknown;
|
|
147
|
+
}
|
|
148
|
+
/** A streamed NDJSON chunk from `/api/chat`. The terminal chunk carries `done: true` + stats. */
|
|
149
|
+
export interface OllamaChatStreamChunk {
|
|
150
|
+
/** Model that produced the chunk. */
|
|
151
|
+
model?: string;
|
|
152
|
+
/** ISO-8601 timestamp the chunk was created. */
|
|
153
|
+
created_at?: string;
|
|
154
|
+
/** Partial assistant message carried by this chunk. */
|
|
155
|
+
message?: {
|
|
156
|
+
role?: 'assistant';
|
|
157
|
+
content?: string;
|
|
158
|
+
thinking?: string;
|
|
159
|
+
images?: string[];
|
|
160
|
+
tool_calls?: OllamaToolCall[];
|
|
161
|
+
};
|
|
162
|
+
/** `true` on the terminal chunk. */
|
|
163
|
+
done?: boolean;
|
|
164
|
+
/** Why generation stopped, present on the terminal chunk. */
|
|
165
|
+
done_reason?: 'stop' | 'load' | 'unload' | string;
|
|
166
|
+
/** Total request time in nanoseconds (terminal chunk). */
|
|
167
|
+
total_duration?: number;
|
|
168
|
+
/** Model load time in nanoseconds (terminal chunk). */
|
|
169
|
+
load_duration?: number;
|
|
170
|
+
/** Number of prompt tokens evaluated (terminal chunk). */
|
|
171
|
+
prompt_eval_count?: number;
|
|
172
|
+
/** Prompt evaluation time in nanoseconds (terminal chunk). */
|
|
173
|
+
prompt_eval_duration?: number;
|
|
174
|
+
/** Number of tokens generated (terminal chunk). */
|
|
175
|
+
eval_count?: number;
|
|
176
|
+
/** Generation time in nanoseconds (terminal chunk). */
|
|
177
|
+
eval_duration?: number;
|
|
178
|
+
}
|
|
179
|
+
/** A non-streaming `/api/chat` response (single object with `done: true`). */
|
|
180
|
+
export interface OllamaChatResponse {
|
|
181
|
+
/** Model that produced the response. */
|
|
182
|
+
model?: string;
|
|
183
|
+
/** ISO-8601 timestamp the response was created. */
|
|
184
|
+
created_at?: string;
|
|
185
|
+
/** The completed assistant message. */
|
|
186
|
+
message?: {
|
|
187
|
+
role?: 'assistant';
|
|
188
|
+
content?: string;
|
|
189
|
+
thinking?: string;
|
|
190
|
+
images?: string[];
|
|
191
|
+
tool_calls?: OllamaToolCall[];
|
|
192
|
+
};
|
|
193
|
+
/** Always `true` for a non-streaming response. */
|
|
194
|
+
done?: boolean;
|
|
195
|
+
/** Why generation stopped. */
|
|
196
|
+
done_reason?: 'stop' | 'load' | 'unload' | string;
|
|
197
|
+
/** Total request time in nanoseconds. */
|
|
198
|
+
total_duration?: number;
|
|
199
|
+
/** Model load time in nanoseconds. */
|
|
200
|
+
load_duration?: number;
|
|
201
|
+
/** Number of prompt tokens evaluated. */
|
|
202
|
+
prompt_eval_count?: number;
|
|
203
|
+
/** Prompt evaluation time in nanoseconds. */
|
|
204
|
+
prompt_eval_duration?: number;
|
|
205
|
+
/** Number of tokens generated. */
|
|
206
|
+
eval_count?: number;
|
|
207
|
+
/** Generation time in nanoseconds. */
|
|
208
|
+
eval_duration?: number;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Full translation-helper contract for the native Ollama battery. Extends the wire-shape-agnostic
|
|
212
|
+
* {@link ChatHelpersCommon} (shared with the OpenAI battery) and adds the Ollama-WIRE-SPECIFIC
|
|
213
|
+
* members: flat timeline-message rendering (`images[]` + `thinking`), string-only tool-call-result
|
|
214
|
+
* rendering, and native-history assembly (`tool_name`, object-form tool-call `arguments`). There is
|
|
215
|
+
* no streaming tool-call delta accumulator — native `/api/chat` emits whole `tool_calls` per chunk.
|
|
216
|
+
*/
|
|
217
|
+
export interface OllamaHelpers extends ChatHelpersCommon {
|
|
218
|
+
/** Renders a timeline message into a native Ollama message (`images[]` + `thinking`). */
|
|
219
|
+
renderOllamaTimelineMessage: (input: {
|
|
220
|
+
message: Message;
|
|
221
|
+
selfIdentity: string;
|
|
222
|
+
unsupportedMediaPolicy: UnsupportedMediaPolicy;
|
|
223
|
+
warn?: (msg: string) => void;
|
|
224
|
+
}) => Promise<OllamaMessage>;
|
|
225
|
+
/** Renders a tool call's result into a native Ollama tool-role message body (string-only). */
|
|
226
|
+
renderOllamaToolCallResult: (input: {
|
|
227
|
+
toolCall: ToolCall;
|
|
228
|
+
results: Tokenizable | SpooledArtifact | SpooledArtifact[] | Media | Media[];
|
|
229
|
+
tool: Tool | ArtifactTool | undefined;
|
|
230
|
+
renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent'];
|
|
231
|
+
renderTrustedContent: ChatHelpersCommon['renderTrustedContent'];
|
|
232
|
+
unsupportedMediaPolicy: UnsupportedMediaPolicy;
|
|
233
|
+
warn?: (msg: string) => void;
|
|
234
|
+
}) => Promise<string>;
|
|
235
|
+
/** Assembles the full native history (system prompt, buckets, timeline, thoughts) into messages. */
|
|
236
|
+
buildOllamaHistory: (input: {
|
|
237
|
+
systemPrompt: Tokenizable;
|
|
238
|
+
standingInstructions: Iterable<Tokenizable>;
|
|
239
|
+
memories: Iterable<Memory>;
|
|
240
|
+
retrievables: Iterable<Retrievable>;
|
|
241
|
+
messages: Iterable<Message>;
|
|
242
|
+
thoughts: Iterable<Thought>;
|
|
243
|
+
toolCalls: Iterable<ToolCall>;
|
|
244
|
+
tools: ToolRegistry;
|
|
245
|
+
renderedToolCallResults: Map<string, string>;
|
|
246
|
+
bucketOrder: ChatCompletionsBucketOrder;
|
|
247
|
+
selfIdentity: string;
|
|
248
|
+
thoughtSurfacing: 'all-self' | 'latest-self' | 'all';
|
|
249
|
+
replayCompatibility: ReadonlyArray<string>;
|
|
250
|
+
unsupportedMediaPolicy: UnsupportedMediaPolicy;
|
|
251
|
+
renderOllamaToolCallResult: OllamaHelpers['renderOllamaToolCallResult'];
|
|
252
|
+
renderChatCompletionsSystemPrompt: ChatHelpersCommon['renderChatCompletionsSystemPrompt'];
|
|
253
|
+
renderStandingInstructions: ChatHelpersCommon['renderStandingInstructions'];
|
|
254
|
+
renderMemories: ChatHelpersCommon['renderMemories'];
|
|
255
|
+
renderRetrievables: ChatHelpersCommon['renderRetrievables'];
|
|
256
|
+
renderRetrievableSafetyDirective: ChatHelpersCommon['renderRetrievableSafetyDirective'];
|
|
257
|
+
renderFirstPartyRetrievables: ChatHelpersCommon['renderFirstPartyRetrievables'];
|
|
258
|
+
renderThirdPartyPublicRetrievables: ChatHelpersCommon['renderThirdPartyPublicRetrievables'];
|
|
259
|
+
renderThirdPartyPrivateRetrievables: ChatHelpersCommon['renderThirdPartyPrivateRetrievables'];
|
|
260
|
+
renderOllamaTimelineMessage: OllamaHelpers['renderOllamaTimelineMessage'];
|
|
261
|
+
renderThought: ChatHelpersCommon['renderThought'];
|
|
262
|
+
filterThoughts: ChatHelpersCommon['filterThoughts'];
|
|
263
|
+
renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent'];
|
|
264
|
+
renderTrustedContent: ChatHelpersCommon['renderTrustedContent'];
|
|
265
|
+
warn?: (msg: string) => void;
|
|
266
|
+
}) => Promise<{
|
|
267
|
+
messages: OllamaMessage[];
|
|
268
|
+
reasoningPayloads: Array<{
|
|
269
|
+
id: string;
|
|
270
|
+
replayCompatibility: string;
|
|
271
|
+
payload: unknown;
|
|
272
|
+
}>;
|
|
273
|
+
}>;
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Configuration options for the native Ollama `/api/chat` adapter.
|
|
277
|
+
*/
|
|
278
|
+
export interface OllamaAdapterOptions {
|
|
279
|
+
/** Bearer token for cloud Ollama (`https://ollama.com`). Omit for local (no auth). */
|
|
280
|
+
apiKey?: string;
|
|
281
|
+
/**
|
|
282
|
+
* Endpoint base URL. The adapter targets `<baseURL>/api/chat`. Defaults to
|
|
283
|
+
* `http://localhost:11434` (local); cloud is `https://ollama.com`. Native Ollama is HTTP-only —
|
|
284
|
+
* for a Unix-socket deployment, point this at an HTTP bridge (nginx `proxy_pass` / `socat`) or
|
|
285
|
+
* inject a custom {@link OllamaAdapterOptions.fetch} instead.
|
|
286
|
+
*/
|
|
287
|
+
baseURL?: string;
|
|
288
|
+
/** Custom HTTP headers sent with every request (override built defaults, including auth). */
|
|
289
|
+
headers?: Record<string, string>;
|
|
290
|
+
/**
|
|
291
|
+
* Custom `fetch` implementation. Use to reach a Unix-socket Ollama via a custom transport (e.g.
|
|
292
|
+
* undici with a `unix:` socket path) — native Ollama is HTTP-only, so socket access is a
|
|
293
|
+
* fetch/bridge concern, not an adapter option.
|
|
294
|
+
*/
|
|
295
|
+
fetch?: typeof globalThis.fetch;
|
|
296
|
+
/** Whether to stream the response chunk by chunk. */
|
|
297
|
+
stream?: boolean;
|
|
298
|
+
/** Idle timeout in milliseconds for the stream before aborting. */
|
|
299
|
+
streamIdleTimeoutMs?: number;
|
|
300
|
+
/** Request timeout in milliseconds for API calls. */
|
|
301
|
+
requestTimeoutMs?: number;
|
|
302
|
+
/** Configures request retry behavior. */
|
|
303
|
+
retry?: ChatCompletionsRetryConfig;
|
|
304
|
+
/** Determines order of the system-prompt content buckets in history assembly. */
|
|
305
|
+
bucketOrder?: ChatCompletionsBucketOrder;
|
|
306
|
+
/** Size of the model's token context window (the ADK guard, independent of `num_ctx`). */
|
|
307
|
+
contextWindow?: number;
|
|
308
|
+
/** Unique identity label for the assistant instance. */
|
|
309
|
+
selfIdentity?: string;
|
|
310
|
+
/** Determines which thoughts are surfaced back to the model. */
|
|
311
|
+
thoughtSurfacing?: 'all-self' | 'latest-self' | 'all';
|
|
312
|
+
/** Tokenizer encoding configuration for token counting. */
|
|
313
|
+
tokenEncoding?: TokenEncoding | null;
|
|
314
|
+
/** List of replay labels supported by the assistant. */
|
|
315
|
+
replayCompatibility?: ReadonlyArray<string>;
|
|
316
|
+
/** Optional overrides for the Ollama translation helpers. */
|
|
317
|
+
helpers?: Partial<OllamaHelpers>;
|
|
318
|
+
/** Backing store for `string` / `Uint8Array` tool returns; defaults to a per-dispatch in-memory store. */
|
|
319
|
+
spoolStore?: SpoolStore;
|
|
320
|
+
/** Whether the executor acks automatically on a tool-call-free terminal answer. */
|
|
321
|
+
autoAck?: boolean;
|
|
322
|
+
/** Policy for handling a {@link @nhtio/adk!Media} whose modality the Ollama wire cannot represent. */
|
|
323
|
+
unsupportedMediaPolicy?: UnsupportedMediaPolicy;
|
|
324
|
+
/** Required. The Ollama model name (e.g. `llama3.2`, `gpt-oss:120b` for cloud). */
|
|
325
|
+
model: string;
|
|
326
|
+
/** Native reasoning control for thinking-capable models. */
|
|
327
|
+
think?: OllamaThink;
|
|
328
|
+
/** Structured-output control: `'json'` or a JSON schema object. */
|
|
329
|
+
format?: OllamaFormat;
|
|
330
|
+
/** Native sampling/runtime parameters, sent nested under the request body's `options` key. */
|
|
331
|
+
options?: OllamaRuntimeOptions;
|
|
332
|
+
/** How long the model stays resident after the request (e.g. `'5m'`, `0` to unload). */
|
|
333
|
+
keep_alive?: string | number;
|
|
334
|
+
}
|
|
File without changes
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
require("../../../chunk-Ble4zEEl.js");
|
|
3
|
+
const require_common = require("../../../common-DZl3ADJs.js");
|
|
4
|
+
require("../../../guards.cjs");
|
|
5
|
+
const require_batteries_llm_ollama_exceptions = require("./exceptions.cjs");
|
|
6
|
+
let _nhtio_validation = require("@nhtio/validation");
|
|
7
|
+
//#region src/batteries/llm/ollama/validation.ts
|
|
8
|
+
var jsonSchemaSchema = _nhtio_validation.validator.object().unknown(true);
|
|
9
|
+
var bucketLabelSchema = _nhtio_validation.validator.string().valid("standingInstructions", "memories", "retrievables", "timeline");
|
|
10
|
+
var bucketOrderSchema = _nhtio_validation.validator.array().items(bucketLabelSchema).unique().default([
|
|
11
|
+
"standingInstructions",
|
|
12
|
+
"memories",
|
|
13
|
+
"retrievables",
|
|
14
|
+
"timeline"
|
|
15
|
+
]);
|
|
16
|
+
var tokenEncodingSchema = _nhtio_validation.validator.alternatives(_nhtio_validation.validator.string().valid("gpt2", "r50k_base", "p50k_base", "p50k_edit", "cl100k_base", "o200k_base", "gemini", "llama2", "claude"), _nhtio_validation.validator.any().valid(null).optional()).default(null);
|
|
17
|
+
var retrySchema = _nhtio_validation.validator.object({
|
|
18
|
+
maxAttempts: _nhtio_validation.validator.number().integer().min(1).default(1),
|
|
19
|
+
baseDelayMs: _nhtio_validation.validator.number().integer().min(0).default(500),
|
|
20
|
+
maxDelayMs: _nhtio_validation.validator.number().integer().min(1).default(3e4),
|
|
21
|
+
retriableStatuses: _nhtio_validation.validator.array().items(_nhtio_validation.validator.number().integer().min(100).max(599)).default([
|
|
22
|
+
429,
|
|
23
|
+
502,
|
|
24
|
+
503,
|
|
25
|
+
504
|
|
26
|
+
]),
|
|
27
|
+
honorRetryAfter: _nhtio_validation.validator.boolean().default(true)
|
|
28
|
+
}).unknown(false);
|
|
29
|
+
var helperSchema = _nhtio_validation.validator.function();
|
|
30
|
+
var helpersSchema = _nhtio_validation.validator.object({
|
|
31
|
+
descriptionToChatCompletionsJsonSchema: helperSchema.optional(),
|
|
32
|
+
renderUntrustedContent: helperSchema.optional(),
|
|
33
|
+
renderTrustedContent: helperSchema.optional(),
|
|
34
|
+
renderStandingInstructions: helperSchema.optional(),
|
|
35
|
+
renderMemories: helperSchema.optional(),
|
|
36
|
+
renderRetrievables: helperSchema.optional(),
|
|
37
|
+
renderRetrievableSafetyDirective: helperSchema.optional(),
|
|
38
|
+
renderFirstPartyRetrievables: helperSchema.optional(),
|
|
39
|
+
renderThirdPartyPublicRetrievables: helperSchema.optional(),
|
|
40
|
+
renderThirdPartyPrivateRetrievables: helperSchema.optional(),
|
|
41
|
+
renderThought: helperSchema.optional(),
|
|
42
|
+
filterThoughts: helperSchema.optional(),
|
|
43
|
+
toolsToChatCompletionsTools: helperSchema.optional(),
|
|
44
|
+
renderChatCompletionsSystemPrompt: helperSchema.optional(),
|
|
45
|
+
renderOllamaTimelineMessage: helperSchema.optional(),
|
|
46
|
+
renderOllamaToolCallResult: helperSchema.optional(),
|
|
47
|
+
buildOllamaHistory: helperSchema.optional()
|
|
48
|
+
}).unknown(false);
|
|
49
|
+
var thinkSchema = _nhtio_validation.validator.alternatives(_nhtio_validation.validator.boolean(), _nhtio_validation.validator.string().valid("low", "medium", "high"));
|
|
50
|
+
var formatSchema = _nhtio_validation.validator.alternatives(_nhtio_validation.validator.string().valid("json"), jsonSchemaSchema);
|
|
51
|
+
var keepAliveSchema = _nhtio_validation.validator.alternatives(_nhtio_validation.validator.string(), _nhtio_validation.validator.number());
|
|
52
|
+
var stopSchema = _nhtio_validation.validator.alternatives(_nhtio_validation.validator.string(), _nhtio_validation.validator.array().items(_nhtio_validation.validator.string()));
|
|
53
|
+
var runtimeOptionsSchema = _nhtio_validation.validator.object({
|
|
54
|
+
num_ctx: _nhtio_validation.validator.number().integer().min(1).optional(),
|
|
55
|
+
temperature: _nhtio_validation.validator.number().min(0).optional(),
|
|
56
|
+
top_p: _nhtio_validation.validator.number().min(0).max(1).optional(),
|
|
57
|
+
top_k: _nhtio_validation.validator.number().integer().min(0).optional(),
|
|
58
|
+
min_p: _nhtio_validation.validator.number().min(0).max(1).optional(),
|
|
59
|
+
typical_p: _nhtio_validation.validator.number().min(0).max(1).optional(),
|
|
60
|
+
seed: _nhtio_validation.validator.number().integer().optional(),
|
|
61
|
+
stop: stopSchema.optional(),
|
|
62
|
+
num_predict: _nhtio_validation.validator.number().integer().optional(),
|
|
63
|
+
num_keep: _nhtio_validation.validator.number().integer().min(0).optional(),
|
|
64
|
+
repeat_penalty: _nhtio_validation.validator.number().optional(),
|
|
65
|
+
repeat_last_n: _nhtio_validation.validator.number().integer().optional(),
|
|
66
|
+
presence_penalty: _nhtio_validation.validator.number().optional(),
|
|
67
|
+
frequency_penalty: _nhtio_validation.validator.number().optional(),
|
|
68
|
+
penalize_newline: _nhtio_validation.validator.boolean().optional(),
|
|
69
|
+
num_batch: _nhtio_validation.validator.number().integer().min(1).optional(),
|
|
70
|
+
num_gpu: _nhtio_validation.validator.number().integer().min(0).optional(),
|
|
71
|
+
main_gpu: _nhtio_validation.validator.number().integer().min(0).optional(),
|
|
72
|
+
num_thread: _nhtio_validation.validator.number().integer().min(1).optional(),
|
|
73
|
+
numa: _nhtio_validation.validator.boolean().optional(),
|
|
74
|
+
use_mmap: _nhtio_validation.validator.boolean().optional()
|
|
75
|
+
}).unknown(true);
|
|
76
|
+
/**
|
|
77
|
+
* Validator schema for `OllamaAdapterOptions`. Used by `validateOptions` at construction time and
|
|
78
|
+
* again at the start of every iteration after options have been merged (stash > executor >
|
|
79
|
+
* constructor). Rejects unknown top-level keys so typos fail loud.
|
|
80
|
+
*/
|
|
81
|
+
var ollamaOptionsSchema = _nhtio_validation.validator.object({
|
|
82
|
+
apiKey: _nhtio_validation.validator.string().optional(),
|
|
83
|
+
baseURL: _nhtio_validation.validator.string().optional(),
|
|
84
|
+
headers: _nhtio_validation.validator.object().pattern(_nhtio_validation.validator.string(), _nhtio_validation.validator.string()).optional(),
|
|
85
|
+
fetch: _nhtio_validation.validator.function().optional(),
|
|
86
|
+
stream: _nhtio_validation.validator.boolean().default(true),
|
|
87
|
+
streamIdleTimeoutMs: _nhtio_validation.validator.number().integer().min(0).default(0),
|
|
88
|
+
requestTimeoutMs: _nhtio_validation.validator.number().integer().min(0).default(0),
|
|
89
|
+
retry: retrySchema.optional(),
|
|
90
|
+
bucketOrder: bucketOrderSchema,
|
|
91
|
+
contextWindow: _nhtio_validation.validator.number().integer().min(1).optional(),
|
|
92
|
+
selfIdentity: _nhtio_validation.validator.string().min(1).default("assistant"),
|
|
93
|
+
thoughtSurfacing: _nhtio_validation.validator.string().valid("all-self", "latest-self", "all").default("all-self"),
|
|
94
|
+
tokenEncoding: tokenEncodingSchema,
|
|
95
|
+
replayCompatibility: _nhtio_validation.validator.array().items(_nhtio_validation.validator.string().min(1)).default([]),
|
|
96
|
+
helpers: helpersSchema.optional(),
|
|
97
|
+
spoolStore: require_common.byteStoreSchema.optional(),
|
|
98
|
+
autoAck: _nhtio_validation.validator.boolean().default(false),
|
|
99
|
+
unsupportedMediaPolicy: _nhtio_validation.validator.alternatives(_nhtio_validation.validator.string().valid("throw", "fallback-stash", "synthetic-description"), _nhtio_validation.validator.object({
|
|
100
|
+
mode: _nhtio_validation.validator.string().valid("fallback-stash").required(),
|
|
101
|
+
stashKeys: _nhtio_validation.validator.array().items(_nhtio_validation.validator.string().min(1)).required()
|
|
102
|
+
}).unknown(false)).default("throw"),
|
|
103
|
+
model: _nhtio_validation.validator.string().required(),
|
|
104
|
+
think: thinkSchema.optional(),
|
|
105
|
+
format: formatSchema.optional(),
|
|
106
|
+
options: runtimeOptionsSchema.optional(),
|
|
107
|
+
keep_alive: keepAliveSchema.optional()
|
|
108
|
+
}).unknown(false);
|
|
109
|
+
var formatValidationDetails = (err) => err.details.map((d) => d.message).join(" and ");
|
|
110
|
+
/**
|
|
111
|
+
* Validates an arbitrary input against `ollamaOptionsSchema` and returns the resolved options
|
|
112
|
+
* shape. Throws `E_INVALID_OLLAMA_OPTIONS` (carrying the validator's error report on `cause`) on
|
|
113
|
+
* failure.
|
|
114
|
+
*
|
|
115
|
+
* @param input - The raw options object to validate.
|
|
116
|
+
* @returns The resolved options object with defaults filled in.
|
|
117
|
+
*/
|
|
118
|
+
var validateOptions = (input) => {
|
|
119
|
+
const { value, error } = ollamaOptionsSchema.validate(input, {
|
|
120
|
+
abortEarly: false,
|
|
121
|
+
convert: false
|
|
122
|
+
});
|
|
123
|
+
if (error) throw new require_batteries_llm_ollama_exceptions.E_INVALID_OLLAMA_OPTIONS([formatValidationDetails(error)], { cause: error });
|
|
124
|
+
return value;
|
|
125
|
+
};
|
|
126
|
+
//#endregion
|
|
127
|
+
exports.ollamaOptionsSchema = ollamaOptionsSchema;
|
|
128
|
+
exports.validateOptions = validateOptions;
|
|
129
|
+
|
|
130
|
+
//# sourceMappingURL=validation.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validation.cjs","names":[],"sources":["../../../../src/batteries/llm/ollama/validation.ts"],"sourcesContent":["/**\n * Runtime validation schema and wrapper for native Ollama adapter options.\n *\n * @module @nhtio/adk/batteries/llm/ollama/validation\n *\n * @remarks\n * Schema and call-site wrapper for validating `OllamaAdapterOptions`. Used at construction time\n * and at the start of every iteration against the merged options shape (stash > executor >\n * constructor). Throws `E_INVALID_OLLAMA_OPTIONS` on failure — same hard-fail policy as every other\n * ADK contract.\n *\n * Note the deliberate `.unknown(...)` asymmetry: the TOP level is `.unknown(false)` so option typos\n * fail loud, but the nested `options` (runtime/sampling) block is `.unknown(true)` so new llama.cpp\n * parameters pass through without a library bump.\n */\n\nimport { isError } from '@nhtio/adk/guards'\nimport { byteStoreSchema } from '@nhtio/adk/common'\nimport { E_INVALID_OLLAMA_OPTIONS } from './exceptions'\nimport { validator, ValidationError } from '@nhtio/validation'\nimport type { OllamaAdapterOptions } from './types'\n\n// ─── Sub-schemas ──────────────────────────────────────────────────────────────\n\nconst jsonSchemaSchema = validator.object().unknown(true)\n\nconst bucketLabelSchema = validator\n .string()\n .valid('standingInstructions', 'memories', 'retrievables', 'timeline')\n\nconst bucketOrderSchema = validator\n .array()\n .items(bucketLabelSchema)\n .unique()\n .default(['standingInstructions', 'memories', 'retrievables', 'timeline'])\n\nconst tokenEncodingSchema = validator\n .alternatives(\n validator\n .string()\n .valid(\n 'gpt2',\n 'r50k_base',\n 'p50k_base',\n 'p50k_edit',\n 'cl100k_base',\n 'o200k_base',\n 'gemini',\n 'llama2',\n 'claude'\n ),\n // `tokenEncoding?: TokenEncoding | null` — OPTIONAL: a valid encoding string, explicit null, or\n // absent (undefined = \"no token counting\"). `.optional()` makes the null/undefined disposition\n // explicit per adk/require-validator-any-required, without rejecting the legitimate \"omitted\"\n // case.\n validator.any().valid(null).optional()\n )\n .default(null)\n\nconst retrySchema = validator\n .object({\n maxAttempts: validator.number().integer().min(1).default(1),\n baseDelayMs: validator.number().integer().min(0).default(500),\n maxDelayMs: validator.number().integer().min(1).default(30_000),\n retriableStatuses: validator\n .array()\n .items(validator.number().integer().min(100).max(599))\n .default([429, 502, 503, 504]),\n honorRetryAfter: validator.boolean().default(true),\n })\n .unknown(false)\n\nconst helperSchema = validator.function()\n\nconst helpersSchema = validator\n .object({\n descriptionToChatCompletionsJsonSchema: helperSchema.optional(),\n renderUntrustedContent: helperSchema.optional(),\n renderTrustedContent: helperSchema.optional(),\n renderStandingInstructions: helperSchema.optional(),\n renderMemories: helperSchema.optional(),\n renderRetrievables: helperSchema.optional(),\n renderRetrievableSafetyDirective: helperSchema.optional(),\n renderFirstPartyRetrievables: helperSchema.optional(),\n renderThirdPartyPublicRetrievables: helperSchema.optional(),\n renderThirdPartyPrivateRetrievables: helperSchema.optional(),\n renderThought: helperSchema.optional(),\n filterThoughts: helperSchema.optional(),\n toolsToChatCompletionsTools: helperSchema.optional(),\n renderChatCompletionsSystemPrompt: helperSchema.optional(),\n renderOllamaTimelineMessage: helperSchema.optional(),\n renderOllamaToolCallResult: helperSchema.optional(),\n buildOllamaHistory: helperSchema.optional(),\n })\n .unknown(false)\n\n// ─── Native request-body sub-schemas ──────────────────────────────────────────\n\nconst thinkSchema = validator.alternatives(\n validator.boolean(),\n validator.string().valid('low', 'medium', 'high')\n)\n\nconst formatSchema = validator.alternatives(validator.string().valid('json'), jsonSchemaSchema)\n\nconst keepAliveSchema = validator.alternatives(validator.string(), validator.number())\n\nconst stopSchema = validator.alternatives(\n validator.string(),\n validator.array().items(validator.string())\n)\n\n// Nested runtime/sampling options block. `.unknown(true)` — the ONLY place unknown keys are\n// allowed — so new llama.cpp parameters pass through without a library bump.\nconst runtimeOptionsSchema = validator\n .object({\n num_ctx: validator.number().integer().min(1).optional(),\n temperature: validator.number().min(0).optional(),\n top_p: validator.number().min(0).max(1).optional(),\n top_k: validator.number().integer().min(0).optional(),\n min_p: validator.number().min(0).max(1).optional(),\n typical_p: validator.number().min(0).max(1).optional(),\n seed: validator.number().integer().optional(),\n stop: stopSchema.optional(),\n num_predict: validator.number().integer().optional(),\n num_keep: validator.number().integer().min(0).optional(),\n repeat_penalty: validator.number().optional(),\n repeat_last_n: validator.number().integer().optional(),\n presence_penalty: validator.number().optional(),\n frequency_penalty: validator.number().optional(),\n penalize_newline: validator.boolean().optional(),\n num_batch: validator.number().integer().min(1).optional(),\n num_gpu: validator.number().integer().min(0).optional(),\n main_gpu: validator.number().integer().min(0).optional(),\n num_thread: validator.number().integer().min(1).optional(),\n numa: validator.boolean().optional(),\n use_mmap: validator.boolean().optional(),\n })\n .unknown(true)\n\n// ─── Top-level schema ─────────────────────────────────────────────────────────\n\n/**\n * Validator schema for `OllamaAdapterOptions`. Used by `validateOptions` at construction time and\n * again at the start of every iteration after options have been merged (stash > executor >\n * constructor). Rejects unknown top-level keys so typos fail loud.\n */\nexport const ollamaOptionsSchema = validator\n .object<OllamaAdapterOptions>({\n // ADK control\n apiKey: validator.string().optional(),\n baseURL: validator.string().optional(),\n headers: validator.object().pattern(validator.string(), validator.string()).optional(),\n fetch: validator.function().optional(),\n stream: validator.boolean().default(true),\n streamIdleTimeoutMs: validator.number().integer().min(0).default(0),\n requestTimeoutMs: validator.number().integer().min(0).default(0),\n retry: retrySchema.optional(),\n bucketOrder: bucketOrderSchema,\n contextWindow: validator.number().integer().min(1).optional(),\n selfIdentity: validator.string().min(1).default('assistant'),\n thoughtSurfacing: validator\n .string()\n .valid('all-self', 'latest-self', 'all')\n .default('all-self'),\n tokenEncoding: tokenEncodingSchema,\n replayCompatibility: validator.array().items(validator.string().min(1)).default([]),\n helpers: helpersSchema.optional(),\n spoolStore: byteStoreSchema.optional(),\n // Opt-in: the executor only self-acks tool-call-free responses when true. Default false hands\n // turn-completion control to the implementor's output pipeline.\n autoAck: validator.boolean().default(false),\n unsupportedMediaPolicy: validator\n .alternatives(\n validator.string().valid('throw', 'fallback-stash', 'synthetic-description'),\n validator\n .object({\n mode: validator.string().valid('fallback-stash').required(),\n stashKeys: validator.array().items(validator.string().min(1)).required(),\n })\n .unknown(false)\n )\n .default('throw'),\n\n // Native /api/chat request body\n model: validator.string().required(),\n think: thinkSchema.optional(),\n format: formatSchema.optional(),\n options: runtimeOptionsSchema.optional(),\n keep_alive: keepAliveSchema.optional(),\n })\n .unknown(false)\n\nconst isValidationError = (value: unknown): value is ValidationError =>\n isError(value) && Array.isArray((value as ValidationError).details)\n\nconst formatValidationDetails = (err: ValidationError): string =>\n err.details.map((d) => d.message).join(' and ')\n\n/**\n * Validates an arbitrary input against `ollamaOptionsSchema` and returns the resolved options\n * shape. Throws `E_INVALID_OLLAMA_OPTIONS` (carrying the validator's error report on `cause`) on\n * failure.\n *\n * @param input - The raw options object to validate.\n * @returns The resolved options object with defaults filled in.\n */\nexport const validateOptions = (input: unknown): OllamaAdapterOptions => {\n const { value, error } = ollamaOptionsSchema.validate(input, {\n abortEarly: false,\n convert: false,\n })\n if (error) {\n throw new E_INVALID_OLLAMA_OPTIONS([formatValidationDetails(error)], { cause: error })\n }\n return value as OllamaAdapterOptions\n}\n\n// suppress unused import warning when the alias isn't referenced\nvoid isValidationError\n"],"mappings":";;;;;;;AAwBA,IAAM,mBAAmB,kBAAA,UAAU,OAAO,EAAE,QAAQ,IAAI;AAExD,IAAM,oBAAoB,kBAAA,UACvB,OAAO,EACP,MAAM,wBAAwB,YAAY,gBAAgB,UAAU;AAEvE,IAAM,oBAAoB,kBAAA,UACvB,MAAM,EACN,MAAM,iBAAiB,EACvB,OAAO,EACP,QAAQ;CAAC;CAAwB;CAAY;CAAgB;AAAU,CAAC;AAE3E,IAAM,sBAAsB,kBAAA,UACzB,aACC,kBAAA,UACG,OAAO,EACP,MACC,QACA,aACA,aACA,aACA,eACA,cACA,UACA,UACA,QACF,GAKF,kBAAA,UAAU,IAAI,EAAE,MAAM,IAAI,EAAE,SAAS,CACvC,EACC,QAAQ,IAAI;AAEf,IAAM,cAAc,kBAAA,UACjB,OAAO;CACN,aAAa,kBAAA,UAAU,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,EAAE,QAAQ,CAAC;CAC1D,aAAa,kBAAA,UAAU,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,EAAE,QAAQ,GAAG;CAC5D,YAAY,kBAAA,UAAU,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,EAAE,QAAQ,GAAM;CAC9D,mBAAmB,kBAAA,UAChB,MAAM,EACN,MAAM,kBAAA,UAAU,OAAO,EAAE,QAAQ,EAAE,IAAI,GAAG,EAAE,IAAI,GAAG,CAAC,EACpD,QAAQ;EAAC;EAAK;EAAK;EAAK;CAAG,CAAC;CAC/B,iBAAiB,kBAAA,UAAU,QAAQ,EAAE,QAAQ,IAAI;AAC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