Skip to content

Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.

EPIC Feature/portkey backend (#493)

Louis Choquel0d30a920b8d5
diff --git a/.badges/tests.json b/.badges/tests.json
index c9f504fd2..ab252a096 100644
--- a/.badges/tests.json
+++ b/.badges/tests.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"label": "tests",
- "message": "1697",
+ "message": "1802",
"color": "blue",
"cacheSeconds": 300
-}
+}
\ No newline at end of file
diff --git a/.blackboxrules b/.blackboxrules
index 211d85f6e..c9b8a4ea2 100644
--- a/.blackboxrules
+++ b/.blackboxrules
@@ -107,6 +107,7 @@ This document outlines the core coding standards, best practices, and quality co
### Enums and tests
- When defining enums related to string values, always inherit from `StrEnum`
+ - When you need the enum value as a string, don't use `str(enum_var)` or `enum_var.value`, just use `enum_var` itself, that is the point of using StrEnum!
- Never test equality to an enum value: use match/case, even to single out 1 case out of 10 cases. To avoid heavy match/case code in awkward places, add methods to the enum class such as `is_foobar()`. This is to avoid bugs: when new enum values are added we want the linter to complain. Use the `|` operator to group cases
- As our match/case constructs over enums are always exhaustive, NEVER add a default `case _: ...`. Otherwise, you won't pass linting.
- `StrEnum` must be imported from `pipelex.types` (handles python retrocompatibility):
@@ -114,6 +115,10 @@ This document outlines the core coding standards, best practices, and quality co
from pipelex.types import StrEnum
```
+### Optionals
+
+- Don't write things like `a = b if b else c`, write `a = b or c` instead.
+
### Imports
#### **Imports at the top of the file**
@@ -281,7 +286,6 @@ class TestFooBar:
- Never more than 1 class per test module.
- When testing one method, if possible, limit the number of test functions, but with different test cases in parameters
-- Sometimes it can be convenient to access the test's name in its body, for instance to include into a job_id. To achieve that, add the argument `request: FixtureRequest` into the signature and then you can get the test name using `cast(str, request.node.originalname), # type: ignore`.
#### Test Data Organization
diff --git a/.cursor/rules/pytest_standards.mdc b/.cursor/rules/pytest_standards.mdc
index 2b1a92002..3c5d361b8 100644
--- a/.cursor/rules/pytest_standards.mdc
+++ b/.cursor/rules/pytest_standards.mdc
@@ -64,7 +64,6 @@ class TestFooBar:
- Never more than 1 class per test module.
- When testing one method, if possible, limit the number of test functions, but with different test cases in parameters
-- Sometimes it can be convenient to access the test's name in its body, for instance to include into a job_id. To achieve that, add the argument `request: FixtureRequest` into the signature and then you can get the test name using `cast(str, request.node.originalname), # type: ignore`.
### Test Data Organization
diff --git a/.cursor/rules/python_standards.mdc b/.cursor/rules/python_standards.mdc
index 980b3c7d6..37bef5c88 100644
--- a/.cursor/rules/python_standards.mdc
+++ b/.cursor/rules/python_standards.mdc
@@ -18,6 +18,7 @@ This document outlines the core coding standards, best practices, and quality co
## Enums and tests
- When defining enums related to string values, always inherit from `StrEnum`
+ - When you need the enum value as a string, don't use `str(enum_var)` or `enum_var.value`, just use `enum_var` itself, that is the point of using StrEnum!
- Never test equality to an enum value: use match/case, even to single out 1 case out of 10 cases. To avoid heavy match/case code in awkward places, add methods to the enum class such as `is_foobar()`. This is to avoid bugs: when new enum values are added we want the linter to complain. Use the `|` operator to group cases
- As our match/case constructs over enums are always exhaustive, NEVER add a default `case _: ...`. Otherwise, you won't pass linting.
- `StrEnum` must be imported from `pipelex.types` (handles python retrocompatibility):
@@ -25,6 +26,10 @@ This document outlines the core coding standards, best practices, and quality co
from pipelex.types import StrEnum
```
+## Optionals
+
+- Don't write things like `a = b if b else c`, write `a = b or c` instead.
+
## Imports
### **Imports at the top of the file**
diff --git a/.env.example b/.env.example
index 65770cace..e0d3c5a1a 100644
--- a/.env.example
+++ b/.env.example
@@ -1,6 +1,7 @@
-# [OPTIONAL] Free Pipelex Inference API key - Get yours on Discord: https://go.pipelex.com/discord
-# No credit card required, limited time offer
-PIPELEX_INFERENCE_API_KEY=
+# [OPTIONAL] Free Pipelex Gateway API key - Get yours here: https://app.pipelex.com/
+# This key gets you access to all the best models …
+# … No credit card required, time-limited offer
+PIPELEX_GATEWAY_API_KEY=
# OpenAI: to use models like GPT-4o and GPT-5
OPENAI_API_KEY=
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index 211d85f6e..c9b8a4ea2 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -107,6 +107,7 @@ This document outlines the core coding standards, best practices, and quality co
### Enums and tests
- When defining enums related to string values, always inherit from `StrEnum`
+ - When you need the enum value as a string, don't use `str(enum_var)` or `enum_var.value`, just use `enum_var` itself, that is the point of using StrEnum!
- Never test equality to an enum value: use match/case, even to single out 1 case out of 10 cases. To avoid heavy match/case code in awkward places, add methods to the enum class such as `is_foobar()`. This is to avoid bugs: when new enum values are added we want the linter to complain. Use the `|` operator to group cases
- As our match/case constructs over enums are always exhaustive, NEVER add a default `case _: ...`. Otherwise, you won't pass linting.
- `StrEnum` must be imported from `pipelex.types` (handles python retrocompatibility):
@@ -114,6 +115,10 @@ This document outlines the core coding standards, best practices, and quality co
from pipelex.types import StrEnum
```
+### Optionals
+
+- Don't write things like `a = b if b else c`, write `a = b or c` instead.
+
### Imports
#### **Imports at the top of the file**
@@ -281,7 +286,6 @@ class TestFooBar:
- Never more than 1 class per test module.
- When testing one method, if possible, limit the number of test functions, but with different test cases in parameters
-- Sometimes it can be convenient to access the test's name in its body, for instance to include into a job_id. To achieve that, add the argument `request: FixtureRequest` into the signature and then you can get the test name using `cast(str, request.node.originalname), # type: ignore`.
#### Test Data Organization
diff --git a/.gitignore b/.gitignore
index 3584b117f..f8944e416 100644
--- a/.gitignore
+++ b/.gitignore
@@ -45,6 +45,9 @@ results/
# personnal pipelex config file that overrides the default one
pipelex_super.toml
+# local pipelex service configuration
+.pipelex/pipelex_service.toml
+
# temporary files
temp/
diff --git a/.pipelex/inference/backends.toml b/.pipelex/inference/backends.toml
index 2f002afc8..6191f4edd 100644
--- a/.pipelex/inference/backends.toml
+++ b/.pipelex/inference/backends.toml
@@ -10,16 +10,15 @@
#
####################################################################################################
-[pipelex_inference]
-display_name = "⭐ Pipelex Inference"
-enabled = true
-endpoint = "https://inference.pipelex.com/v1"
-api_key = "${PIPELEX_INFERENCE_API_KEY}"
+[pipelex_gateway]
+display_name = "⭐ Pipelex Gateway"
+enabled = true # Enable after accepting terms via `pipelex init config`
+api_key = "${PIPELEX_GATEWAY_API_KEY}"
[anthropic]
enabled = true
api_key = "${ANTHROPIC_API_KEY}"
-claude_4_tokens_limit = 8192
+valued_constraints = { max_output_tokens_limit = 8192 }
[azure_openai]
display_name = "Azure OpenAI"
@@ -69,6 +68,18 @@ display_name = "OpenAI"
enabled = true
api_key = "${OPENAI_API_KEY}"
+[portkey]
+display_name = "Portkey"
+enabled = true
+endpoint = "https://api.portkey.ai/v1"
+api_key = "${PORTKEY_API_KEY}"
+
+[scaleway]
+display_name = "Scaleway"
+enabled = true
+endpoint = "${SCALEWAY_ENDPOINT}"
+api_key = "${SCALEWAY_API_KEY}"
+
[vertexai]
display_name = "Google Vertex AI"
enabled = false # This is the only one we disable beacuse setting it up requires internet access just to get credentials so it fails in CI sandboxes
@@ -84,3 +95,10 @@ api_key = "${XAI_API_KEY}"
[internal] # software-only backend, runs internally, without AI
enabled = true
+
+# Deprecated
+[pipelex_inference]
+display_name = "🛑 Legacy Pipelex Inference"
+enabled = false
+endpoint = "https://inference.pipelex.com/v1"
+api_key = "${PIPELEX_INFERENCE_API_KEY}"
diff --git a/.pipelex/inference/backends/anthropic.toml b/.pipelex/inference/backends/anthropic.toml
index a3a485379..729e2d107 100644
--- a/.pipelex/inference/backends/anthropic.toml
+++ b/.pipelex/inference/backends/anthropic.toml
@@ -101,7 +101,7 @@ costs = { input = 1.0, output = 5.0 }
["claude-4.5-opus"]
model_id = "claude-opus-4-5-20251101"
-max_tokens = 32000
+max_tokens = 64000
inputs = ["text", "images"]
outputs = ["text", "structured"]
max_prompt_images = 100
diff --git a/.pipelex/inference/backends/azure_openai.toml b/.pipelex/inference/backends/azure_openai.toml
index ee04f7ad6..35ccb4820 100644
--- a/.pipelex/inference/backends/azure_openai.toml
+++ b/.pipelex/inference/backends/azure_openai.toml
@@ -22,9 +22,9 @@
[defaults]
model_type = "llm"
-sdk = "azure_openai"
+sdk = "azure_openai_responses"
prompting_target = "openai"
-structure_method = "instructor/openai_tools"
+structure_method = "instructor/openai_responses_tools"
################################################################################
# LANGUAGE MODELS
@@ -68,28 +68,28 @@ model_id = "o1-mini-2024-09-12"
inputs = ["text"]
outputs = ["text", "structured"]
costs = { input = 3.0, output = 12.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[o1]
model_id = "o1-2024-12-17"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 15.0, output = 60.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[o3-mini]
model_id = "o3-mini-2025-01-31"
inputs = ["text"]
outputs = ["text", "structured"]
costs = { input = 1.1, output = 4.4 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[o3]
model_id = "o3-2025-04-16"
inputs = ["text"]
outputs = ["text", "structured"]
costs = { input = 2, output = 8 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
# --- GPT-5 Series -------------------------------------------------------------
[gpt-5-mini]
@@ -97,28 +97,28 @@ model_id = "gpt-5-mini-2025-08-07"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 0.25, output = 2.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[gpt-5-nano]
model_id = "gpt-5-nano-2025-08-07"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 0.05, output = 0.4 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[gpt-5-chat]
model_id = "gpt-5-chat-2025-08-07"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 1.25, output = 10.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[gpt-5]
model_id = "gpt-5-2025-08-07"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 1.25, output = 10.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
# --- GPT-5.1 Series -------------------------------------------------------------
["gpt-5.1"]
@@ -126,14 +126,14 @@ model_id = "gpt-5.1-2025-11-13"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 1.25, output = 10.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
["gpt-5.1-chat"]
model_id = "gpt-5.1-chat-2025-11-13"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 1.25, output = 10.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
################################################################################
# IMAGE GENERATION MODELS
@@ -141,7 +141,7 @@ constraints = ["temperature_must_be_1"]
# --- OpenAI Image Generation --------------------------------------------------
[gpt-image-1]
-sdk = "azure_rest"
+sdk = "azure_rest_img_gen"
model_type = "img_gen"
model_id = "gpt-image-1-2025-04-15"
inputs = ["text"]
diff --git a/.pipelex/inference/backends/blackboxai.toml b/.pipelex/inference/backends/blackboxai.toml
index 405675b5c..e6cf9dde0 100644
--- a/.pipelex/inference/backends/blackboxai.toml
+++ b/.pipelex/inference/backends/blackboxai.toml
@@ -167,13 +167,13 @@ costs = { input = 0.06, output = 0.24 }
################################################################################
# --- DeepSeek Free Models -----------------------------------------------------
-[deepseek-chat-free]
+[deepseek-chat]
model_id = "blackboxai/deepseek/deepseek-chat:free"
inputs = ["text"]
outputs = ["text", "structured"]
costs = { input = 0.00, output = 0.00 }
-[deepseek-r1-free]
+[deepseek-r1]
model_id = "blackboxai/deepseek/deepseek-r1:free"
inputs = ["text"]
outputs = ["text", "structured"]
diff --git a/.pipelex/inference/backends/groq.toml b/.pipelex/inference/backends/groq.toml
index 72fc0b804..72bdae3fc 100644
--- a/.pipelex/inference/backends/groq.toml
+++ b/.pipelex/inference/backends/groq.toml
@@ -46,7 +46,7 @@ outputs = ["text", "structured"]
costs = { input = 0.59, output = 0.79 }
# --- Meta Llama Guard ---------------------------------------------------------
-["meta-llama/llama-guard-4-12b"]
+[llama-guard-4-12b]
model_id = "meta-llama/llama-guard-4-12b"
max_tokens = 1024
inputs = ["text"]
@@ -54,14 +54,14 @@ outputs = ["text", "structured"]
costs = { input = 0.20, output = 0.20 }
# --- OpenAI GPT-OSS Models ----------------------------------------------------
-["openai/gpt-oss-20b"]
+[gpt-oss-20b]
model_id = "openai/gpt-oss-20b"
max_tokens = 65536
inputs = ["text"]
outputs = ["text", "structured"]
costs = { input = 0.075, output = 0.30 }
-["openai/gpt-oss-120b"]
+[gpt-oss-120b]
model_id = "openai/gpt-oss-120b"
max_tokens = 65536
inputs = ["text"]
@@ -88,7 +88,7 @@ costs = { input = 0.10, output = 0.30 }
################################################################################
# --- Meta Llama 4 Vision Models (Preview) -------------------------------------
-["meta-llama/llama-4-scout-17b-16e-instruct"]
+[llama-4-scout-17b-16e-instruct]
model_id = "meta-llama/llama-4-scout-17b-16e-instruct"
max_tokens = 8192
inputs = ["text", "images"]
@@ -96,7 +96,7 @@ outputs = ["text", "structured"]
max_prompt_images = 5
costs = { input = 0.11, output = 0.34 }
-["meta-llama/llama-4-maverick-17b-128e-instruct"]
+[llama-4-maverick-17b-128e-instruct]
model_id = "meta-llama/llama-4-maverick-17b-128e-instruct"
max_tokens = 8192
inputs = ["text", "images"]
@@ -105,7 +105,7 @@ max_prompt_images = 5
costs = { input = 0.20, output = 0.60 }
# --- Moonshot Kimi K2 ---------------------------------------------------------
-["moonshotai/kimi-k2-instruct-0905"]
+[kimi-k2-instruct-0905]
model_id = "moonshotai/kimi-k2-instruct-0905"
max_tokens = 16384
inputs = ["text"]
@@ -113,7 +113,7 @@ outputs = ["text", "structured"]
costs = { input = 1.00, output = 3.00 }
# --- OpenAI Safety Model ------------------------------------------------------
-["openai/gpt-oss-safeguard-20b"]
+[gpt-oss-safeguard-20b]
model_id = "openai/gpt-oss-safeguard-20b"
max_tokens = 65536
inputs = ["text"]
@@ -121,7 +121,7 @@ outputs = ["text", "structured"]
costs = { input = 0.075, output = 0.30 }
# --- Qwen 3 -------------------------------------------------------------------
-["qwen/qwen3-32b"]
+[qwen3-32b]
model_id = "qwen/qwen3-32b"
max_tokens = 40960
inputs = ["text"]
diff --git a/.pipelex/inference/backends/openai.toml b/.pipelex/inference/backends/openai.toml
index 7fcf0afed..bfb3dd9ff 100644
--- a/.pipelex/inference/backends/openai.toml
+++ b/.pipelex/inference/backends/openai.toml
@@ -22,9 +22,9 @@
[defaults]
model_type = "llm"
-sdk = "openai"
+sdk = "openai_responses"
prompting_target = "openai"
-structure_method = "instructor/openai_tools"
+structure_method = "instructor/openai_responses_tools"
################################################################################
# LANGUAGE MODELS
@@ -93,40 +93,33 @@ outputs = ["text", "structured"]
costs = { input = 0.1, output = 0.4 }
# --- o Series ----------------------------------------------------------------
-[o1-mini]
-model_id = "o1-mini"
-inputs = ["text"]
-outputs = ["text"]
-costs = { input = 3.0, output = 12.0 }
-constraints = ["temperature_must_be_1"]
-
[o1]
model_id = "o1"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 15.0, output = 60.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[o3-mini]
model_id = "o3-mini"
inputs = ["text"]
outputs = ["text", "structured"]
costs = { input = 1.1, output = 4.4 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[o3]
model_id = "o3"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 10.0, output = 40.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[o4-mini]
model_id = "o4-mini"
inputs = ["text"]
outputs = ["text", "structured"]
costs = { input = 1.1, output = 4.4 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
# --- GPT-5 Series -------------------------------------------------------------
[gpt-5]
@@ -134,28 +127,28 @@ model_id = "gpt-5"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 1.25, output = 10.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[gpt-5-mini]
model_id = "gpt-5-mini"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 0.25, output = 2.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[gpt-5-nano]
model_id = "gpt-5-nano"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 0.05, output = 0.4 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[gpt-5-chat]
model_id = "gpt-5-chat-latest"
inputs = ["text", "images"]
outputs = ["text"]
costs = { input = 1.25, output = 10.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
# --- GPT-5.1 Series -------------------------------------------------------------
["gpt-5.1"]
@@ -170,6 +163,7 @@ costs = { input = 1.25, output = 10.0 }
# --- OpenAI Image Generation --------------------------------------------------
[gpt-image-1]
+sdk = "openai_img_gen"
model_type = "img_gen"
model_id = "gpt-image-1"
inputs = ["text"]
diff --git a/.pipelex/inference/backends/pipelex_gateway.toml b/.pipelex/inference/backends/pipelex_gateway.toml
new file mode 100644
index 000000000..bca075b7c
--- /dev/null
+++ b/.pipelex/inference/backends/pipelex_gateway.toml
@@ -0,0 +1,41 @@
+################################################################################
+# Pipelex Gateway Local Overrides
+################################################################################
+#
+# TELEMETRY NOTICE:
+#
+# Using Pipelex Gateway enables identified telemetry tied to your API key
+# (hashed for security). This is independent from your telemetry.toml settings.
+#
+# We collect only technical data (model names, token counts, latency, error rates).
+# We do NOT collect prompts, completions, pipe codes, or business data.
+#
+# This allows us to monitor service quality, enforce fair usage, and support you.
+#
+################################################################################
+#
+# WARNING: USE AT YOUR OWN RISK!
+#
+# The actual model configuration is fetched remotely from Pipelex servers.
+# Any override in this file may cause unexpected behavior or failures,
+# as the remote configuration may change at any time.
+#
+# If you must override, you may ONLY use these keys per model:
+# - sdk
+# - structure_method
+#
+# All other keys will be ignored.
+#
+# If you need custom configurations, consider using your own API keys
+# with direct provider backends (openai, anthropic, etc.) instead.
+#
+# Documentation:
+# https://docs.pipelex.com/home/7-configuration/config-technical/inference-backend-config/
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+# Per-model overrides example:
+# [gpt-4o]
+# sdk = "gateway_completions"
+# structure_method = "instructor/openai_tools"
diff --git a/.pipelex/inference/backends/pipelex_inference.toml b/.pipelex/inference/backends/pipelex_inference.toml
index a7dbdfbc3..751c57021 100644
--- a/.pipelex/inference/backends/pipelex_inference.toml
+++ b/.pipelex/inference/backends/pipelex_inference.toml
@@ -36,66 +36,88 @@ model_id = "pipelex/gpt-4o"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 2.75, output = 11.00 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
[gpt-4o-mini]
model_id = "pipelex/gpt-4o-mini"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 0.17, output = 0.66 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
["gpt-4.1"]
model_id = "pipelex/gpt-4.1"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 2, output = 8 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
["gpt-4.1-mini"]
model_id = "pipelex/gpt-4.1-mini"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 0.4, output = 1.6 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
["gpt-4.1-nano"]
model_id = "pipelex/gpt-4.1-nano"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 0.1, output = 0.4 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
[gpt-5-nano]
model_id = "pipelex/gpt-5-nano"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 0.05, output = 0.40 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
[gpt-5-mini]
model_id = "pipelex/gpt-5-mini"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 0.25, output = 2.00 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
[gpt-5-chat]
model_id = "pipelex/gpt-5-chat"
inputs = ["text", "images"]
outputs = ["text"]
costs = { input = 1.25, output = 10.00 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
[gpt-5]
model_id = "pipelex/gpt-5"
inputs = ["text", "images"]
outputs = ["text"]
costs = { input = 1.25, output = 10.00 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
["gpt-5.1"]
model_id = "pipelex/gpt-5.1"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 1.25, output = 10.00 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
["gpt-5.1-chat"]
model_id = "pipelex/gpt-5.1-chat"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 1.25, output = 10.00 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
# --- Claude LLMs --------------------------------------------------------------
["claude-4-sonnet"]
diff --git a/.pipelex/inference/backends/portkey.toml b/.pipelex/inference/backends/portkey.toml
new file mode 100644
index 000000000..2080d0e14
--- /dev/null
+++ b/.pipelex/inference/backends/portkey.toml
@@ -0,0 +1,272 @@
+################################################################################
+# Portkey Configuration
+################################################################################
+#
+# This file defines the model specifications for the Portkey backend.
+# It contains model definitions for various AI models.
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots must be quoted (e.g., ["gpt-4.1"])
+# - Model costs are in USD per million tokens (input/output)
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "llm"
+sdk = "portkey_completions"
+structure_method = "instructor/openai_tools"
+prompting_target = "anthropic"
+
+################################################################################
+# LANGUAGE MODELS
+################################################################################
+
+# --- OpenAI LLMs --------------------------------------------------------------
+[gpt-4o-mini]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.6 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+[gpt-4o]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 2.5, output = 10.0 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+["gpt-4.1-nano"]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.1, output = 0.4 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+["gpt-4.1-mini"]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.4, output = 1.6 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+["gpt-4.1"]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 2, output = 8 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+[o1]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 15.0, output = 60.0 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+[o3-mini]
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 1.1, output = 4.4 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+[o3]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 2, output = 8 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+[o4-mini]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.1, output = 4.4 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+[gpt-5-nano]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.05, output = 0.4 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+[gpt-5-mini]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.25, output = 2.0 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+[gpt-5]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10.0 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+["gpt-5.1"]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10.0 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+["gpt-5.1-codex"]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10.0 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+# --- Claude LLMs --------------------------------------------------------------
+[claude-3-haiku]
+model_id = "claude-3-haiku-20240307"
+max_tokens = 4096
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 0.25, output = 1.25 }
+x-portkey-provider = "@anthropic"
+
+[claude-3-opus]
+model_id = "claude-3-opus-20240229"
+max_tokens = 4096
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 15.0, output = 75.0 }
+x-portkey-provider = "@anthropic"
+
+["claude-3.7-sonnet"]
+model_id = "claude-3-7-sonnet-20250219"
+max_tokens = 8192
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+x-portkey-provider = "@anthropic"
+
+[claude-4-sonnet]
+model_id = "claude-sonnet-4-20250514"
+max_tokens = 64000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+x-portkey-provider = "@anthropic"
+
+[claude-4-opus]
+model_id = "claude-opus-4-20250514"
+max_tokens = 32000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+x-portkey-provider = "@anthropic"
+
+["claude-4.1-opus"]
+model_id = "claude-opus-4-1-20250805"
+max_tokens = 32000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+x-portkey-provider = "@anthropic"
+
+["claude-4.5-sonnet"]
+model_id = "claude-sonnet-4-5-20250929"
+max_tokens = 64000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+x-portkey-provider = "@anthropic"
+
+["claude-4.5-haiku"]
+model_id = "claude-haiku-4-5-20251001"
+max_tokens = 64000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 1.0, output = 5.0 }
+x-portkey-provider = "@anthropic"
+
+["claude-4.5-opus"]
+model_id = "claude-opus-4-5-20251101"
+max_tokens = 64000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 5.0, output = 25.0 }
+x-portkey-provider = "@anthropic"
+
+# --- Gemini LLMs --------------------------------------------------------------
+["gemini-2.0-flash"]
+model_id = "gemini-2.0-flash"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.10, output = 0.40 }
+x-portkey-provider = "@google"
+
+["gemini-2.5-pro"]
+model_id = "gemini-2.5-pro"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 3000
+costs = { input = 1.25, output = 10.0 }
+x-portkey-provider = "@google"
+
+["gemini-2.5-flash"]
+model_id = "gemini-2.5-flash"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.30, output = 2.50 }
+x-portkey-provider = "@google"
+
+["gemini-2.5-flash-lite"]
+model_id = "gemini-2.5-flash-lite"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.10, output = 0.40 }
+x-portkey-provider = "@google"
+
+["gemini-3.0-pro"]
+model_id = "gemini-3-pro-preview"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 3000
+costs = { input = 2, output = 12.0 }
+x-portkey-provider = "@google"
diff --git a/.pipelex/inference/backends/scaleway.toml b/.pipelex/inference/backends/scaleway.toml
new file mode 100644
index 000000000..20fe79205
--- /dev/null
+++ b/.pipelex/inference/backends/scaleway.toml
@@ -0,0 +1,67 @@
+################################################################################
+# Groq Backend Configuration
+################################################################################
+#
+# This file defines the model specifications for Scaleway models.
+# It contains model definitions for various LLM models accessible through
+# the Groq API, including text-only and vision-capable models.
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots or slashes must be quoted (e.g., ["meta-llama/llama-4-scout"])
+# - Model costs are in USD per million tokens (input/output)
+# - Vision models support max 5 images per request, 33MP max resolution
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "llm"
+sdk = "openai"
+structure_method = "instructor/json"
+
+# --- DeepSeek Models ----------------------------------------------------------
+[deepseek-r1-distill-llama-70b]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.90, output = 0.90 }
+
+# --- Meta Llama 3.x Series ----------------------------------------------------
+["llama-3.1-8b-instruct"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.2, output = 0.2 }
+
+["llama-3.3-70b-instruct"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.90, output = 0.90 }
+
+# --- OpenAI GPT-OSS Models ----------------------------------------------------
+[gpt-oss-120b]
+max_tokens = 65536
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.60 }
+
+# --- Qwen 3 -------------------------------------------------------------------
+[qwen3-235b-a22b-instruct-2507]
+max_tokens = 40960
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.75, output = 2.25 }
+
+[qwen3-coder-30b-a3b-instruct]
+max_tokens = 40960
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.20, output = 0.80 }
diff --git a/.pipelex/inference/deck/base_deck.toml b/.pipelex/inference/deck/base_deck.toml
index 954a65d57..6fb0161d6 100644
--- a/.pipelex/inference/deck/base_deck.toml
+++ b/.pipelex/inference/deck/base_deck.toml
@@ -22,16 +22,16 @@ base-gpt = "gpt-4o"
base-gemini = "gemini-2.5-flash"
base-mistral = "mistral-medium"
base-groq = "llama-3.3-70b-versatile"
+base-grok = "grok-4-fast-non-reasoning"
-best-gpt = "gpt-4o"
-best-claude = "claude-4.1-opus"
-best-gemini = "gemini-2.5-pro"
+best-gpt = "gpt-5.1"
+best-claude = "claude-4.5-opus"
+best-gemini = "gemini-3.0-pro"
best-mistral = "mistral-medium"
-best-grok = "grok-3"
# Groq-specific aliases
fast-groq = "llama-3.1-8b-instant"
-vision-groq = "meta-llama/llama-4-scout-17b-16e-instruct"
+vision-groq = "llama-4-scout-17b-16e-instruct"
# Image generation aliases
base-img-gen = "flux-pro/v1.1"
@@ -43,35 +43,49 @@ fast-img-gen = "fast-lightning-sdxl"
####################################################################################################
[waterfalls]
+
+# --- Waterfalls for LLMs ---------------------------------------------------------------------
smart_llm = [
+ "claude-4.5-opus",
"claude-4.5-sonnet",
+ "gemini-3.0-pro",
+ "gpt-5.1",
"claude-4.1-opus",
- "claude-4-sonnet",
"gemini-2.5-pro",
- "gpt-4o", # we're using gpt-4o here rather than gpt-5 until we'll handle reasoning parameters
- "grok-3",
+ "claude-4-sonnet",
+ "grok-4",
]
smart_llm_with_vision = [
+ "claude-4.5-opus",
"claude-4.5-sonnet",
+ "gemini-3.0-pro",
+ "gpt-5.1",
"claude-4.1-opus",
- "claude-4-sonnet",
"gemini-2.5-pro",
- "gpt-4o", # we use gpt-4o here rather than gpt-5 until we handle reasoning parameters
- "grok-3",
+ "claude-4-sonnet",
+ "grok-4",
]
smart_llm_for_structured = [
+ "claude-4.5-opus",
"claude-4.5-sonnet",
+ "gemini-3.0-pro",
+ "gpt-5.1",
"claude-4.1-opus",
"claude-4-sonnet",
- "gpt-4o", # we use gpt-4o here rather than gpt-5 until we handle reasoning parameters
]
-llm_for_creativity = ["claude-4.1-opus", "gemini-2.5-pro", "gpt-4o"]
+llm_for_creativity = [
+ "claude-4.5-opus",
+ "claude-4.1-opus",
+ "gemini-2.5-pro",
+ "gpt-5.1",
+]
llm_for_large_codebase = [
"gemini-2.5-pro",
"claude-4.5-sonnet",
- "gpt-4o", # we use gpt-4o here rather than gpt-5 until we handle reasoning parameters
+ "gemini-3.0-pro",
+ "gpt-5.1",
"gemini-2.5-flash",
- "grok-3",
+ "grok-4",
]
cheap_llm = [
"gpt-4o-mini",
@@ -93,6 +107,10 @@ cheap_llm_for_creativity = [
"claude-4.5-haiku",
]
+# --- Waterfalls for Extracts ---------------------------------------------------------------------
+pdf_text_extractor = ["mistral-ocr", "pypdfium2-extract-text"]
+image_text_extractor = ["mistral-ocr"]
+
####################################################################################################
# LLM Presets
####################################################################################################
@@ -119,7 +137,7 @@ llm_to_analyze_large_codebase = { model = "base-claude", temperature = 0.1 }
# Vision skills
llm_for_img_to_text_cheap = { model = "gpt-4o-mini", temperature = 0.1 }
llm_for_img_to_text = { model = "base-claude", temperature = 0.1 }
-llm_for_diagram_to_text = { model = "base-claude", temperature = 0.3 }
+llm_for_diagram_to_text = { model = "best-claude", temperature = 0.3 }
llm_for_table_to_text = { model = "base-claude", temperature = 0.3 }
# Image generation prompting skills
diff --git a/.pipelex/inference/routing_profiles.toml b/.pipelex/inference/routing_profiles.toml
index 0910ff285..b3733ae23 100644
--- a/.pipelex/inference/routing_profiles.toml
+++ b/.pipelex/inference/routing_profiles.toml
@@ -9,27 +9,29 @@
# =========================================================================================
# Which profile to use (change this to switch routing)
-active = "pipelex_first"
+# TODO: TBD
+active = "pipelex_gateway_first" # Change to "pipelex_gateway_first" after enabling gateway
-# We recommend using the "pipelex_first" profile to get a head start with all models.
-# The Pipelex Inference backend is currently not recommended for production use,
-# but it's great for development and testing.
-# To use the Pipelex Inference backend (pipelex_first profile):
+# We recommend using the "pipelex_gateway_first" profile to get a head start with all models.
+# To use the Pipelex Gateway backend:
# 1. Join our Discord community to get your free API key (no credit card required):
# Visit https://go.pipelex.com/discord and request your key in the appropriate channel
-# 2. Set the environment variable: export PIPELEX_INFERENCE_API_KEY="your-api-key"
-# 3. The .pipelex/inference/backends.toml is already configured with api_key = "${PIPELEX_INFERENCE_API_KEY}"
-# which will get the key from the environment variable.
+# 2. Set the environment variable (or add it to your .env file):
+# - Linux/macOS: export PIPELEX_GATEWAY_API_KEY="your-api-key"
+# - Windows CMD: set PIPELEX_GATEWAY_API_KEY=your-api-key
+# - Windows PowerShell: $env:PIPELEX_GATEWAY_API_KEY="your-api-key"
+# 3. The .pipelex/inference/backends.toml is already configured with api_key = "${PIPELEX_GATEWAY_API_KEY}"
+# which will get the key from the environment variable.
# =========================================================================================
# Routing Profiles
# =========================================================================================
-[profiles.pipelex_first]
-description = "Use Pipelex Inference backend for all its supported models"
-default = "pipelex_inference"
+[profiles.pipelex_gateway_first]
+description = "Use Pipelex Gateway backend for all its supported models"
+default = "pipelex_gateway"
fallback_order = [
- "pipelex_inference",
+ "pipelex_gateway",
"azure_openai",
"bedrock",
"blackboxai",
@@ -37,19 +39,23 @@ fallback_order = [
"fal",
]
-[profiles.pipelex_first.routes]
+[profiles.pipelex_gateway_first.routes]
# Pattern matching: "model-pattern" = "backend-name"
-"gpt-*" = "pipelex_inference"
-"claude-*" = "pipelex_inference"
-"grok-*" = "pipelex_inference"
-"gemini-*" = "pipelex_inference"
+"gpt-*" = "pipelex_gateway"
+"claude-*" = "pipelex_gateway"
+"grok-*" = "pipelex_gateway"
+"gemini-*" = "pipelex_gateway"
-[profiles.pipelex_first.optional_routes] # Each optional route is considered only if its backend is available
+[profiles.pipelex_gateway_first.optional_routes] # Each optional route is considered only if its backend is available
"*-sdxl" = "fal"
"flux-*" = "fal"
"gpt-image-1" = "openai"
"mistral-ocr" = "mistral"
+[profiles.all_pipelex_gateway]
+description = "Use Pipelex Gateway for all its supported models"
+default = "pipelex_gateway"
+
[profiles.all_anthropic]
description = "Use Anthropic backend for all its supported models"
default = "anthropic"
@@ -90,14 +96,22 @@ default = "ollama"
description = "Use OpenAI backend for all its supported models"
default = "openai"
-[profiles.all_pipelex_inference]
-description = "Use Pipelex Inference backend for all its supported models"
-default = "pipelex_inference"
+[profiles.all_portkey]
+description = "Use Portkey backend for all its supported models"
+default = "portkey"
+
+[profiles.all_scaleway]
+description = "Use Scaleway backend for all its supported models"
+default = "scaleway"
[profiles.all_xai]
description = "Use xAI backend for all its supported models"
default = "xai"
+[profiles.all_internal]
+description = "Use internal backend for all its supported models"
+default = "internal"
+
# =========================================================================================
# Custom Profiles
# =========================================================================================
diff --git a/.pipelex/pipelex.toml b/.pipelex/pipelex.toml
index 9e4f9cbb6..955152085 100644
--- a/.pipelex/pipelex.toml
+++ b/.pipelex/pipelex.toml
@@ -67,6 +67,13 @@ pipelex = "INFO"
# Uncomment to change the reaction to missing presets: "raise" (default), "log" or "none"
# missing_presets_reaction = "raise"
+[cogt.tenacity_config]
+# Uncomment to change those values as needed
+# max_retries = 50 # Maximum number of retry attempts before giving up
+# wait_multiplier = 0.2 # Multiplier applied to the wait time between retries (in seconds)
+# wait_max = 20 # Maximum wait time between retries (in seconds)
+# wait_exp_base = 1.3 # Base for exponential backoff calculation
+
[cogt.llm_config]
# Uncomment any of these to enable dumping the inputs or outputs of text-genration with an LLM
# is_dump_text_prompts_enabled = true
diff --git a/.pipelex/telemetry.toml b/.pipelex/telemetry.toml
index af98b57e8..75207a7c8 100644
--- a/.pipelex/telemetry.toml
+++ b/.pipelex/telemetry.toml
@@ -1,21 +1,84 @@
####################################################################################################
-# Pipelex Telemetry Configuration
+# Custom Telemetry Configuration
####################################################################################################
#
-# This file controls telemetry settings for Pipelex usage analytics.
-# Telemetry helps us improve Pipelex by understanding how it's used.
+# This file controls YOUR custom telemetry settings for observability and analytics.
+# Configure your own PostHog, Langfuse, or OTLP-compatible backends here.
+#
+# NOTE: When using Pipelex Gateway, identified telemetry is automatically enabled
+# (tied to your Gateway API key, hashed for security). This allows us to monitor
+# service quality, enforce fair usage, and provide you with better support.
+# Gateway telemetry operates independently from your settings below - you can have both!
+#
+# To disable all telemetry, set the DO_NOT_TRACK=1 environment variable.
#
# Documentation: https://docs.pipelex.com
# Support: https://go.pipelex.com/discord
#
####################################################################################################
-telemetry_mode = "anonymous" # Values: "off" | "anonymous" | "identified"
-host = "https://eu.i.posthog.com"
-project_api_key = "phc_HPJnNKpIXh0SxNDYyTAyUtnq9KxNNZJWQszynsWVx4Y"
-respect_dnt = true
-redact = ["prompt", "system_prompt", "response", "file_path", "url"]
-geoip_enabled = true
-dry_mode_enabled = false
-verbose_enabled = false
-user_id = ""
+# ──────────────────────────────────────────────────────────────────────────────
+# PostHog Configuration (Event tracking + AI span tracing)
+# ──────────────────────────────────────────────────────────────────────────────
+
+[posthog]
+mode = "off" # Values: "off" | "anonymous" | "identified"
+# user_id = "your_user_id" # Required when mode = "identified"
+endpoint = "${POSTHOG_ENDPOINT}" # Default: https://us.i.posthog.com (or https://eu.i.posthog.com for EU)
+api_key = "${POSTHOG_API_KEY}" # Get from PostHog Project Settings
+geoip = true # Enable GeoIP lookup
+debug = false # Enable PostHog debug mode
+redact_properties = [
+ "prompt",
+ "system_prompt",
+ "response",
+ "file_path",
+ "url",
+] # Event properties to redact
+
+# AI span tracing to YOUR PostHog (does NOT affect Langfuse/OTLP - they receive full data)
+[posthog.tracing]
+enabled = false # Send AI spans to your PostHog
+
+# Privacy controls for data sent to YOUR PostHog only
+[posthog.tracing.capture]
+content = false # Capture prompt/completion content
+# content_max_length = 1000 # Max length for captured content (omit for unlimited)
+pipe_codes = false # Include pipe codes in span names/attributes
+output_class_names = false # Include output class names in span names/attributes
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Langfuse Integration
+# Note: Langfuse receives FULL span data (no redaction)
+# ──────────────────────────────────────────────────────────────────────────────
+
+[langfuse]
+enabled = false
+# endpoint = "https://cloud.langfuse.com" # Override for self-hosted Langfuse
+# public_key = "${LANGFUSE_PUBLIC_KEY}" # Langfuse public key
+# secret_key = "${LANGFUSE_SECRET_KEY}" # Langfuse secret key
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Additional OTLP Exporters (array for multiple)
+# Note: OTLP exporters receive FULL span data (no redaction)
+# ──────────────────────────────────────────────────────────────────────────────
+
+# [[otlp]]
+# name = "my-collector" # Identifier for logging
+# endpoint = "https://..." # OTLP endpoint URL
+# headers = { Authorization = "Bearer ${OTLP_AUTH_TOKEN}" } # Headers for OTLP export
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Custom Telemetry Allowed Modes
+# Controls which integration modes can use custom telemetry settings above.
+# ──────────────────────────────────────────────────────────────────────────────
+
+[custom_telemetry_allowed_modes]
+ci = false # CI environments don't use custom telemetry
+cli = true # CLI usage allows custom telemetry
+docker = true # Docker deployments allow custom telemetry
+fastapi = true # FastAPI integrations allow custom telemetry
+mcp = true # MCP integrations allow custom telemetry
+n8n = true # n8n integrations allow custom telemetry
+pytest = false # Tests don't use custom telemetry
+python = false # Direct Python SDK usage doesn't use custom telemetry by default
diff --git a/.windsurfrules.md b/.windsurfrules.md
index 211d85f6e..c9b8a4ea2 100644
--- a/.windsurfrules.md
+++ b/.windsurfrules.md
@@ -107,6 +107,7 @@ This document outlines the core coding standards, best practices, and quality co
### Enums and tests
- When defining enums related to string values, always inherit from `StrEnum`
+ - When you need the enum value as a string, don't use `str(enum_var)` or `enum_var.value`, just use `enum_var` itself, that is the point of using StrEnum!
- Never test equality to an enum value: use match/case, even to single out 1 case out of 10 cases. To avoid heavy match/case code in awkward places, add methods to the enum class such as `is_foobar()`. This is to avoid bugs: when new enum values are added we want the linter to complain. Use the `|` operator to group cases
- As our match/case constructs over enums are always exhaustive, NEVER add a default `case _: ...`. Otherwise, you won't pass linting.
- `StrEnum` must be imported from `pipelex.types` (handles python retrocompatibility):
@@ -114,6 +115,10 @@ This document outlines the core coding standards, best practices, and quality co
from pipelex.types import StrEnum
```
+### Optionals
+
+- Don't write things like `a = b if b else c`, write `a = b or c` instead.
+
### Imports
#### **Imports at the top of the file**
@@ -281,7 +286,6 @@ class TestFooBar:
- Never more than 1 class per test module.
- When testing one method, if possible, limit the number of test functions, but with different test cases in parameters
-- Sometimes it can be convenient to access the test's name in its body, for instance to include into a job_id. To achieve that, add the argument `request: FixtureRequest` into the signature and then you can get the test name using `cast(str, request.node.originalname), # type: ignore`.
#### Test Data Organization
diff --git a/AGENTS.md b/AGENTS.md
index 1456cbe11..051c86aee 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -8,7 +8,7 @@
After making code changes, you must always lint using `make check`.
```bash
- make check
+ make format lint pyright mypy check-unused-imports check-config-sync check-rules pylint
# If the current system doesn't have the `make` command, lookup the "check" target in the Makefile and run the command manually.
```
@@ -16,6 +16,7 @@
- Pyright: Static type checking
- Ruff: Fast Python linter
- Mypy: Static type checker
+ - Other checks
Always fix any issues reported by these tools before proceeding.
@@ -77,6 +78,7 @@ This document outlines the core coding standards, best practices, and quality co
### Enums and tests
- When defining enums related to string values, always inherit from `StrEnum`
+ - When you need the enum value as a string, don't use `str(enum_var)` or `enum_var.value`, just use `enum_var` itself, that is the point of using StrEnum!
- Never test equality to an enum value: use match/case, even to single out 1 case out of 10 cases. To avoid heavy match/case code in awkward places, add methods to the enum class such as `is_foobar()`. This is to avoid bugs: when new enum values are added we want the linter to complain. Use the `|` operator to group cases
- As our match/case constructs over enums are always exhaustive, NEVER add a default `case _: ...`. Otherwise, you won't pass linting.
- `StrEnum` must be imported from `pipelex.types` (handles python retrocompatibility):
@@ -84,6 +86,10 @@ This document outlines the core coding standards, best practices, and quality co
from pipelex.types import StrEnum
```
+### Optionals
+
+- Don't write things like `a = b if b else c`, write `a = b or c` instead.
+
### Imports
#### **Imports at the top of the file**
@@ -251,7 +257,6 @@ class TestFooBar:
- Never more than 1 class per test module.
- When testing one method, if possible, limit the number of test functions, but with different test cases in parameters
-- Sometimes it can be convenient to access the test's name in its body, for instance to include into a job_id. To achieve that, add the argument `request: FixtureRequest` into the signature and then you can get the test name using `cast(str, request.node.originalname), # type: ignore`.
#### Test Data Organization
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f26fb2116..bbb805a0a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,20 +2,61 @@
## Unreleased
+**Highlights:**
+
+- **Pipelex Gateway** — The deprecated `pipelex_inference` backend is now replaced by `pipelex_gateway`, featuring remote model configuration fetching so you always have access to the latest models without updating Pipelex.
+
+ **Getting your API key:**
+
+ 1. Join our Discord community at [go.pipelex.com/discord](https://go.pipelex.com/discord)
+ 2. Request your free API key (includes credits for testing and development)
+ 3. Add it to your `.env` file: `PIPELEX_GATEWAY_API_KEY=your-key-here`
+
+ **Accepting the Terms of Service:**
+
+ When you run `pipelex init`, you'll be prompted to accept the Gateway terms of service. By using Pipelex Gateway, telemetry is automatically enabled and identified by your API key (hashed for security) to monitor service quality and enforce fair usage. **We only collect technical data** (model names, token counts, latency, error rates)—never your prompts, completions, or business data. See our [Privacy Policy](https://go.pipelex.com/privacy-policy).
+
+ **⚠️ Migration deadline:** If you were using `pipelex_inference`, please migrate soon—the legacy service will be shut down within a week. Get your new Gateway key at [app.pipelex.com](https://app.pipelex.com/).
+
+- **Pydantic Structure Generation** — New CLI command `pipelex build structures /library_dir/` generates Pydantic models from your concept definitions. This bridges Pipelex's declarative concepts with your Python code, enabling you to receive LLM structured outputs as fully-typed Pydantic objects with IDE autocompletion, validation, and seamless integration into your application logic. The `pipelex build runner` command now automatically generates and imports these structures.
+
### Added
-- Can now generate the pydantic structure of a concept with the cli: `pipelex build structures /library_dir/`.
-- The Pipelex CLI `pipelex build runner` that creates the python file to run a pipe now runs the `structures` build command and then imports those structures in the runner file.
-- Added validation for output concepts of `PipeCompose`: must be strictly compatible with the Text concept.
-- Added validation for the Pipelex Bundle on the concept keys: Cannot create a native concept.
+- New backends & models
+ - **Scaleway** inference provider support for open-source models
+ - **Mistral** Document AI (OCR) via Pipelex Gateway (disclaimer: it's flaky, needs many retries via tenacity)
+ - **Portkey AI** backend integration for unified access to multiple models through a single API key
+ - Mistral Document AI (OCR) via Pipelex Gateway (disclaimer: it's flaky, needs many retries via tenacity)
+- OpenTelemetry-based observability system with native support for Langfuse and OTLP-compatible backends (Datadog, Honeycomb, etc.), configured via `.pipelex/telemetry.toml`
+- Pipelex Gateway service with terms of service management via `.pipelex/pipelex_service.toml` and interactive acceptance flow in `pipelex init`
+- Configurable retry logic with exponential backoff for inference API calls, configurable in `pipelex.toml` under `[cogt.tenacity_config]`
+- Context manager support for the `Pipelex` class (`with Pipelex.make(): ...`) for graceful shutdown
+- Validation for `PipeCompose` output concepts: must be strictly compatible with the Text concept
+- Validation for Pipelex Bundle concept keys: cannot create a native concept
### Changed
-- The Pipelex cli for the `runner`, `structures`, and `inputs` commands now accept a `--output-dir` option to specify the output directory, by default it in the `target_dir`
+- **`pipelex_inference` replaced by `pipelex_gateway`** with remote model configuration fetching for always-current model support
+ - New environment variable `PIPELEX_GATEWAY_API_KEY`
+ - Default routing profiles updated from `pipelex_first` to `pipelex_gateway_first` with automatic migration in `pipelex init`
+- Telemetry system split into two streams:
+ 1. Pipelex Gateway telemetry for service monitoring (never collects prompts/completions/business data)
+ 2. Custom telemetry to user-configured backends
+- `pipelex init` now creates a documented `telemetry.toml` template instead of prompting for preferences
+- Model catalog updated with latest models (gpt-5.1, claude-4.5-opus, gemini-3.0-pro, etc.) and updated waterfalls in `base_deck.toml`
+- Model constraints refactored from simple lists to structured `valued_constraints` dictionaries (e.g., `valued_constraints = { fixed_temperature = 1 }`)
+- New OpenAI Responses API implemented—now differentiates between `openai_completions` and `openai_responses`
+- CLI commands refactored to use centralized `Pipelex` initialization factory for improved error handling
+- `pipelex doctor` command enhanced to detect outdated `telemetry.toml` formats and suggest fixes
+- The `runner`, `structures`, and `inputs` CLI commands now accept `--output-dir` option (defaults to `target_dir`)
+
+### Deprecated
+
+- `pipelex_inference` backend in favor of `pipelex_gateway` (marked as "🛑 Legacy" in configuration template)
### Refactored
-- Refactored the `ConceptFactory.make_from_blueprint` method: Now it correctly handles native concepts.
+- `ConceptFactory.make_from_blueprint` method now correctly handles native concepts
## [v0.17.3] - 2025-12-01
diff --git a/CLAUDE.md b/CLAUDE.md
index 211d85f6e..c9b8a4ea2 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -107,6 +107,7 @@ This document outlines the core coding standards, best practices, and quality co
### Enums and tests
- When defining enums related to string values, always inherit from `StrEnum`
+ - When you need the enum value as a string, don't use `str(enum_var)` or `enum_var.value`, just use `enum_var` itself, that is the point of using StrEnum!
- Never test equality to an enum value: use match/case, even to single out 1 case out of 10 cases. To avoid heavy match/case code in awkward places, add methods to the enum class such as `is_foobar()`. This is to avoid bugs: when new enum values are added we want the linter to complain. Use the `|` operator to group cases
- As our match/case constructs over enums are always exhaustive, NEVER add a default `case _: ...`. Otherwise, you won't pass linting.
- `StrEnum` must be imported from `pipelex.types` (handles python retrocompatibility):
@@ -114,6 +115,10 @@ This document outlines the core coding standards, best practices, and quality co
from pipelex.types import StrEnum
```
+### Optionals
+
+- Don't write things like `a = b if b else c`, write `a = b or c` instead.
+
### Imports
#### **Imports at the top of the file**
@@ -281,7 +286,6 @@ class TestFooBar:
- Never more than 1 class per test module.
- When testing one method, if possible, limit the number of test functions, but with different test cases in parameters
-- Sometimes it can be convenient to access the test's name in its body, for instance to include into a job_id. To achieve that, add the argument `request: FixtureRequest` into the signature and then you can get the test name using `cast(str, request.node.originalname), # type: ignore`.
#### Test Data Organization
diff --git a/Makefile b/Makefile
index f47291b81..179d669cb 100644
--- a/Makefile
+++ b/Makefile
@@ -58,8 +58,10 @@ make rules - Install agent rules for contributing to Pipelex
make up-kit-configs - Update kit configs from .pipelex/
make ukc - Shorthand -> up-kit-configs
make check-config-sync - Verify .pipelex and pipelex/kit/configs are in sync
-make check-rules - Verify installed agent rules match kit templates
make ccs - Shorthand -> check-config-sync
+make check-rules - Verify installed agent rules match kit templates
+make check-urls - Check all URLs in pipelex/urls.py for broken links (quiet)
+make cu - Check URLs with verbose output (shows details)
make cleanenv - Remove virtual env and lock files
make cleanderived - Remove extraneous compiled files, caches, logs, etc.
@@ -114,7 +116,7 @@ export HELP
.PHONY: \
all help env lock install update build \
format lint pyright mypy pylint \
- rules up-kit-configs ukc check-config-sync check-rules ccs \
+ rules up-kit-configs ukc check-config-sync ccs check-rules check-urls cu \
cleanderived cleanenv cleanall \
test test-xdist t test-quiet tq test-with-prints tp test-inference ti \
test-llm tl test-img-gen tg test-extract te codex-tests gha-tests \
@@ -184,9 +186,17 @@ check-rules: env
$(call PRINT_TITLE,"Checking installed agent rules against templates")
$(VENV_PIPELEX_DEV) check-rules --quiet
+check-urls: env
+ $(call PRINT_TITLE,"Checking URLs in pipelex/urls.py for broken links")
+ $(VENV_PIPELEX_DEV) check-urls --quiet
+
+cu: env
+ $(call PRINT_TITLE,"Checking URLs in pipelex/urls.py for broken links with detailed output")
+ $(VENV_PIPELEX_DEV) check-urls
+
up-kit-configs:
$(call PRINT_TITLE,"Updating kit configs from .pipelex/")
- @rsync -av --delete .pipelex/ pipelex/kit/configs/
+ @rsync -av --delete --exclude='pipelex_service.toml' .pipelex/ pipelex/kit/configs/
ukc: up-kit-configs
@echo "> done: ukc = up-kit-configs"
@@ -550,7 +560,7 @@ c: format lint pyright mypy
cc: cleanderived c
@echo "> done: cc = cleanderived format lint pyright pylint mypy"
-check: cc check-unused-imports ccs check-rules pylint
+check: cc check-unused-imports check-config-sync check-rules check-urls pylint
@echo "> done: check"
v: validate
diff --git a/README.md b/README.md
index e824025ac..1602c65dd 100644
--- a/README.md
+++ b/README.md
@@ -49,7 +49,7 @@ To use AI models, you need an API key:
- **Bring your own API keys**: OpenAI, Anthropic, Google, Mistral
- **Local AI**: Ollama, vLLM, LM Studio, llama.cpp... any endpoint based on the OpenAI API or not, as you can plug-in your own non-standard APIs.
-See [Configure AI Providers](https://docs.pipelex.com/pages/setup/configure-ai-providers/) for details.
+See [Configure AI Providers](https://docs.pipelex.com/home/5-setup/configure-ai-providers/) for details.
## 3. Generate Your First Workflow
@@ -318,9 +318,9 @@ Each pipe processes information using **Concepts** (typing with meaning) to ensu
## 📖 Next Steps
**Learn More:**
-- [Writing Workflows Tutorial](https://docs.pipelex.com/pages/writing-workflows/) - Complete guide with examples
-- [Build Reliable AI Workflows](https://docs.pipelex.com/pages/build-reliable-ai-workflows-with-pipelex/kick-off-a-pipelex-workflow-project/) - Deep dive into Pipelex
-- [Configuration Guide](https://docs.pipelex.com/pages/setup/configure-ai-providers/) - Set up AI providers and models
+- [Design and Run Pipelines](https://docs.pipelex.com/home/6-build-reliable-ai-workflows/pipes/) - Complete guide with examples
+- [Kick off a Pipeline Project](https://docs.pipelex.com/home/6-build-reliable-ai-workflows/kick-off-a-pipelex-workflow-project/) - Deep dive into Pipelex
+- [Configure AI Providers](https://docs.pipelex.com/home/5-setup/configure-ai-providers/) - Set up AI providers and models
## 🔧 IDE Extension
@@ -361,7 +361,7 @@ Pipelex collects optional, anonymous usage data to help improve the product. On
Your prompts, LLM responses, file paths, and URLs are automatically redacted and never transmitted. You can change your preference at any time or disable telemetry completely by setting the `DO_NOT_TRACK` environment variable.
-For more details, see the [Telemetry Documentation](https://docs.pipelex.com/pages/setup/telemetry/) or read our [Privacy Policy](https://www.pipelex.com/privacy-policy).
+For more details, see the [Telemetry Documentation](https://docs.pipelex.com/home/5-setup/telemetry/) or read our [Privacy Policy](https://go.pipelex.com/privacy-policy).
## 🤝 Contributing
diff --git a/docs/home/2-get-started/pipe-builder.md b/docs/home/2-get-started/pipe-builder.md
index 124498de1..94665b4d1 100644
--- a/docs/home/2-get-started/pipe-builder.md
+++ b/docs/home/2-get-started/pipe-builder.md
@@ -15,8 +15,8 @@ pipelex init
To use AI models, you need API key(s):
-- The `PIPELEX_INFERENCE_API_KEY` key provides access to all the AI models. To get your key, join our [Discord community](https://go.pipelex.com/discord), then request your **free API key** (no credit card required, limited time offer) in the [🔑・free-api-key](https://discord.com/channels/1369447918955921449/1418228010431025233) channel.
-- You can also use other AI routing services like [BlackBox AI](https://docs.blackbox.ai/), or you can bring your own API keys (OpenAI, Anthropic, Google, Mistral, etc.), or run local AI (no key needed).
+- The `PIPELEX_GATEWAY_API_KEY` key provides access to all the AI models. To get your key, join our [Discord community](https://go.pipelex.com/discord), then request your **free API key** (no credit card required, limited time offer) in the [🔑・free-api-key](https://discord.com/channels/1369447918955921449/1418228010431025233) channel.
+- You can also use other AI routing services like [BlackBox AI](https://docs.blackbox.ai/) or [Portkey](https://portkey.ai/), or you can bring your own API keys (OpenAI, Anthropic, Google, Mistral, etc.), or run local AI (no key needed).
See [Configure AI Providers](../../home/5-setup/configure-ai-providers.md) for details. If you are using non-standard APIs, that's OK too, don't hesitate to join our [Discord](https://go.pipelex.com/discord) for guidance, Pipelex provides dependency injections for the API portals, [See here for more information](../10-advanced-customizations/plugin-injection.md)
# Generate workflows with Pipe Builder
diff --git a/docs/home/5-setup/configure-ai-providers.md b/docs/home/5-setup/configure-ai-providers.md
index d390a8290..e7156e7db 100644
--- a/docs/home/5-setup/configure-ai-providers.md
+++ b/docs/home/5-setup/configure-ai-providers.md
@@ -4,31 +4,51 @@
To run pipelines with LLMs, you need to configure API access. **You have three options** - choose what works best for you:
-### Option 1: Pipelex Inference (Easiest for Getting Started)
+### Option 1: Pipelex Gateway (Easiest for Getting Started)
-Get **free credits** for testing and development with a single API key that works with all major LLM providers:
+Get **free credits** for testing and development with a single API key that works with all major LLM providers. Unlock the **full power of Pipelex** with many models already available and new ones being added constantly.
**Benefits:**
- No credit card required
-- Access to OpenAI, Anthropic Claude, Google Gemini, and xAI Grok
+- Access to OpenAI, Anthropic Claude, Google Gemini, xAI Grok, and more
+- New models added constantly
- Perfect for development and testing
- Single API key for all models
**Setup:**
1. Join our Discord community to get your free API key:
-
-- Visit [https://go.pipelex.com/discord](https://go.pipelex.com/discord)
-- Request your key in the appropriate channel
+
+ - Visit [https://go.pipelex.com/discord](https://go.pipelex.com/discord)
+ - Request your key in the appropriate channel
2. Create a `.env` file in your project root:
- ```env
- PIPELEX_INFERENCE_API_KEY=your-key-here
- ```
+
+ ```env
+ PIPELEX_GATEWAY_API_KEY=your-key-here
+ ```
+
+3. Run `pipelex init` and accept the Gateway terms of service when prompted.
That's it! Your pipelines can now access any supported LLM.
+!!! info "Terms of Service & Telemetry"
+ When using Pipelex Gateway, you'll be prompted to accept our terms of service. By using the Gateway, identified telemetry is automatically enabled (tied to your hashed API key) to help us monitor service quality and enforce fair usage.
+
+ **We collect only technical data** (model names, token counts, latency, error rates). We do **NOT** collect your prompts, completions, or business data. See our [Privacy Policy](https://go.pipelex.com/privacy-policy) for details.
+
+!!! note "Migration from pipelex_inference"
+ If you were using the deprecated `pipelex_inference` backend, migrate to `pipelex_gateway`:
+
+ 1. **Get your new Gateway API key**:
+ - If you had a `pipelex_inference` key: get your new key at [app.pipelex.com](https://app.pipelex.com/)
+ - New users: join our [Discord](https://go.pipelex.com/discord) and request a free key with credits
+ 2. Update your `.env`: set `PIPELEX_GATEWAY_API_KEY` with your new key
+ 3. Run `pipelex init` and accept the Gateway terms
+
+ The `pipelex_inference` backend is deprecated and will be removed in a future release.
+
### Option 2: Bring Your Own API Keys
Use your existing API keys from LLM providers. This is ideal if you:
@@ -36,6 +56,7 @@ Use your existing API keys from LLM providers. This is ideal if you:
- Already have API keys from providers
- Need to use specific accounts for billing
- Have negotiated rates or enterprise agreements
+- Prefer not to send any telemetry to Pipelex servers
**Setup:**
@@ -78,21 +99,22 @@ You only need to add keys for the providers you plan to use.
When using your own keys, enable the corresponding backends:
1. Initialize configuration:
- ```bash
- pipelex init config
- ```
+
+ ```bash
+ pipelex init config
+ ```
2. Edit `.pipelex/inference/backends.toml`:
-```toml
-[google]
-enabled = true
+ ```toml
+ [google]
+ enabled = true
-[openai]
-enabled = true
+ [openai]
+ enabled = true
-# Enable any providers you have keys for
-```
+ # Enable any providers you have keys for
+ ```
See [Inference Backend Configuration](../../home/7-configuration/config-technical/inference-backend-config.md) for all options.
@@ -132,9 +154,11 @@ pipelex init config
```
This creates a `.pipelex/` directory with:
+
```
.pipelex/
├── pipelex.toml # Feature flags, logging, cost reporting
+├── telemetry.toml # Custom telemetry configuration
└── inference/ # LLM configuration and model presets
├── backends.toml # Enable/disable model providers
├── deck/
@@ -157,4 +181,3 @@ Now that you have your backend configured:
!!! tip "Advanced Configuration"
For detailed backend configuration options, see [Inference Backend Configuration](../../home/7-configuration/config-technical/inference-backend-config.md).
-
diff --git a/docs/home/5-setup/telemetry.md b/docs/home/5-setup/telemetry.md
index a9e7ce433..23e7f947c 100644
--- a/docs/home/5-setup/telemetry.md
+++ b/docs/home/5-setup/telemetry.md
@@ -1,81 +1,106 @@
# Telemetry
-## What is Telemetry?
+Pipelex supports two independent telemetry streams that serve different purposes. Understanding how they work helps you make informed decisions about data collection.
-Pipelex collects optional, anonymous usage data to help improve the product. This helps us understand how Pipelex is being used and identify areas for improvement.
+## Two Telemetry Streams
-## First Run Experience
+### 1. Gateway Telemetry (Pipelex-Controlled)
-When you run most Pipelex commands for the first time (after running `pipelex init`), you'll be prompted to configure your telemetry preferences:
+When you use **Pipelex Gateway** as your inference backend, identified telemetry is **automatically enabled**. This telemetry is tied to your Gateway API key (hashed for security) and operates independently from your `telemetry.toml` settings.
-```
-======================================================================
-Telemetry Configuration
-======================================================================
+**What we collect:**
-Pipelex can collect anonymous usage data to help improve the product.
+- Model names used (e.g., `gpt-4o`, `claude-3.7-sonnet`) and parameters
+- Pipe types (e.g., `PipeLLM`, `PipeSequence`, etc.)
+- Token counts (input/output)
+- Latency metrics
+- Error rates (without error details)
-Please choose your telemetry preference:
- [1] off - No telemetry data collected
- [2] anonymous - Anonymous usage data only
- [3] identified - Usage data with user identification
- [q] quit - Exit without configuring
+**What we do NOT collect:**
-Enter your choice:
-```
+- Your prompts or completions
+- Your pipe codes or output class names
+- File contents or business data
+
+This telemetry allows us to:
+
+- Monitor and improve service quality
+- Enforce fair usage limits and prevent abuse
+- Provide you with usage insights and better support
+
+!!! info "Gateway Telemetry is Optional"
+ Using Pipelex Gateway is entirely optional. If you prefer not to send telemetry to Pipelex servers, simply use your own API keys with direct provider backends (OpenAI, Anthropic, Azure, Bedrock, etc.).
+
+### 2. Custom Telemetry (User-Controlled)
-## Telemetry Modes
+Custom telemetry is configured in `.pipelex/telemetry.toml` and allows you to send observability data to **your own** analytics and monitoring systems:
-### Off
+- **PostHog**: Event tracking and AI span tracing with privacy controls
+- **Langfuse**: Full LLM observability (receives full span data)
+- **OTLP**: Send spans to any OpenTelemetry-compatible backend (receives full span data)
-No telemetry data is collected. Pipelex will not send any data to our servers.
+Custom telemetry is completely independent from Gateway telemetry—you can use both, either, or neither.
-### Anonymous
+## Quick Setup
-Anonymous usage data only. This includes:
+When you run `pipelex init`, a default `telemetry.toml` configuration file is created:
-- Command usage (which commands are run)
-- Pipeline execution statistics (success/failure rates, performance metrics)
-- Feature usage patterns
+```bash
+pipelex init telemetry
+```
+
+This creates `.pipelex/telemetry.toml` with all options disabled by default. Edit this file to enable your preferred telemetry destinations.
-This mode does **not** include:
+### Example: Enable PostHog Tracing
-- Personal identification
-- Your prompts or system prompts
-- LLM responses
-- File paths or URLs
-- Any sensitive information
+```toml
+[posthog]
+mode = "anonymous" # or "identified" with user_id
+endpoint = "${POSTHOG_ENDPOINT}"
+api_key = "${POSTHOG_API_KEY}"
-### Identified
+[posthog.tracing]
+enabled = true
-Same as anonymous mode, but includes a user identifier. This helps us provide better support and understand user journeys across sessions.
+[posthog.tracing.capture]
+content = false # Don't capture prompts/completions
+pipe_codes = true # Include pipe codes in span names
+```
+
+### Example: Enable Langfuse
-If you choose this mode, you can optionally provide a `user_id` in the configuration file.
+```toml
+[langfuse]
+enabled = true
+public_key = "${LANGFUSE_PUBLIC_KEY}"
+secret_key = "${LANGFUSE_SECRET_KEY}"
+```
-## DO_NOT_TRACK Support
+## DO_NOT_TRACK Global Override
-Pipelex respects the `DO_NOT_TRACK` environment variable. If you have `DO_NOT_TRACK` set in your environment (to any value except `false` or `0`), telemetry will be automatically disabled regardless of your configuration settings.
+The `DO_NOT_TRACK` environment variable provides a universal way to disable **all** telemetry:
```bash
-# Disable telemetry via environment variable
export DO_NOT_TRACK=1
```
-## Changing Your Settings
+When set, this disables:
-You can change your telemetry settings at any time:
+- Gateway telemetry (but note: Gateway won't work without telemetry)
+- All custom telemetry destinations
-1. **Via configuration file**: Edit `.pipelex/telemetry.toml` directly (see [Telemetry Configuration](../../home/7-configuration/config-practical/telemetry-config.md))
-2. **Trigger the prompt again**: Delete `.pipelex/telemetry.toml`, and the prompt will appear next time you run a command
+!!! warning "Gateway Requires Telemetry"
+ If you set `DO_NOT_TRACK=1` while using Pipelex Gateway, the Gateway will not function. Use direct provider backends instead if you need to disable all telemetry.
## Privacy
We take your privacy seriously:
-- Sensitive data (prompts, responses, file paths, URLs) is automatically redacted
-- You have full control over what level of telemetry you're comfortable with
+- **Gateway telemetry** never collects prompts, completions, or business data
+- **Custom telemetry** gives you full control over what data is captured
+- PostHog tracing includes privacy controls to redact sensitive content
- All telemetry can be completely disabled
-- Our telemetry infrastructure uses PostHog, hosted in the EU
For detailed configuration options, see [Telemetry Configuration](../../home/7-configuration/config-practical/telemetry-config.md).
+For more information about our data practices, see our [Privacy Policy](https://go.pipelex.com/privacy-policy).
diff --git a/docs/home/7-configuration/config-practical/telemetry-config.md b/docs/home/7-configuration/config-practical/telemetry-config.md
index e29fd7bee..5ed8bd1b5 100644
--- a/docs/home/7-configuration/config-practical/telemetry-config.md
+++ b/docs/home/7-configuration/config-practical/telemetry-config.md
@@ -2,9 +2,15 @@
## Overview
-Telemetry configuration is stored in `.pipelex/telemetry.toml`, separate from the main `pipelex.toml` configuration. This file is created automatically the first time you run a Pipelex command (after `pipelex init config`) and are prompted to choose your telemetry preference.
+Telemetry configuration is stored in `.pipelex/telemetry.toml`. This file controls **your custom telemetry** destinations—where you want to send observability data for your own analytics and monitoring.
-For a user-friendly introduction to telemetry, see [Telemetry Setup](../../../home/5-setup/telemetry.md).
+!!! info "Two Telemetry Streams"
+ Pipelex has two independent telemetry streams:
+
+ 1. **Gateway Telemetry** (Pipelex-controlled): Automatic when using Pipelex Gateway, tied to your API key
+ 2. **Custom Telemetry** (User-controlled): Configured in this file, sent to your own backends
+
+ For an overview, see [Telemetry Setup](../../../home/5-setup/telemetry.md).
## Configuration File Location
@@ -12,153 +18,213 @@ For a user-friendly introduction to telemetry, see [Telemetry Setup](../../../ho
.pipelex/telemetry.toml
```
-This file is created in the `.pipelex` directory at your project root.
-
-## Configuration Options
+This file is created when you run `pipelex init telemetry` or `pipelex init`.
-### Example Configuration
+## Full Example Configuration
```toml
-telemetry_mode = "off"
-host = "https://eu.i.posthog.com"
-project_api_key = "phc_HPJnNKpIXh0SxNDYyTAyUtnq9KxNNZJWQszynsWVx4Y"
-respect_dnt = true
-redact = ["prompt", "system_prompt", "response", "file_path", "url"]
-geoip_enabled = true
-dry_mode_enabled = false
-verbose_enabled = false
-user_id = ""
+# PostHog Configuration (Event tracking + AI span tracing)
+[posthog]
+mode = "anonymous" # "off" | "anonymous" | "identified"
+# user_id = "your_user_id" # Required when mode = "identified"
+endpoint = "${POSTHOG_ENDPOINT}" # Default: https://us.i.posthog.com
+api_key = "${POSTHOG_API_KEY}" # Get from PostHog Project Settings
+geoip = true # Enable GeoIP lookup
+debug = false # Enable PostHog debug mode
+redact_properties = [
+ "prompt",
+ "system_prompt",
+ "response",
+ "file_path",
+ "url",
+] # Event properties to redact
+
+# AI span tracing to YOUR PostHog
+[posthog.tracing]
+enabled = true # Send AI spans to your PostHog
+
+# Privacy controls for data sent to YOUR PostHog only
+[posthog.tracing.capture]
+content = false # Capture prompt/completion content
+content_max_length = 1000 # Max length for captured content
+pipe_codes = true # Include pipe codes in span names
+output_class_names = true # Include output class names in spans
+
+# Langfuse Integration (receives FULL span data, no redaction)
+[langfuse]
+enabled = true
+endpoint = "https://cloud.langfuse.com" # Override for self-hosted Langfuse
+public_key = "${LANGFUSE_PUBLIC_KEY}"
+secret_key = "${LANGFUSE_SECRET_KEY}"
+
+# Additional OTLP Exporters (array, receives FULL span data)
+[[otlp]]
+name = "my-collector" # Identifier for logging
+endpoint = "https://otel.example.com/v1/traces" # OTLP endpoint URL
+headers = { Authorization = "Bearer ${OTLP_AUTH_TOKEN}" }
```
-### Settings Reference
+---
+
+## PostHog Configuration
+
+The `[posthog]` section configures event tracking and optional AI span tracing to your own PostHog instance.
-#### `telemetry_mode`
+### `[posthog]` Settings
-- **Type**: `string`
-- **Default**: `"off"`
-- **Allowed values**: `"off"`, `"anonymous"`, `"identified"`
-- **Description**: Controls the telemetry collection mode.
- - `"off"`: No telemetry data is collected
- - `"anonymous"`: Anonymous usage data only (no user identification)
- - `"identified"`: Usage data with user identification (requires `user_id` to be set)
+| Setting | Type | Default | Description |
+|---------|------|---------|-------------|
+| `mode` | string | `"off"` | Telemetry mode: `"off"`, `"anonymous"`, or `"identified"` |
+| `user_id` | string | (none) | Required when `mode = "identified"` |
+| `endpoint` | string | `"https://us.i.posthog.com"` | PostHog endpoint URL |
+| `api_key` | string | (required) | Your PostHog project API key |
+| `geoip` | boolean | `true` | Enable GeoIP lookup for location data |
+| `debug` | boolean | `false` | Log events locally without sending |
+| `redact_properties` | array | `[]` | Event properties to redact before sending |
-#### `host`
+#### Mode Options
-- **Type**: `string`
-- **Default**: `"https://eu.i.posthog.com"`
-- **Description**: The PostHog server host URL. We use the EU-hosted instance for privacy compliance.
+- **`"off"`**: No events sent to your PostHog
+- **`"anonymous"`**: Events sent without user identification
+- **`"identified"`**: Events sent with your `user_id` for cross-session tracking
-**Note**: This is typically not changed unless you're self-hosting PostHog.
+### `[posthog.tracing]` Settings
-#### `project_api_key`
+Controls AI span tracing to your PostHog instance.
-- **Type**: `string`
-- **Default**: `"phc_HPJnNKpIXh0SxNDYyTAyUtnq9KxNNZJWQszynsWVx4Y"`
-- **Description**: The PostHog project API key for the Pipelex telemetry project.
+| Setting | Type | Default | Description |
+|---------|------|---------|-------------|
+| `enabled` | boolean | `false` | Send AI spans to your PostHog |
-**Note**: This is typically not changed unless you're using a custom telemetry backend.
+### `[posthog.tracing.capture]` Settings
-#### `respect_dnt`
+Privacy controls for what data is included in spans sent to **your** PostHog.
-- **Type**: `boolean`
-- **Default**: `true`
-- **Description**: When `true`, Pipelex respects the `DO_NOT_TRACK` environment variable. If `DO_NOT_TRACK` is set to any value except `false` or `0`, telemetry is automatically disabled.
+| Setting | Type | Default | Description |
+|---------|------|---------|-------------|
+| `content` | boolean | `false` | Capture prompt/completion content |
+| `content_max_length` | integer | (unlimited) | Max length for captured content |
+| `pipe_codes` | boolean | `false` | Include pipe codes in span names/attributes |
+| `output_class_names` | boolean | `false` | Include output class names in spans |
-#### `redact`
+!!! warning "Privacy Note"
+ These capture settings only affect data sent to **your** PostHog. Langfuse and OTLP exporters always receive full span data without redaction.
-- **Type**: `array` of `string`
-- **Default**: `["prompt", "system_prompt", "response", "file_path", "url"]`
-- **Description**: List of event properties to redact from telemetry data. These sensitive fields are automatically filtered out before any data is sent.
+---
-**Privacy protection**: This ensures that your actual prompts, LLM responses, and file paths are never transmitted to telemetry servers.
+## Langfuse Configuration
-#### `debug`
+The `[langfuse]` section enables integration with [Langfuse](https://langfuse.com/) for LLM observability.
-- **Type**: `boolean`
-- **Default**: `false`
-- **Description**: When `true`, telemetry events are logged locally but not actually sent to PostHog. Useful for debugging telemetry implementation.
+| Setting | Type | Default | Description |
+|---------|------|---------|-------------|
+| `enabled` | boolean | `false` | Enable Langfuse integration |
+| `endpoint` | string | `"https://cloud.langfuse.com"` | Langfuse endpoint (override for self-hosted) |
+| `public_key` | string | (required if enabled) | Langfuse public key |
+| `secret_key` | string | (required if enabled) | Langfuse secret key |
-#### `user_id`
+!!! info "Full Data"
+ Langfuse receives **full span data** including prompts, completions, and all metadata. There is no redaction applied.
-- **Type**: `string`
-- **Default**: `""`
-- **Description**: User identifier for the `"identified"` telemetry mode. If `telemetry_mode` is set to `"identified"` but `user_id` is empty, telemetry falls back to anonymous mode.
+---
-**Usage**: Set this to your email, username, or any identifier you prefer when using identified mode.
+## OTLP Exporters Configuration
-## Manually Changing Settings
+The `[[otlp]]` section is an **array** that allows you to configure multiple OpenTelemetry Protocol exporters.
-Edit `.pipelex/telemetry.toml` directly. Changes take effect on the next command run.
+| Setting | Type | Default | Description |
+|---------|------|---------|-------------|
+| `name` | string | (required) | Identifier for logging |
+| `endpoint` | string | (required) | OTLP endpoint URL |
+| `headers` | object | `{}` | HTTP headers for authentication |
+
+### Example: Multiple OTLP Exporters
```toml
-telemetry_mode = "off" # Disable telemetry
-telemetry_mode = "anonymous" # Enable anonymous telemetry
+[[otlp]]
+name = "datadog"
+endpoint = "https://trace.agent.datadoghq.com/v1/traces"
+headers = { "DD-API-KEY" = "${DD_API_KEY}" }
+
+[[otlp]]
+name = "honeycomb"
+endpoint = "https://api.honeycomb.io/v1/traces"
+headers = { "x-honeycomb-team" = "${HONEYCOMB_API_KEY}" }
```
-### Example: Enable Identified Telemetry
+!!! info "Full Data"
+ OTLP exporters receive **full span data** including prompts, completions, and all metadata. There is no redaction applied.
+
+---
+
+## Environment Variable Substitution
+
+All string values in `telemetry.toml` support environment variable substitution using the `${VAR_NAME}` syntax:
```toml
-telemetry_mode = "identified"
-user_id = "[email protected]"
+[posthog]
+endpoint = "${POSTHOG_ENDPOINT}"
+api_key = "${POSTHOG_API_KEY}"
+
+[langfuse]
+public_key = "${LANGFUSE_PUBLIC_KEY}"
+secret_key = "${LANGFUSE_SECRET_KEY}"
+
+[[otlp]]
+headers = { Authorization = "Bearer ${OTLP_AUTH_TOKEN}" }
```
-## Re-triggering the Configuration Prompt
+This allows you to keep sensitive credentials in environment variables or `.env` files rather than committing them to version control.
-If you want to see the configuration prompt again (for example, to change your choice through the interactive interface), delete the `.pipelex/telemetry.toml` file:
+### Variable Syntax Options
-```bash
-rm .pipelex/telemetry.toml
-```
+| Syntax | Description |
+|--------|-------------|
+| `${VAR_NAME}` | Use secrets provider (default: environment variable) |
+| `${env:VAR_NAME}` | Force environment variable |
+| `${secret:VAR_NAME}` | Force secrets provider |
+| `${env:VAR\|secret:FALLBACK}` | Try env first, then secret as fallback |
-The next time you run a Pipelex command (except `pipelex init`), you'll be prompted to choose your telemetry preference.
+---
-## Environment Variable Override
+## DO_NOT_TRACK Override
-The `DO_NOT_TRACK` environment variable provides a universal way to disable telemetry:
+The `DO_NOT_TRACK` environment variable disables **all** telemetry globally:
```bash
-# Linux/MacOS
+# Linux/macOS
export DO_NOT_TRACK=1
# Windows PowerShell
-$env:DO_NOT_TRACK="1"
+$env:DO_NOT_TRACK = "1"
# Windows CMD
set DO_NOT_TRACK=1
```
-When `respect_dnt = true` (the default), this will disable all telemetry regardless of the `telemetry_mode` setting.
+When set, this disables:
-## What Data is Collected?
+- All custom telemetry (PostHog, Langfuse, OTLP)
+- Gateway telemetry (note: Gateway won't work without telemetry)
-When telemetry is enabled (anonymous or identified mode), Pipelex collects:
+---
-- Whole pipeline execution events (start, success, failure)
-- Each pipe execution events (start, success, failure)
+## Resetting Configuration
-soon to be added:
-- Error types (without error messages)
-- Command usage (which CLI commands are run)
-- Feature usage patterns (which pipe types are used)
-- Performance metrics (execution time, token usage)
+To reset your telemetry configuration to defaults:
-**Never collected** (automatically redacted):
+```bash
+rm .pipelex/telemetry.toml
+pipelex init telemetry
+```
-- Your prompts or system prompts
-- LLM responses
-- File paths
-- URLs
-- Any content from your documents or images
-- Personal data (unless you explicitly set a `user_id` in identified mode)
+---
## Privacy and Compliance
-- Telemetry is **opt-in** via the first-run prompt
-- All sensitive data is **automatically redacted**
-- We use **PostHog** (EU-hosted) for telemetry infrastructure
-- We **respect DO_NOT_TRACK** by default
-- You can **completely disable** telemetry at any time
-- Telemetry configuration is **stored locally** in your project
-
-For more information about our data practices, see our [privacy policy](https://pipelex.com/privacy-policy).
+- **Custom telemetry** gives you full control over what data is captured and where it's sent
+- **PostHog tracing** includes granular privacy controls via the `capture` settings
+- **Langfuse and OTLP** receive full data—configure these only if you're comfortable with that
+- The `DO_NOT_TRACK` environment variable provides a global kill switch
+For more information about our data practices, see our [Privacy Policy](https://go.pipelex.com/privacy-policy).
diff --git a/docs/home/7-configuration/config-technical/cogt-config.md b/docs/home/7-configuration/config-technical/cogt-config.md
index e2ce4b157..53980a522 100644
--- a/docs/home/7-configuration/config-technical/cogt-config.md
+++ b/docs/home/7-configuration/config-technical/cogt-config.md
@@ -35,7 +35,6 @@ is_structure_prompt_enabled = false
# Job configuration
[cogt.llm_config.llm_job_config]
-is_streaming_enabled = false
max_retries = 3 # Between 1 and 10
```
@@ -172,7 +171,6 @@ default_max_images = 100
is_structure_prompt_enabled = false
[cogt.llm_config.llm_job_config]
-is_streaming_enabled = false
max_retries = 3
[cogt.img_gen_config.img_gen_job_config]
diff --git a/docs/home/7-configuration/config-technical/inference-backend-config.md b/docs/home/7-configuration/config-technical/inference-backend-config.md
index 91010ca42..3f7c700d0 100644
--- a/docs/home/7-configuration/config-technical/inference-backend-config.md
+++ b/docs/home/7-configuration/config-technical/inference-backend-config.md
@@ -6,7 +6,7 @@ The Inference Backend Configuration System manages how Pipelex handles AI model
Pipelex supports three flexible approaches for accessing AI models:
-### Option A: Pipelex Inference (Optional & Free)
+### Option A: Pipelex Gateway (Optional & Free)
Get a single API key that works with all major providers (OpenAI, Anthropic, Google, Mistral, FAL, and more). This is the **recommended approach for getting started quickly**.
@@ -15,6 +15,9 @@ Get a single API key that works with all major providers (OpenAI, Anthropic, Goo
- ✅ Automatic model routing
- ✅ Free on Discord (limited time offer)
+!!! note "Terms of Service"
+ Using Pipelex Gateway requires accepting our terms of service. When you run `pipelex init`, you'll be prompted to review and accept the terms. Gateway usage enables identified telemetry (tied to your hashed API key) for service monitoring. See our [Privacy Policy](https://go.pipelex.com/privacy-policy) for details.
+
### Option B: Bring Your Own Keys
Use your own API keys from individual providers for full control and direct billing. Ideal for production deployments with existing provider relationships.
@@ -28,7 +31,7 @@ See [Inference Backends](#inference-backends) section below for configuration.
### Option C: Mix & Match (Custom Routing)
-Configure custom routing profiles to use your own keys for some models and Pipelex Inference for others. This gives you full flexibility to optimize for cost, performance, or rate limits.
+Configure custom routing profiles to use your own keys for some models and Pipelex Gateway for others. This gives you full flexibility to optimize for cost, performance, or rate limits.
- ✅ Hybrid approach
- ✅ Cost optimization
@@ -69,9 +72,9 @@ All inference backend configurations are stored in the `.pipelex/inference/` dir
└── overrides.toml # Custom overrides
```
-## Pipelex Inference (Optional & Free)
+## Pipelex Gateway (Optional & Free)
-Pipelex Inference is a unified inference backend that provides access to all major AI providers through a single API key. This is the **recommended approach for getting started quickly** with Pipelex, and it's **completely optional**.
+Pipelex Gateway is a unified inference backend that provides access to all major AI providers through a single API key. This is the **recommended approach for getting started quickly** with Pipelex and **unlocking its full power**—with many models already available and new ones being added constantly. Using Pipelex Gateway is **completely optional**.
### Benefits
@@ -81,45 +84,76 @@ Pipelex Inference is a unified inference backend that provides access to all maj
- **Automatic Routing**: All AI models (LLMs, OCR, image generation) are automatically routed to their respective providers
- **Unified Interface**: Same configuration system for text generation, OCR, and image generation
+### Terms of Service & Telemetry
+
+Using Pipelex Gateway requires accepting our terms of service. When you enable Gateway and run `pipelex init`, you'll be prompted with a terms panel explaining:
+
+- **What we collect**: Model names, token counts, latency, error rates (technical data only)
+- **What we do NOT collect**: Your prompts, completions, pipe codes, or business data
+- **Why**: To monitor service quality, enforce fair usage, and provide better support
+- **Your choice**: If you decline, Gateway is disabled and you can use direct provider backends instead
+
+Your API key is hashed for security. Gateway telemetry operates independently from your `telemetry.toml` settings. See our [Privacy Policy](https://go.pipelex.com/privacy-policy) for details.
+
### Setup
1. **Get your API key:**
-- Visit [https://go.pipelex.com/discord](https://go.pipelex.com/discord) to join our Discord
-- Request your free API key in the appropriate channel
-- No credit card required (limited time offer)
+
+ - Visit [https://go.pipelex.com/discord](https://go.pipelex.com/discord) to join our Discord
+ - Request your free API key in the appropriate channel
+ - No credit card required (limited time offer)
2. **Configure environment variables:**
- ```bash
- # Copy the example environment file
- cp .env.example .env
-
- # Edit .env and add your Pipelex Inference API key
- # PIPELEX_INFERENCE_API_KEY="your-api-key"
- ```
-3. **Verify backend configuration:**
+ ```bash
+ # Copy the example environment file
+ cp .env.example .env
+
+ # Edit .env and add your Pipelex Gateway API key
+ PIPELEX_GATEWAY_API_KEY="your-api-key"
+ ```
+
+3. **Accept terms and verify configuration:**
+
+ ```bash
+ pipelex init
+ ```
+
+ When prompted, review and accept the Gateway terms of service.
+
+4. **Verify backend configuration:**
- The `pipelex_inference` backend should already be enabled in `.pipelex/inference/backends.toml`:
+ The `pipelex_gateway` backend should be enabled in `.pipelex/inference/backends.toml`:
```toml
- [pipelex_inference]
+ [pipelex_gateway]
+ display_name = "⭐ Pipelex Gateway"
enabled = true
- endpoint = "https://inference.pipelex.com/v1"
- api_key = "${PIPELEX_INFERENCE_API_KEY}"
+ api_key = "${PIPELEX_GATEWAY_API_KEY}"
```
- The environment variable `${PIPELEX_INFERENCE_API_KEY}` will be automatically loaded from your `.env` file.
+ The environment variable `${PIPELEX_GATEWAY_API_KEY}` will be automatically loaded from your environment.
+
+!!! warning "Migrating from pipelex_inference"
+ The `pipelex_inference` backend is **deprecated** and will be removed in a future release. To migrate:
+
+ 1. **Get your new Gateway API key**:
+ - If you had a `pipelex_inference` key: get your new key at [app.pipelex.com](https://app.pipelex.com/)
+ - New users: join our [Discord](https://go.pipelex.com/discord) and request a free key with credits
+ 2. Update your `.env`: set `PIPELEX_GATEWAY_API_KEY` with your new key
+ 3. Run `pipelex init` and accept the Gateway terms
+ 4. Update any routing profiles that reference `pipelex_inference` to use `pipelex_gateway`
4. **Verify routing configuration:**
- The default routing profile in `.pipelex/inference/routing_profiles.toml` should be set to `pipelex_first`:
+ The default routing profile in `.pipelex/inference/routing_profiles.toml` should be set to `pipelex_gateway_first`:
```toml
- active = "pipelex_first"
+ active = "pipelex_gateway_first"
- [profiles.pipelex_first]
- description = "Use Pipelex Inference backend for all its supported models"
- default = "pipelex_inference"
+ [profiles.pipelex_gateway_first]
+ description = "Use Pipelex Gateway backend for all its supported models"
+ default = "pipelex_gateway"
```
### Usage
@@ -130,18 +164,42 @@ Once configured, all models are available through the unified backend. Use stand
[pipe.example]
type = "PipeLLM"
model = { model = "claude-4.5-sonnet", temperature = 0.7 }
-# Model automatically routed through Pipelex Inference
+# Model automatically routed through Pipelex Gateway
```
+### Gateway Model Overrides
+
+!!! warning "Advanced Feature - Use at Your Own Risk"
+ The Pipelex Gateway model configuration is fetched remotely from Pipelex servers. Any local override may cause unexpected behavior or failures, as the remote configuration may change at any time.
+
+If you need to customize how a specific model behaves through the Gateway, you can add per-model overrides in `.pipelex/inference/backends/pipelex_gateway.toml`. However, only two keys are supported:
+
+- `sdk`: The SDK to use for the model (e.g., `gateway_completions`)
+- `structure_method`: The method for structured output (e.g., `instructor/openai_tools`)
+
+All other keys will be ignored.
+
+```toml
+# .pipelex/inference/backends/pipelex_gateway.toml
+
+# Per-model overrides example:
+[gpt-4o]
+sdk = "gateway_completions"
+structure_method = "instructor/openai_tools"
+```
+
+!!! tip "Prefer Direct Backends for Custom Configurations"
+ If you need custom configurations beyond `sdk` and `structure_method`, consider using your own API keys with direct provider backends (openai, anthropic, etc.) instead of Gateway overrides.
+
### Model Availability Note
-While Pipelex Inference provides access to most AI models through a unified API, certain specialized models require their native backend to be enabled directly:
+While Pipelex Gateway provides access to most AI models through a unified API, certain specialized models require their native backend to be enabled directly:
- **FAL image generation models** (e.g., Flux models) - Enable the FAL backend
- **OpenAI image generation** (`gpt-image-1`) - Enable the OpenAI backend (should also work via Azure OpenAI, but we haven't been able to test this - if you've successfully used it on Azure, please let us know on [Discord](https://go.pipelex.com/discord) so we can validate this configuration)
- **Mistral OCR models** - Enable the Mistral backend
-These models are not proxied through Pipelex Inference and require direct configuration of their respective backends with appropriate API keys.
+These models are not proxied through Pipelex Gateway and require direct configuration of their respective backends with appropriate API keys.
## Inference Backends
@@ -165,8 +223,8 @@ cp .env.example .env
The `.env.example` file contains all available providers with helpful comments:
```bash
-# [OPTIONAL] Free Pipelex Inference API key - Get yours on Discord: https://go.pipelex.com/discord
-PIPELEX_INFERENCE_API_KEY=
+# [OPTIONAL] Free Pipelex Gateway API key - Get yours on Discord: https://go.pipelex.com/discord
+PIPELEX_GATEWAY_API_KEY=
OPENAI_API_KEY=
@@ -253,22 +311,22 @@ Routing profiles determine which backend handles specific models. This is where
### Profile Examples
-**All Pipelex Inference (Option A):**
+**All Pipelex Gateway (Option A):**
Setup:
```bash
# In .env
-PIPELEX_INFERENCE_API_KEY="your-pipelex-key"
+PIPELEX_GATEWAY_API_KEY="your-pipelex-key"
```
In `.pipelex/inference/routing_profiles.toml`:
```toml
# Which profile to use
-active = "pipelex_first"
+active = "pipelex_gateway_first"
-[profiles.pipelex_first]
-description = "Use Pipelex Inference backend for all its supported models"
-default = "pipelex_inference"
+[profiles.pipelex_gateway_first]
+description = "Use Pipelex Gateway backend for all its supported models"
+default = "pipelex_gateway"
```
**Native Providers Only (Option B):**
@@ -304,7 +362,7 @@ default = "openai"
Setup:
```bash
# In .env - combine Pipelex with specific provider keys
-PIPELEX_INFERENCE_API_KEY="your-pipelex-key"
+PIPELEX_GATEWAY_API_KEY="your-pipelex-key"
OPENAI_API_KEY="your-openai-key" # For GPT models
FAL_API_KEY="your-fal-key" # For image generation
```
@@ -314,15 +372,15 @@ In `.pipelex/inference/routing_profiles.toml`:
active = "hybrid"
[profiles.hybrid]
-description = "Use Pipelex for most models, native providers for specific ones"
-default = "pipelex_inference"
+description = "Use Pipelex Gateway for most models, native providers for specific ones"
+default = "pipelex_gateway"
[profiles.hybrid.routes]
# Use your own OpenAI key for GPT models (better rate limits)
"gpt-*" = "openai"
# Use your own FAL key for image generation (direct billing)
"flux-*" = "fal"
-# All other models use Pipelex Inference (claude, gemini, mistral, etc.)
+# All other models use Pipelex Gateway (claude, gemini, mistral, etc.)
```
### Routing System Features
@@ -334,16 +392,16 @@ The routing system supports:
- Prefix: `"gpt-*" = "openai"`
- Suffix: `"*-turbo" = "openai"`
- Contains: `"*-vision-*" = "openai"`
-- **Default fallback**: `default = "pipelex_inference"`
+- **Default fallback**: `default = "pipelex_gateway"`
### Use Cases for Mix & Match
Common scenarios for hybrid routing:
-1. **Cost Optimization**: Use Pipelex Inference for expensive models, your own keys for cheaper ones
+1. **Cost Optimization**: Use Pipelex Gateway for expensive models, your own keys for cheaper ones
2. **Rate Limits**: Use your own keys for high-volume models to avoid shared rate limits
-3. **Gradual Migration**: Start with Pipelex Inference, gradually move to your own keys as usage grows
-4. **Provider Features**: Use native providers for models requiring specific features not proxied through Pipelex Inference
+3. **Gradual Migration**: Start with Pipelex Gateway, gradually move to your own keys as usage grows
+4. **Provider Features**: Use native providers for models requiring specific features not proxied through Pipelex Gateway
## Model Deck
@@ -483,7 +541,7 @@ Common error types:
## Best Practices
1. **Choosing Your Configuration Approach**:
- - **Starting out?** Use Pipelex Inference (Option A) to get running quickly
+ - **Starting out?** Use Pipelex Gateway (Option A) to get running quickly
- **Production deployment?** Consider bringing your own keys (Option B) for direct billing control
- **Optimizing costs/performance?** Use Mix & Match (Option C) for maximum flexibility
- You can switch between approaches at any time by changing your routing profile
diff --git a/pipelex/builder/pipe/pipe_extract_spec.py b/pipelex/builder/pipe/pipe_extract_spec.py
index ee09b1a83..19b425da2 100644
--- a/pipelex/builder/pipe/pipe_extract_spec.py
+++ b/pipelex/builder/pipe/pipe_extract_spec.py
@@ -16,8 +16,8 @@ if TYPE_CHECKING:
class ExtractSkill(StrEnum):
- EXTRACT_TEXT_FROM_VISUALS = "extract_text_from_visuals"
- EXTRACT_TEXT_FROM_PDF = "extract_text_from_pdf"
+ PDF_TEXT_EXTRACTOR = "pdf_text_extractor"
+ IMAGE_TEXT_EXTRACTOR = "image_text_extractor"
class PipeExtractSpec(PipeSpec):
diff --git a/pipelex/builder/runner_code.py b/pipelex/builder/runner_code.py
index 1d0b010af..1c114ad34 100644
--- a/pipelex/builder/runner_code.py
+++ b/pipelex/builder/runner_code.py
@@ -268,10 +268,9 @@ def generate_runner_code(pipe: PipeAbstract, output_multiplicity: bool = False)
"",
'if __name__ == "__main__":',
" # Initialize Pipelex",
- " Pipelex.make()",
- "",
- " # Run the pipeline",
- f" result = asyncio.run(run_{pipe.code}())",
+ " with Pipelex.make():",
+ " # Run the pipeline",
+ f" result = asyncio.run(run_{pipe.code}())",
"",
]
)
diff --git a/pipelex/cli/_cli.py b/pipelex/cli/_cli.py
index 1fbbc36f7..14b88e04f 100644
--- a/pipelex/cli/_cli.py
+++ b/pipelex/cli/_cli.py
@@ -72,6 +72,7 @@ def app_callback(ctx: typer.Context) -> None:
# Check system readiness (dependencies and venv for dev installs)
check_readiness()
+ # Silently create missing config files if needed (doesn't validate existing ones)
init_cmd(silent=True)
diff --git a/pipelex/cli/cli_factory.py b/pipelex/cli/cli_factory.py
new file mode 100644
index 000000000..925599349
--- /dev/null
+++ b/pipelex/cli/cli_factory.py
@@ -0,0 +1,56 @@
+"""Factory functions for CLI commands."""
+
+from pipelex.cli.error_handlers import (
+ ErrorContext,
+ handle_gateway_api_key_missing_error,
+ handle_gateway_do_not_track_conflict_error,
+ handle_gateway_terms_not_accepted_error,
+ handle_model_deck_preset_error,
+ handle_remote_config_fetch_error,
+ handle_remote_config_validation_error,
+ handle_telemetry_config_validation_error,
+)
+from pipelex.cogt.exceptions import ModelDeckPresetValidatonError
+from pipelex.pipelex import Pipelex
+from pipelex.system.pipelex_service.exceptions import (
+ GatewayApiKeyMissingError,
+ GatewayDoNotTrackConflictError,
+ GatewayTermsNotAcceptedError,
+ RemoteConfigFetchError,
+ RemoteConfigValidationError,
+)
+from pipelex.system.runtime import IntegrationMode
+from pipelex.system.telemetry.exceptions import TelemetryConfigValidationError
+
+
+def make_pipelex_for_cli(context: ErrorContext) -> Pipelex:
+ """Initialize Pipelex for CLI commands with proper error handling.
+
+ This is a DRY wrapper around Pipelex.make() that catches common errors
+ and displays user-friendly messages with guidance.
+
+ Args:
+ context: The CLI context for error messages.
+
+ Returns:
+ Initialized Pipelex instance.
+
+ Raises:
+ typer.Exit: If initialization fails with a handled error.
+ """
+ try:
+ return Pipelex.make(integration_mode=IntegrationMode.CLI)
+ except TelemetryConfigValidationError as exc:
+ handle_telemetry_config_validation_error(exc)
+ except GatewayTermsNotAcceptedError as exc:
+ handle_gateway_terms_not_accepted_error(exc)
+ except GatewayApiKeyMissingError as exc:
+ handle_gateway_api_key_missing_error(exc)
+ except GatewayDoNotTrackConflictError as exc:
+ handle_gateway_do_not_track_conflict_error(exc)
+ except RemoteConfigFetchError as exc:
+ handle_remote_config_fetch_error(exc)
+ except RemoteConfigValidationError as exc:
+ handle_remote_config_validation_error(exc)
+ except ModelDeckPresetValidatonError as exc:
+ handle_model_deck_preset_error(exc, context=context)
diff --git a/pipelex/cli/commands/build/inputs_cmd.py b/pipelex/cli/commands/build/inputs_cmd.py
index f4a84e52d..9a2fd8bcb 100644
--- a/pipelex/cli/commands/build/inputs_cmd.py
+++ b/pipelex/cli/commands/build/inputs_cmd.py
@@ -6,19 +6,18 @@ import click
import typer
from posthog import tag
+from pipelex.cli.cli_factory import make_pipelex_for_cli
from pipelex.cli.commands.build.app import build_app
from pipelex.cli.error_handlers import (
ErrorContext,
handle_model_availability_error,
handle_model_choice_error,
- handle_model_deck_preset_error,
)
-from pipelex.cogt.exceptions import ModelDeckPresetValidatonError
from pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError
from pipelex.core.pipes.inputs.exceptions import PipeInputError
from pipelex.hub import get_required_pipe, get_telemetry_manager
from pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityError
-from pipelex.pipelex import PACKAGE_VERSION, Pipelex
+from pipelex.pipelex import PACKAGE_VERSION
from pipelex.pipeline.validate_bundle import ValidateBundleError, validate_bundle
from pipelex.system.runtime import IntegrationMode
from pipelex.system.telemetry.events import EventProperty
@@ -184,10 +183,7 @@ def generate_inputs_cmd(
typer.secho(f"❌ Error saving file: {exc}", fg=typer.colors.RED)
raise typer.Exit(1) from exc
- try:
- pipelex_instance = Pipelex.make(integration_mode=IntegrationMode.CLI)
- except ModelDeckPresetValidatonError as model_deck_error:
- handle_model_deck_preset_error(model_deck_error, context=ErrorContext.VALIDATION_BEFORE_BUILD_INPUTS)
+ pipelex_instance = make_pipelex_for_cli(context=ErrorContext.VALIDATION_BEFORE_BUILD_INPUTS)
try:
with get_telemetry_manager().telemetry_context():
diff --git a/pipelex/cli/commands/build/pipe_cmd.py b/pipelex/cli/commands/build/pipe_cmd.py
index a985280d9..606be9aeb 100644
--- a/pipelex/cli/commands/build/pipe_cmd.py
+++ b/pipelex/cli/commands/build/pipe_cmd.py
@@ -12,14 +12,13 @@ from pipelex.builder.builder import PipelexBundleSpec
from pipelex.builder.builder_errors import PipeBuilderError
from pipelex.builder.builder_loop import BuilderLoop
from pipelex.builder.runner_code import generate_runner_code
+from pipelex.cli.cli_factory import make_pipelex_for_cli
from pipelex.cli.commands.build.app import build_app
from pipelex.cli.error_handlers import (
ErrorContext,
handle_model_availability_error,
handle_model_choice_error,
- handle_model_deck_preset_error,
)
-from pipelex.cogt.exceptions import ModelDeckPresetValidatonError
from pipelex.config import get_config
from pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError
from pipelex.core.pipes.variable_multiplicity import parse_concept_with_multiplicity
@@ -66,6 +65,9 @@ pipelex build pipe "Take a CV and Job offer in PDF, analyze if they match and ge
pipelex build pipe \
"Take a Job offer text and a bunch of CVs (PDF), analyze how each CV matches the Job offer and generate 5 questions for each interview"
+pipelex build pipe \
+ "Take a Job offer and a bunch of CVs (PDF), analyze how each CV matches the Job offer and generate 5 questions for each interview"
+
# Other ideas:
pipelex build pipe "Take a photo as input, and render the opposite of the photo, don't structure anything, use only text content, be super concise"
pipelex build pipe "Take a photo as input, and render the opposite of the photo"
@@ -104,10 +106,7 @@ def build_pipe_cmd(
# Import here to avoid circular imports
from pipelex.cli.commands.build.structures_cmd import generate_structures_from_blueprints # noqa: PLC0415
- try:
- pipelex_instance = Pipelex.make(integration_mode=IntegrationMode.CLI)
- except ModelDeckPresetValidatonError as model_deck_error:
- handle_model_deck_preset_error(model_deck_error, context=ErrorContext.VALIDATION_BEFORE_BUILD_PIPE)
+ make_pipelex_for_cli(context=ErrorContext.VALIDATION_BEFORE_BUILD_PIPE)
typer.secho("🔥 Starting pipe builder... 🚀\n", fg=typer.colors.GREEN)
@@ -257,7 +256,7 @@ def build_pipe_cmd(
handle_model_availability_error(exc, context=ErrorContext.BUILD)
finally:
- pipelex_instance.teardown()
+ Pipelex.teardown_if_needed()
@build_app.command(SUB_COMMAND_ONE_SHOT_PIPE, help="Developer utility for contributors: deliver pipeline in one shot, without validation loop")
@@ -279,10 +278,7 @@ def build_one_shot_cmd(
typer.Option("--no-output", help="Skip saving the pipeline to file"),
] = False,
) -> None:
- try:
- pipelex_instance = Pipelex.make(integration_mode=IntegrationMode.CLI)
- except ModelDeckPresetValidatonError as model_deck_error:
- handle_model_deck_preset_error(model_deck_error, context=ErrorContext.VALIDATION_BEFORE_BUILD_ONE_SHOT)
+ make_pipelex_for_cli(context=ErrorContext.VALIDATION_BEFORE_BUILD_ONE_SHOT)
typer.secho("🔥 Starting pipe builder... 🚀\n", fg=typer.colors.GREEN)
@@ -335,7 +331,7 @@ def build_one_shot_cmd(
handle_model_availability_error(exc, context=ErrorContext.BUILD)
finally:
- pipelex_instance.teardown()
+ Pipelex.teardown_if_needed()
@build_app.command(
@@ -368,10 +364,7 @@ def build_partial_cmd(
typer.Option("--no-output", help="Skip saving the pipeline to file"),
] = False,
) -> None:
- try:
- pipelex_instance = Pipelex.make(integration_mode=IntegrationMode.CLI)
- except ModelDeckPresetValidatonError as model_deck_error:
- handle_model_deck_preset_error(model_deck_error, context=ErrorContext.VALIDATION_BEFORE_BUILD_PARTIAL)
+ make_pipelex_for_cli(context=ErrorContext.VALIDATION_BEFORE_BUILD_PARTIAL)
typer.secho("🔥 Starting pipe builder... 🚀\n", fg=typer.colors.GREEN)
@@ -442,4 +435,4 @@ def build_partial_cmd(
handle_model_availability_error(exc, context=ErrorContext.BUILD)
finally:
- pipelex_instance.teardown()
+ Pipelex.teardown_if_needed()
diff --git a/pipelex/cli/commands/build/runner_cmd.py b/pipelex/cli/commands/build/runner_cmd.py
index 3d1abbdac..b68c6b00b 100644
--- a/pipelex/cli/commands/build/runner_cmd.py
+++ b/pipelex/cli/commands/build/runner_cmd.py
@@ -7,20 +7,19 @@ import typer
from posthog import tag
from pipelex.builder.runner_code import generate_runner_code
+from pipelex.cli.cli_factory import make_pipelex_for_cli
from pipelex.cli.commands.build.app import build_app
from pipelex.cli.error_handlers import (
ErrorContext,
handle_model_availability_error,
handle_model_choice_error,
- handle_model_deck_preset_error,
)
-from pipelex.cogt.exceptions import ModelDeckPresetValidatonError
from pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError
from pipelex.core.pipes.inputs.exceptions import PipeInputError
from pipelex.core.pipes.variable_multiplicity import parse_concept_with_multiplicity
from pipelex.hub import get_required_pipe, get_telemetry_manager
from pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityError
-from pipelex.pipelex import PACKAGE_VERSION, Pipelex
+from pipelex.pipelex import PACKAGE_VERSION
from pipelex.pipeline.validate_bundle import ValidateBundleError, validate_bundle
from pipelex.system.runtime import IntegrationMode
from pipelex.system.telemetry.events import EventProperty
@@ -218,10 +217,7 @@ def prepare_runner_cmd(
typer.secho(f"❌ Error saving file: {exc}", fg=typer.colors.RED)
raise typer.Exit(1) from exc
- try:
- pipelex_instance = Pipelex.make(integration_mode=IntegrationMode.CLI)
- except ModelDeckPresetValidatonError as model_deck_error:
- handle_model_deck_preset_error(model_deck_error, context=ErrorContext.VALIDATION_BEFORE_BUILD_RUNNER)
+ pipelex_instance = make_pipelex_for_cli(context=ErrorContext.VALIDATION_BEFORE_BUILD_RUNNER)
try:
with get_telemetry_manager().telemetry_context():
diff --git a/pipelex/cli/commands/build/structures_cmd.py b/pipelex/cli/commands/build/structures_cmd.py
index f916611cf..cd680fb64 100644
--- a/pipelex/cli/commands/build/structures_cmd.py
+++ b/pipelex/cli/commands/build/structures_cmd.py
@@ -7,17 +7,17 @@ from kajson.kajson_manager import KajsonManager
from pipelex import log
from pipelex.base_exceptions import PipelexError
+from pipelex.cli.cli_factory import make_pipelex_for_cli
from pipelex.cli.commands.build.app import build_app
+from pipelex.cli.error_handlers import ErrorContext
from pipelex.core.concepts.concept_factory import ConceptFactory
from pipelex.core.concepts.helpers import normalize_structure_blueprint
from pipelex.core.concepts.structure_generation.exceptions import ConceptStructureGeneratorError
from pipelex.core.concepts.structure_generation.generator import StructureGenerator
from pipelex.core.stuffs.structured_content import StructuredContent
from pipelex.core.stuffs.text_content import TextContent
-from pipelex.pipelex import Pipelex
from pipelex.pipeline.validate_bundle import validate_bundle, validate_bundles_from_directory
from pipelex.system.registries.class_registry_utils import ClassRegistryUtils
-from pipelex.system.runtime import IntegrationMode
if TYPE_CHECKING:
from pipelex.core.bundles.pipelex_bundle_blueprint import PipelexBundleBlueprint
@@ -204,7 +204,7 @@ def build_structures_command(
# Determine if target is a file or directory
is_plx_file = target_path.is_file() and target_path.suffix == ".plx"
- pipelex_instance = Pipelex.make(integration_mode=IntegrationMode.CLI)
+ pipelex_instance = make_pipelex_for_cli(context=ErrorContext.BUILD)
try:
if is_plx_file:
diff --git a/pipelex/cli/commands/doctor_cmd.py b/pipelex/cli/commands/doctor_cmd.py
index 0afd794b4..78f205a8c 100644
--- a/pipelex/cli/commands/doctor_cmd.py
+++ b/pipelex/cli/commands/doctor_cmd.py
@@ -6,7 +6,7 @@ import contextlib
import io
import sys
from pathlib import Path
-from typing import Any
+from typing import TYPE_CHECKING, Any
from pydantic import BaseModel, ValidationError
from rich.panel import Panel
@@ -19,8 +19,12 @@ from pipelex.cli.commands.init.command import init_cmd
from pipelex.cli.commands.init.config_files import init_config
from pipelex.cli.commands.init.ui.types import InitFocus
from pipelex.cogt.exceptions import InferenceBackendLibraryError
+from pipelex.cogt.model_backends.backend_credentials import BackendCredentialsErrorMsgFactory
from pipelex.cogt.model_backends.backend_library import BackendCredentialsReport, InferenceBackendLibrary
from pipelex.cogt.models.model_manager import ModelManager
+
+if TYPE_CHECKING:
+ from pipelex.cogt.model_backends.model_spec_factory import BackendModelSpecs
from pipelex.config import get_config
from pipelex.core.validation import report_validation_error
from pipelex.hub import PipelexHub, get_console, set_pipelex_hub
@@ -28,13 +32,18 @@ from pipelex.kit.paths import get_kit_configs_dir
from pipelex.system.configuration.config_loader import config_manager
from pipelex.system.configuration.configs import PipelexConfig
from pipelex.system.environment import get_optional_env
+from pipelex.system.pipelex_service.exceptions import RemoteConfigFetchError, RemoteConfigValidationError
+from pipelex.system.pipelex_service.pipelex_service_config import (
+ is_pipelex_gateway_enabled,
+ load_pipelex_service_config_if_exists,
+)
+from pipelex.system.pipelex_service.remote_config import fetch_remote_config
from pipelex.system.telemetry.telemetry_config import TELEMETRY_CONFIG_FILE_NAME, TelemetryConfig
from pipelex.tools.misc.dict_utils import extract_vars_from_strings_recursive
from pipelex.tools.misc.file_utils import path_exists
from pipelex.tools.misc.placeholder import value_is_placeholder
-from pipelex.tools.misc.toml_utils import load_toml_from_path
+from pipelex.tools.misc.toml_utils import TomlError, load_toml_from_path
from pipelex.tools.secrets.env_secrets_provider import EnvSecretsProvider
-from pipelex.tools.typing.pydantic_utils import format_pydantic_validation_error
class BackendFileReport(BaseModel):
@@ -89,19 +98,21 @@ def check_telemetry_config() -> tuple[bool, str]:
# Use hard-coded path to avoid needing Pipelex initialization
telemetry_config_path = f".pipelex/{TELEMETRY_CONFIG_FILE_NAME}"
- if not path_exists(telemetry_config_path):
+ try:
+ toml_doc = load_toml_from_path(telemetry_config_path)
+ except FileNotFoundError:
return False, "Telemetry configuration file not found"
+ except TomlError as exc:
+ return False, f"TOML syntax error: {exc}"
try:
- toml_doc = load_toml_from_path(telemetry_config_path)
telemetry_config = TelemetryConfig.model_validate(toml_doc)
- return True, f"Telemetry configured (mode: {telemetry_config.telemetry_mode})"
- except ValidationError as validation_error:
- validation_error_msg = format_pydantic_validation_error(validation_error)
- msg = f"Invalid telemetry configuration: {validation_error_msg}"
- return False, msg
- except Exception as exc:
- return False, f"Error loading telemetry config: {exc}"
+ return True, f"Telemetry configured (mode: {telemetry_config.posthog.mode})"
+ except ValidationError:
+ # Check if this looks like the old config format (has telemetry_mode at root level)
+ if "posthog" not in toml_doc and ("telemetry_mode" in toml_doc or "project_api_key" in toml_doc):
+ return False, "Config format has changed - run [cyan]pipelex init telemetry[/cyan] to update"
+ return False, "Invalid configuration - run [cyan]pipelex init telemetry --reset[/cyan] to fix"
def check_backend_credentials() -> tuple[bool, dict[str, BackendCredentialsReport], str]:
@@ -415,16 +426,21 @@ def display_health_report(
console.print()
# Show details for each backend
+ bad_backend_credential_reports: dict[str, BackendCredentialsReport] = {}
for backend_name, backend_credential_report in backend_credential_reports.items():
if backend_credential_report.all_credentials_valid:
console.print(f" [dim]{backend_name}[/dim]")
console.print(" [green]✓[/green] All credentials set")
else:
+ bad_backend_credential_reports[backend_name] = backend_credential_report
console.print(f" [bold]{backend_name}[/bold]")
if backend_credential_report.missing_vars:
console.print(f" [red]✗[/red] Missing: {', '.join(backend_credential_report.missing_vars)}")
if backend_credential_report.placeholder_vars:
console.print(f" [yellow]⚠[/yellow] Placeholders: {', '.join(backend_credential_report.placeholder_vars)}")
+
+ error_msg = BackendCredentialsErrorMsgFactory.make_comprehensive_error_msg(backend_credential_reports=bad_backend_credential_reports)
+ console.print(error_msg)
console.print()
# Models section
@@ -457,8 +473,12 @@ def display_health_report(
if not all_healthy:
# Check what can be auto-fixed
can_auto_fix_config = not config_healthy and config_missing_count > 0
- can_auto_fix_telemetry = not telemetry_healthy and "not found" in telemetry_message.lower()
- has_telemetry_validation_error = not telemetry_healthy and "not found" not in telemetry_message.lower()
+ can_auto_fix_telemetry = not telemetry_healthy and (
+ "not found" in telemetry_message.lower()
+ or "format has changed" in telemetry_message.lower()
+ or "invalid configuration" in telemetry_message.lower()
+ )
+ has_telemetry_validation_error = not telemetry_healthy and not can_auto_fix_telemetry
# Check for backend file issues
has_backend_file_issues = False
@@ -483,7 +503,7 @@ def display_health_report(
)
if has_recommendations:
- console.print("[bold]Recommended Actions[/bold]")
+ console.print("[bold]Possible Solutions[/bold]")
if can_auto_fix_config:
console.print(" • Run [cyan]pipelex init config[/cyan] to install missing configuration files")
@@ -491,7 +511,7 @@ def display_health_report(
if can_auto_fix_telemetry:
console.print(" • Run [cyan]pipelex init telemetry[/cyan] to configure telemetry preferences")
- if has_telemetry_validation_error:
+ if has_telemetry_validation_error and "pipelex init telemetry" not in telemetry_message:
console.print(" • Fix validation errors in [cyan].pipelex/telemetry.toml[/cyan]")
console.print(" or run [cyan]pipelex init telemetry --reset[/cyan] to regenerate")
@@ -579,10 +599,24 @@ def check_models() -> tuple[bool, str, dict[str, BackendFileReport]]:
log.configure(log_config=get_config().pipelex.log_config)
+ # Fetch gateway model specs if Gateway is enabled
+ gateway_model_specs: BackendModelSpecs | None = None
+ if is_pipelex_gateway_enabled():
+ pipelex_service_config = load_pipelex_service_config_if_exists(config_dir=config_manager.pipelex_config_dir)
+ if pipelex_service_config is None:
+ return False, "Pipelex Gateway is enabled but service configuration is missing", backend_file_reports
+ if not pipelex_service_config.agreement.terms_accepted:
+ return False, "Pipelex Gateway is enabled but terms have not been accepted", backend_file_reports
+ try:
+ remote_config = fetch_remote_config()
+ gateway_model_specs = remote_config.backend_model_specs
+ except (RemoteConfigFetchError, RemoteConfigValidationError) as exc:
+ return False, f"Failed to fetch Pipelex Gateway remote configuration: {exc}", backend_file_reports
+
models_manager = ModelManager()
secrets_provider = EnvSecretsProvider()
try:
- models_manager.setup(secrets_provider=secrets_provider)
+ models_manager.setup(secrets_provider=secrets_provider, gateway_model_specs=gateway_model_specs)
models_manager.validate_model_deck()
except InferenceBackendLibraryError as exc:
# Backend library error - try to identify which backend
@@ -663,7 +697,12 @@ def do_doctor_cmd(
# Determine what can be auto-fixed
can_fix_config = not config_healthy and config_missing_count > 0
- can_fix_telemetry = not telemetry_healthy and "not found" in telemetry_message.lower()
+ # Telemetry can be fixed if not found, format changed, OR invalid configuration
+ can_fix_telemetry = not telemetry_healthy and (
+ "not found" in telemetry_message.lower()
+ or "format has changed" in telemetry_message.lower()
+ or "invalid configuration" in telemetry_message.lower()
+ )
# Check for backend file issues that can be auto-fixed
can_fix_backends = False
@@ -675,9 +714,10 @@ def do_doctor_cmd(
has_auto_fixable_issues = can_fix_config or can_fix_telemetry or can_fix_backends
- # Determine what requires manual fixes
+ # Determine what requires manual fixes (excludes auto-fixable issues)
has_config_validation_error = not config_healthy and config_missing_count == 0
- has_telemetry_validation_error = not telemetry_healthy and "not found" not in telemetry_message.lower()
+ # Telemetry validation error only if it's not auto-fixable (not "not found" and not "format has changed")
+ has_telemetry_validation_error = not telemetry_healthy and not can_fix_telemetry
has_backend_credential_issues = not backends_healthy and backend_credential_reports
# If --fix flag is provided, offer to fix auto-fixable issues
@@ -697,12 +737,22 @@ def do_doctor_cmd(
console.print(f"[red]Failed to install configuration files: {exc!s}[/red]")
console.print()
- # Fix missing telemetry config
+ # Fix missing or outdated telemetry config
if can_fix_telemetry:
- if Confirm.ask("[bold]Configure telemetry preferences?[/bold]", default=True):
+ is_format_change = "format has changed" in telemetry_message.lower()
+ is_invalid_config = "invalid configuration" in telemetry_message.lower()
+ needs_reset = is_format_change or is_invalid_config
+ if is_format_change:
+ prompt_msg = "[bold]Reset telemetry configuration using the new format?[/bold]"
+ elif is_invalid_config:
+ prompt_msg = "[bold]Reset telemetry configuration to fix validation errors?[/bold]"
+ else:
+ prompt_msg = "[bold]Configure telemetry preferences?[/bold]"
+ if Confirm.ask(prompt_msg, default=True):
try:
console.print()
- init_cmd(focus=InitFocus.TELEMETRY, reset=False, skip_confirmation=True)
+ # Use reset=True for format changes or invalid config to overwrite
+ init_cmd(focus=InitFocus.TELEMETRY, reset=needs_reset, skip_confirmation=True)
console.print("[green]✓[/green] Telemetry configured")
except Exception as exc:
console.print(f"[red]Failed to configure telemetry: {exc!s}[/red]")
@@ -748,8 +798,8 @@ def do_doctor_cmd(
console.print("or run [cyan]pipelex init config --reset[/cyan] to regenerate from template.")
console.print()
- # Telemetry validation errors
- if has_telemetry_validation_error:
+ # Telemetry validation errors (skip if message already contains the fix command)
+ if has_telemetry_validation_error and "pipelex init telemetry" not in telemetry_message:
console.print("[bold]Telemetry validation error:[/bold]")
console.print(f" {telemetry_message}")
console.print()
diff --git a/pipelex/cli/commands/init/backends.py b/pipelex/cli/commands/init/backends.py
index b05744478..f1cd0875c 100644
--- a/pipelex/cli/commands/init/backends.py
+++ b/pipelex/cli/commands/init/backends.py
@@ -8,11 +8,18 @@ from pipelex.cli.commands.init.ui.backends_ui import (
display_selected_backends,
get_backend_options_from_toml,
get_currently_enabled_backends,
- prompt_backend_indices,
+ prompt_backend_select,
)
+from pipelex.cli.commands.init.ui.gateway_ui import (
+ display_gateway_accepted_message,
+ display_gateway_declined_message,
+ prompt_gateway_acceptance,
+)
+from pipelex.cogt.model_backends.backend import PipelexBackend
from pipelex.hub import get_console
from pipelex.kit.paths import get_kit_configs_dir
from pipelex.system.configuration.config_loader import config_manager
+from pipelex.system.pipelex_service.pipelex_service_agreement import update_service_terms_acceptance
from pipelex.tools.misc.file_utils import path_exists
from pipelex.tools.misc.toml_utils import load_toml_from_path, load_toml_with_tomlkit, save_toml_to_path
@@ -62,6 +69,22 @@ def get_selected_backend_keys(backends_toml_path: str) -> list[str]:
return selected_backends
+def disable_gateway_backend(backends_toml_path: str) -> None:
+ """Disable the pipelex_gateway backend in backends.toml.
+
+ Args:
+ backends_toml_path: Path to the backends.toml file.
+ """
+ if not path_exists(backends_toml_path):
+ return
+
+ toml_doc = load_toml_with_tomlkit(backends_toml_path)
+
+ if PipelexBackend.GATEWAY in toml_doc:
+ toml_doc[PipelexBackend.GATEWAY]["enabled"] = False # type: ignore[index]
+ save_toml_to_path(toml_doc, backends_toml_path)
+
+
def customize_backends_config(is_first_time_setup: bool = False) -> None:
"""Interactively customize which inference backends are enabled in backends.toml.
@@ -85,7 +108,7 @@ def customize_backends_config(is_first_time_setup: bool = False) -> None:
currently_enabled = get_currently_enabled_backends(backends_toml_path, backend_options)
# If this is first-time setup, ignore what's in the template (all enabled)
- # and use only pipelex_inference as the default
+ # and use only pipelex_gateway as the default
if is_first_time_setup or (currently_enabled and len(currently_enabled) == len(backend_options)):
currently_enabled = []
@@ -95,7 +118,26 @@ def customize_backends_config(is_first_time_setup: bool = False) -> None:
# UI: Display panel and get user selection
console.print(build_backend_selection_panel(backend_options, currently_enabled, is_first_time_setup))
- selected_indices = prompt_backend_indices(console, backend_options, currently_enabled, is_first_time_setup)
+ selected_indices, selected_backends = prompt_backend_select(
+ console=console,
+ backend_options=backend_options,
+ currently_enabled=currently_enabled,
+ is_first_time_setup=is_first_time_setup,
+ )
+
+ # Check if pipelex_gateway is selected and handle terms acceptance
+ if PipelexBackend.GATEWAY in selected_backends:
+ gateway_accepted = prompt_gateway_acceptance(console)
+
+ if gateway_accepted:
+ display_gateway_accepted_message(console)
+ update_service_terms_acceptance(accepted=True)
+ else:
+ display_gateway_declined_message(console)
+ update_service_terms_acceptance(accepted=False)
+
+ # Remove pipelex_gateway from selected indices
+ selected_indices = [idx for idx in selected_indices if backend_options[idx][0] != PipelexBackend.GATEWAY]
# Business logic: Update TOML
update_backends_in_toml(toml_doc, selected_indices, backend_options)
diff --git a/pipelex/cli/commands/init/command.py b/pipelex/cli/commands/init/command.py
index 1deedeab5..a218f8105 100644
--- a/pipelex/cli/commands/init/command.py
+++ b/pipelex/cli/commands/init/command.py
@@ -7,20 +7,68 @@ import typer
from rich.console import Console
from rich.prompt import Confirm
-from pipelex.cli.commands.init.backends import customize_backends_config, get_selected_backend_keys
+from pipelex.cli.commands.init.backends import (
+ customize_backends_config,
+ disable_gateway_backend,
+ get_selected_backend_keys,
+)
from pipelex.cli.commands.init.config_files import init_config
from pipelex.cli.commands.init.routing import customize_routing_profile
from pipelex.cli.commands.init.telemetry import setup_telemetry
+from pipelex.cli.commands.init.ui.gateway_ui import (
+ display_gateway_accepted_message,
+ display_gateway_declined_message,
+ prompt_gateway_acceptance,
+)
from pipelex.cli.commands.init.ui.general_ui import build_initialization_panel, display_already_configured_message
from pipelex.cli.commands.init.ui.types import InitFocus
+from pipelex.cogt.model_backends.backend import PipelexBackend
from pipelex.hub import get_console
from pipelex.kit.paths import get_kit_configs_dir
from pipelex.system.configuration.config_loader import config_manager
+from pipelex.system.pipelex_service.pipelex_service_agreement import update_service_terms_acceptance
+from pipelex.system.pipelex_service.pipelex_service_config import load_pipelex_service_config_if_exists
from pipelex.system.telemetry.telemetry_config import TELEMETRY_CONFIG_FILE_NAME
-from pipelex.system.telemetry.telemetry_manager_abstract import TelemetryManagerAbstract
from pipelex.tools.misc.file_utils import path_exists
+def _check_gateway_terms_if_needed(console: Console, backends_toml_path: str) -> None:
+ """Check if gateway is enabled and terms not yet accepted, then prompt for acceptance.
+
+ This is called after init_config() to ensure users who have gateway enabled
+ in their existing backends.toml are prompted to accept terms when pipelex_service.toml
+ is first created.
+
+ Args:
+ console: Rich Console instance for user interaction.
+ backends_toml_path: Path to backends.toml file.
+ """
+ # Check if backends.toml exists and gateway is enabled
+ if not path_exists(backends_toml_path):
+ return
+
+ selected_backend_keys = get_selected_backend_keys(backends_toml_path)
+ if PipelexBackend.GATEWAY not in selected_backend_keys:
+ return
+
+ # Gateway is enabled - check if terms are already accepted
+ pipelex_service_config = load_pipelex_service_config_if_exists(config_dir=config_manager.pipelex_config_dir)
+ if pipelex_service_config is not None and pipelex_service_config.agreement.terms_accepted:
+ return
+
+ # Gateway is enabled but terms not accepted - prompt user
+ gateway_accepted = prompt_gateway_acceptance(console)
+
+ if gateway_accepted:
+ display_gateway_accepted_message(console)
+ update_service_terms_acceptance(accepted=True)
+ else:
+ display_gateway_declined_message(console)
+ update_service_terms_acceptance(accepted=False)
+ # Actually disable the gateway in backends.toml
+ disable_gateway_backend(backends_toml_path)
+
+
def determine_needs(
reset: bool,
check_config: bool,
@@ -194,12 +242,59 @@ def execute_initialization(
if backends_just_copied_during_config or (check_inference and backends_exists_now):
needs_inference = True
+ # If we're NOT going to run customize_backends_config (which handles gateway terms),
+ # we need to check if gateway is enabled and terms not accepted
+ if not needs_inference and backends_existed_before:
+ _check_gateway_terms_if_needed(console, backends_toml_path)
+
# Determine if this is truly a first-time setup (either tracked from before or just copied now)
first_time_setup = is_first_time_backends_setup or backends_just_copied_during_config
# Step 2: Set up inference backends if needed
if needs_inference:
console.print()
+
+ # If reset is True and we didn't already copy via config init, copy the template files
+ if reset and not backends_just_copied_during_config:
+ template_inference_dir = os.path.join(str(get_kit_configs_dir()), "inference")
+ target_inference_dir = os.path.join(config_manager.pipelex_config_dir, "inference")
+
+ # Reset backends.toml
+ template_backends_path = os.path.join(template_inference_dir, "backends.toml")
+ os.makedirs(os.path.dirname(backends_toml_path), exist_ok=True)
+ shutil.copy2(template_backends_path, backends_toml_path)
+ console.print("✅ Reset backends.toml from template")
+
+ # Reset all individual backend files in backends/ directory
+ template_backends_dir = os.path.join(template_inference_dir, "backends")
+ target_backends_dir = os.path.join(target_inference_dir, "backends")
+ os.makedirs(target_backends_dir, exist_ok=True)
+ reset_backend_files: list[str] = []
+ for backend_file in os.listdir(template_backends_dir):
+ if backend_file.endswith(".toml"):
+ src_path = os.path.join(template_backends_dir, backend_file)
+ dst_path = os.path.join(target_backends_dir, backend_file)
+ shutil.copy2(src_path, dst_path)
+ reset_backend_files.append(backend_file)
+ if reset_backend_files:
+ console.print(f"✅ Reset {len(reset_backend_files)} backend config files from template")
+
+ # Reset deck/ directory files (model deck configurations)
+ template_deck_dir = os.path.join(template_inference_dir, "deck")
+ target_deck_dir = os.path.join(target_inference_dir, "deck")
+ os.makedirs(target_deck_dir, exist_ok=True)
+ reset_deck_files: list[str] = []
+ for deck_file in os.listdir(template_deck_dir):
+ if deck_file.endswith(".toml"):
+ src_path = os.path.join(template_deck_dir, deck_file)
+ dst_path = os.path.join(target_deck_dir, deck_file)
+ shutil.copy2(src_path, dst_path)
+ reset_deck_files.append(deck_file)
+ if reset_deck_files:
+ console.print(f"✅ Reset {len(reset_deck_files)} model deck config files from template")
+
+ first_time_setup = True # Treat as first-time setup since we just replaced the files
+
customize_backends_config(is_first_time_setup=first_time_setup)
# Automatically set up routing after backends (unless routing is the specific focus)
@@ -216,10 +311,8 @@ def execute_initialization(
if reset:
routing_profiles_toml_path = os.path.join(config_manager.pipelex_config_dir, "inference", "routing_profiles.toml")
template_routing_path = os.path.join(str(get_kit_configs_dir()), "inference", "routing_profiles.toml")
-
- if path_exists(template_routing_path):
- shutil.copy2(template_routing_path, routing_profiles_toml_path)
- console.print("✅ Reset routing_profiles.toml from template")
+ shutil.copy2(template_routing_path, routing_profiles_toml_path)
+ console.print("✅ Reset routing_profiles.toml from template")
selected_backend_keys = get_selected_backend_keys(backends_toml_path)
if selected_backend_keys:
@@ -229,8 +322,7 @@ def execute_initialization(
# Step 3: Set up telemetry if needed
if needs_telemetry:
- telemetry_mode = setup_telemetry(console, telemetry_config_path)
- TelemetryManagerAbstract.telemetry_mode_just_set = telemetry_mode
+ setup_telemetry(console, telemetry_config_path)
console.print()
diff --git a/pipelex/cli/commands/init/routing.py b/pipelex/cli/commands/init/routing.py
index 0b8c158fa..b60e82031 100644
--- a/pipelex/cli/commands/init/routing.py
+++ b/pipelex/cli/commands/init/routing.py
@@ -1,7 +1,7 @@
"""Routing profile configuration logic for the init command."""
import os
-from typing import Any
+from typing import Any, cast
from rich.prompt import Confirm
from tomlkit import table
@@ -14,6 +14,8 @@ from pipelex.cli.commands.init.ui.routing_ui import (
prompt_fallback_order,
prompt_primary_backend,
)
+from pipelex.cogt.model_backends.backend import PipelexBackend
+from pipelex.cogt.model_routing.routing_profile import PipelexRoutingProfile
from pipelex.hub import get_console
from pipelex.kit.paths import get_kit_configs_dir
from pipelex.system.configuration.config_loader import config_manager
@@ -21,6 +23,47 @@ from pipelex.tools.misc.file_utils import path_exists
from pipelex.tools.misc.toml_utils import load_toml_with_tomlkit, save_toml_to_path
+def _migrate_profile_to_official_backend(profile: dict[str, Any]) -> None:
+ """Migrate a routing profile from legacy pipelex_inference to pipelex_gateway.
+
+ Updates default, fallback_order, routes, and optional_routes in place.
+
+ Args:
+ profile: The profile dict to migrate (modified in place).
+ """
+ legacy_backend = PipelexBackend.LEGACY_INFERENCE.value
+ official_backend = PipelexBackend.GATEWAY.value
+
+ # Update default
+ if profile.get("default") == legacy_backend:
+ profile["default"] = official_backend
+
+ # Update fallback_order
+ if "fallback_order" in profile:
+ old_fallback: list[str] = list(profile["fallback_order"])
+ new_fallback: list[str] = []
+ for backend in old_fallback:
+ if backend == legacy_backend:
+ new_fallback.append(official_backend)
+ else:
+ new_fallback.append(backend)
+ profile["fallback_order"] = new_fallback
+
+ # Update routes
+ if "routes" in profile:
+ routes: dict[str, str] = profile["routes"]
+ patterns_to_update = [pattern for pattern, backend in routes.items() if backend == legacy_backend]
+ for pattern in patterns_to_update:
+ routes[pattern] = official_backend
+
+ # Update optional_routes
+ if "optional_routes" in profile:
+ optional_routes: dict[str, str] = profile["optional_routes"]
+ optional_patterns_to_update = [pattern for pattern, backend in optional_routes.items() if backend == legacy_backend]
+ for pattern in optional_patterns_to_update:
+ optional_routes[pattern] = official_backend
+
+
def customize_routing_profile(selected_backend_keys: list[str]) -> None:
"""Interactively customize routing profile based on selected backends.
@@ -47,11 +90,21 @@ def customize_routing_profile(selected_backend_keys: list[str]) -> None:
template_backends_path = os.path.join(str(get_kit_configs_dir()), "inference", "backends.toml")
backend_options = get_backend_options_from_toml(template_backends_path, backends_toml_path)
- # Case 1: pipelex_inference is enabled - keep pipelex_first
- if "pipelex_inference" in selected_backend_keys:
- toml_doc["active"] = "pipelex_first"
+ # Case 1: pipelex_gateway is enabled - use pipelex_gateway_first
+ if PipelexBackend.GATEWAY in selected_backend_keys:
+ profiles: dict[str, dict[str, Any]] = toml_doc.get("profiles") or {} # type: ignore[assignment]
+
+ # Migrate legacy pipelex_first profile to pipelex_gateway_first
+ if PipelexRoutingProfile.PIPELEX_FIRST in profiles:
+ legacy_profile = cast("dict[str, Any]", profiles[PipelexRoutingProfile.PIPELEX_FIRST])
+ _migrate_profile_to_official_backend(legacy_profile)
+ # Rename the profile from pipelex_first to pipelex_gateway_first
+ profiles[PipelexRoutingProfile.PIPELEX_GATEWAY_FIRST] = legacy_profile
+ del profiles[PipelexRoutingProfile.PIPELEX_FIRST]
+
+ toml_doc["active"] = PipelexRoutingProfile.PIPELEX_GATEWAY_FIRST
save_toml_to_path(toml_doc, routing_profiles_toml_path)
- display_routing_profile_result(console, "pipelex_first", created=False)
+ display_routing_profile_result(console, PipelexRoutingProfile.PIPELEX_GATEWAY_FIRST, created=False)
return
# Case 2: Only one backend selected - use all_{backend_key} profile
@@ -88,7 +141,7 @@ def customize_routing_profile(selected_backend_keys: list[str]) -> None:
display_routing_profile_result(console, profile_name, created=not profile_exists)
return
- # Case 3: Multiple backends (no pipelex_inference) - create/update custom_routing profile
+ # Case 3: Multiple backends (no pipelex_gateway) - create/update custom_routing profile
console.print()
console.print("[cyan]Setting up routing for multiple backends...[/cyan]")
console.print()
diff --git a/pipelex/cli/commands/init/telemetry.py b/pipelex/cli/commands/init/telemetry.py
index cfe26ea2e..087da9538 100644
--- a/pipelex/cli/commands/init/telemetry.py
+++ b/pipelex/cli/commands/init/telemetry.py
@@ -1,39 +1,36 @@
"""Telemetry configuration logic for the init command."""
import os
+import shutil
from rich.console import Console
-from pipelex.cli.commands.init.ui.telemetry_ui import build_telemetry_selection_panel, prompt_telemetry_mode
from pipelex.kit.paths import get_kit_configs_dir
-from pipelex.system.telemetry.telemetry_config import TELEMETRY_CONFIG_FILE_NAME, TelemetryMode
-from pipelex.tools.misc.toml_utils import load_toml_with_tomlkit, save_toml_to_path
+from pipelex.system.telemetry.telemetry_config import TELEMETRY_CONFIG_FILE_NAME
-def setup_telemetry(console: Console, telemetry_config_path: str) -> TelemetryMode:
- """Set up telemetry configuration interactively.
+def setup_telemetry(console: Console, telemetry_config_path: str) -> None:
+ """Set up telemetry configuration by copying the template.
Args:
console: Rich Console instance for user interaction.
telemetry_config_path: Path to save the telemetry configuration.
-
- Returns:
- The selected TelemetryMode.
-
- Raises:
- typer.Exit: If user chooses to quit.
"""
- console.print()
- console.print(build_telemetry_selection_panel())
-
- telemetry_mode = prompt_telemetry_mode(console)
+ # Ensure parent directory exists (needed when running `pipelex init telemetry` on fresh project)
+ os.makedirs(os.path.dirname(telemetry_config_path), exist_ok=True)
- # Save telemetry config
+ # Copy template to destination
template_path = os.path.join(str(get_kit_configs_dir()), TELEMETRY_CONFIG_FILE_NAME)
- toml_doc = load_toml_with_tomlkit(template_path)
- toml_doc["telemetry_mode"] = telemetry_mode
- save_toml_to_path(toml_doc, telemetry_config_path)
+ shutil.copy(template_path, telemetry_config_path)
- console.print(f"\n[green]✓[/green] Telemetry mode set to: [bold cyan]{telemetry_mode}[/bold cyan]")
-
- return telemetry_mode
+ console.print()
+ console.print("[green]✓[/green] Telemetry configuration created")
+ console.print(f" [dim]File:[/dim] [cyan]{telemetry_config_path}[/cyan]")
+ console.print()
+ console.print("[dim]Edit this file to configure AI trace destinations:[/dim]")
+ console.print("[dim] • \\[posthog] - Send traces to your own PostHog project[/dim]")
+ console.print("[dim] • \\[langfuse] - Enable Langfuse LLM observability[/dim]")
+ console.print("[dim] • \\[\\[otlp]] - Add custom OpenTelemetry exporters[/dim]")
+ console.print()
+ console.print("[dim]💡 Note: If you use Pipelex Gateway, separate telemetry is sent to Pipelex[/dim]")
+ console.print("[dim]servers regardless of these settings.[/dim]")
diff --git a/pipelex/cli/commands/init/ui/backends_ui.py b/pipelex/cli/commands/init/ui/backends_ui.py
index 1d2a31c6f..424ed6812 100644
--- a/pipelex/cli/commands/init/ui/backends_ui.py
+++ b/pipelex/cli/commands/init/ui/backends_ui.py
@@ -150,9 +150,12 @@ def build_backend_selection_panel(
)
-def prompt_backend_indices(
- console: Console, backend_options: list[tuple[str, str]], currently_enabled: list[int] | None = None, is_first_time_setup: bool = False
-) -> list[int]:
+def prompt_backend_select(
+ console: Console,
+ backend_options: list[tuple[str, str]],
+ currently_enabled: list[int] | None = None,
+ is_first_time_setup: bool = False,
+) -> tuple[list[int], set[str]]:
"""Prompt user to select backend indices with validation.
Args:
@@ -162,17 +165,19 @@ def prompt_backend_indices(
is_first_time_setup: Whether this is the first time backends are being set up.
Returns:
- List of validated backend indices (0-based) selected by the user.
+ A tuple of (selected_indices, selected_backend_keys) where:
+ - selected_indices: List of validated backend indices (0-based).
+ - selected_backend_keys: Set of backend keys corresponding to selected indices.
Raises:
typer.Exit: If user chooses to quit.
"""
- # Determine default based on current selection or fallback to first option (pipelex_inference)
+ # Determine default based on current selection or fallback to first option (pipelex_gateway)
if currently_enabled and not is_first_time_setup:
default_indices = sorted(currently_enabled)
default_str = ",".join(str(i + 1) for i in default_indices)
else:
- # For first-time setup or no current selection, default to pipelex_inference (index 0)
+ # For first-time setup or no current selection, default to pipelex_gateway (index 0)
default_indices = [0]
default_str = "1"
@@ -223,7 +228,10 @@ def prompt_backend_indices(
f"Please enter numbers separated by commas or spaces, [cyan]a[/cyan] for all, or [cyan]q[/cyan] to quit.\n"
)
- return selected_indices
+ # Build set of selected backend keys
+ selected_backend_keys = {backend_options[idx][0] for idx in selected_indices}
+
+ return selected_indices, selected_backend_keys
def display_selected_backends(console: Console, selected_indices: list[int], backend_options: list[tuple[str, str]]) -> None:
diff --git a/pipelex/cli/commands/init/ui/gateway_ui.py b/pipelex/cli/commands/init/ui/gateway_ui.py
new file mode 100644
index 000000000..7d66086ce
--- /dev/null
+++ b/pipelex/cli/commands/init/ui/gateway_ui.py
@@ -0,0 +1,144 @@
+"""UI components for Pipelex Gateway terms acceptance flow."""
+
+from rich.console import Console, Group
+from rich.panel import Panel
+from rich.prompt import Confirm
+from rich.text import Text
+
+from pipelex.urls import URLs
+
+
+def build_gateway_terms_panel() -> Panel:
+ """Build a Rich Panel explaining Pipelex Gateway terms and telemetry.
+
+ Returns:
+ A Panel containing the gateway terms explanation.
+ """
+ title_text = Text("Pipelex Gateway Terms of Service", style="bold yellow")
+
+ intro = Text(
+ "You have selected Pipelex Gateway as an inference backend.\nBy using Pipelex Gateway, you agree to the following terms:\n",
+ style="white",
+ )
+
+ telemetry_header = Text("\n📊 Identified Telemetry Requirement\n", style="bold cyan")
+
+ telemetry_explanation = Text(
+ "When using Pipelex Gateway, identified telemetry is automatically enabled.\n"
+ "Your usage is associated with your Gateway API key (hashed for security).\n\n"
+ "This is independent from your telemetry.toml settings and allows us to:\n"
+ " • Monitor and improve service quality\n"
+ " • Enforce fair usage limits and prevent abuse\n"
+ " • Provide you with usage insights and better support\n\n"
+ "We collect ONLY technical and quantitative data:\n",
+ style="white",
+ )
+
+ collected_items = Text(
+ " ✓ Model names used (e.g., gpt-4o, claude-3.7-sonnet) and parameters\n"
+ " ✓ Pipe types (e.g., PipeLLM, PipeSequence, etc.)\n"
+ " ✓ Token counts (input/output)\n"
+ " ✓ Latency metrics\n"
+ " ✓ Error rates (without error details)\n",
+ style="green",
+ )
+
+ not_collected = Text(
+ "\nWe do NOT collect:\n",
+ style="white",
+ )
+
+ not_collected_items = Text(
+ " ✗ Your prompts or completions\n ✗ Your pipe codes or output class names\n ✗ File contents or business data\n",
+ style="red",
+ )
+
+ optional_note = Text(
+ "\n💡 This is Optional\n",
+ style="bold cyan",
+ )
+
+ optional_explanation = Text(
+ "Using Pipelex Gateway is entirely optional. If you prefer not to use our gateway:\n"
+ " • Disable pipelex_gateway in your backends configuration in .pipelex/inference/backends.toml\n"
+ " • Use your own API keys with direct provider backends (openai, anthropic, azure, bedrock, etc.)\n"
+ " • No telemetry will be sent to Pipelex servers\n",
+ style="white",
+ )
+
+ links = Text(
+ f"\n📚 Documentation: {URLs.documentation}\n🔒 Privacy Policy: {URLs.privacy_policy}\n💬 Questions? Join Discord: {URLs.discord}\n",
+ style="dim",
+ )
+
+ content = Group(
+ intro,
+ telemetry_header,
+ telemetry_explanation,
+ collected_items,
+ not_collected,
+ not_collected_items,
+ optional_note,
+ optional_explanation,
+ links,
+ )
+
+ return Panel(
+ content,
+ title=title_text,
+ border_style="yellow",
+ padding=(1, 2),
+ )
+
+
+def prompt_gateway_acceptance(console: Console) -> bool:
+ """Prompt the user to accept Pipelex Gateway terms.
+
+ Args:
+ console: Rich Console instance for user interaction.
+
+ Returns:
+ True if user accepts, False if declined.
+ """
+ console.print()
+ console.print(build_gateway_terms_panel())
+ console.print()
+
+ return Confirm.ask(
+ "[bold]Do you accept the Pipelex Gateway terms of service?[/bold]",
+ console=console,
+ default=True,
+ )
+
+
+def display_gateway_declined_message(console: Console) -> None:
+ """Display message when user declines gateway terms.
+
+ Args:
+ console: Rich Console instance for output.
+ """
+ console.print()
+ console.print("[yellow]⚠ Pipelex Gateway terms not accepted.[/yellow]")
+ console.print()
+ console.print("Pipelex Gateway has been disabled in your backends configuration.")
+ console.print()
+ console.print("[bold yellow]⚠ Important:[/bold yellow] If your routing profile uses pipelex_gateway as its default backend,")
+ console.print(" you will need to reconfigure your routing profile.")
+ console.print(" Run [cyan]pipelex init routing[/cyan] to select a different default backend.")
+ console.print()
+ console.print("[bold]Alternative options:[/bold]")
+ console.print(" • Use your own API keys with direct provider backends")
+ console.print(" • Available backends: openai, anthropic, google, bedrock, etc.")
+ console.print()
+ console.print(f"[dim]Need help? Visit {URLs.documentation} or join {URLs.discord}[/dim]")
+
+
+def display_gateway_accepted_message(console: Console) -> None:
+ """Display confirmation message when user accepts gateway terms.
+
+ Args:
+ console: Rich Console instance for output.
+ """
+ console.print()
+ console.print("[green]✓ Pipelex Gateway terms accepted.[/green]")
+ console.print("[dim]Identified telemetry (tied to your API key) will be enabled for service monitoring.[/dim]")
diff --git a/pipelex/cli/commands/init/ui/routing_ui.py b/pipelex/cli/commands/init/ui/routing_ui.py
index 082f29ddd..d53bafa51 100644
--- a/pipelex/cli/commands/init/ui/routing_ui.py
+++ b/pipelex/cli/commands/init/ui/routing_ui.py
@@ -109,8 +109,9 @@ def build_fallback_order_panel(remaining_backends: list[str], backend_options: l
table.add_row(f"[{idx}]", display_name)
description = Text(
- "Fallback order determines which backends to try when a model has no exact match or pattern match\n"
- "and is not available in your default backend.\nCurrent order:",
+ "Fallback order determines which backends to try when a model is not available in your default backend.\n"
+ "Enter indices to reorder (partial list OK - remaining backends keep their order).\n"
+ "Press Enter to keep the current order:",
style="dim",
)
@@ -137,14 +138,15 @@ def prompt_fallback_order(console: Console, remaining_backends: list[str], backe
console.print()
console.print("[dim]Enter the order of backends (space or comma separated indices).[/dim]")
- console.print("[dim]For example: '2 1 3' or '2,1,3' to reorder them.[/dim]")
+ console.print("[dim]You can provide a partial list - remaining backends will keep their current order.[/dim]")
+ console.print("[dim]For example: '2' puts backend 2 first, then the rest in order.[/dim]")
+ console.print("[dim]Press Enter to keep the current order.[/dim]")
console.print()
fallback_order: list[str] | None = None
while fallback_order is None:
- # Show current order as default
- default_order = " ".join(str(i + 1) for i in range(len(remaining_backends)))
- choice_str = Prompt.ask("[bold]Enter order[/bold]", default=default_order, console=console)
+ # Show current order as default (empty = keep order)
+ choice_str = Prompt.ask("[bold]Enter order[/bold]", default="", console=console)
choice_input = choice_str.strip()
# Handle empty input (use default order)
@@ -159,26 +161,25 @@ def prompt_fallback_order(console: Console, remaining_backends: list[str], backe
# Parse as 1-based indices from user input
user_indices = [int(part.strip()) for part in parts if part.strip()]
- # Validate: must have exactly the same number of indices
- if len(user_indices) != len(remaining_backends):
- console.print(f"[red]Error: You must specify all {len(remaining_backends)} backends.[/red] You provided {len(user_indices)}.\n")
- continue
-
# Validate: all indices are in range (1-based)
- invalid_indices = [i for i in user_indices if i < 1 or i > len(remaining_backends)]
+ invalid_indices = [idx for idx in user_indices if idx < 1 or idx > len(remaining_backends)]
if invalid_indices:
max_idx = len(remaining_backends)
console.print(f"[red]Invalid choice(s): {invalid_indices}.[/red] Please enter numbers between 1 and {max_idx}.\n")
continue
- # Validate: no duplicates
+ # Validate: no duplicates in user input
if len(user_indices) != len(set(user_indices)):
- console.print("[red]Error: Duplicate indices not allowed.[/red] Each backend must appear exactly once.\n")
+ console.print("[red]Error: Duplicate indices not allowed.[/red]\n")
continue
- # Convert to 0-based indices and reorder backends
- zero_based_indices = [i - 1 for i in user_indices]
- fallback_order = [remaining_backends[i] for i in zero_based_indices]
+ # Convert to 0-based indices
+ zero_based_indices = [idx - 1 for idx in user_indices]
+
+ # Build the fallback order: user-specified first, then remaining in original order
+ specified_backends: list[str] = [remaining_backends[idx] for idx in zero_based_indices]
+ remaining_in_order: list[str] = [backend for backend in remaining_backends if backend not in specified_backends]
+ fallback_order = specified_backends + remaining_in_order
break
except ValueError:
diff --git a/pipelex/cli/commands/init/ui/telemetry_ui.py b/pipelex/cli/commands/init/ui/telemetry_ui.py
deleted file mode 100644
index f9b891696..000000000
--- a/pipelex/cli/commands/init/ui/telemetry_ui.py
+++ /dev/null
@@ -1,83 +0,0 @@
-"""UI components for telemetry configuration in the init command."""
-
-import typer
-from rich.console import Console, Group
-from rich.panel import Panel
-from rich.prompt import Prompt
-from rich.table import Table
-from rich.text import Text
-
-from pipelex.system.telemetry.telemetry_config import TelemetryMode
-
-
-def build_telemetry_selection_panel() -> Panel:
- """Create a Rich Panel for telemetry mode selection.
-
- Returns:
- A Panel containing the telemetry selection interface.
- """
- table = Table(show_header=False, box=None, padding=(0, 2))
- table.add_column(style="bold cyan", justify="right")
- table.add_column(style="bold")
- table.add_column()
-
- table.add_row("[1]", TelemetryMode.OFF, "No telemetry data collected")
- table.add_row("[2]", TelemetryMode.ANONYMOUS, "Anonymous usage data only")
- table.add_row("[3]", TelemetryMode.IDENTIFIED, "Usage data with user identification")
- table.add_row("[Q]", "[dim]quit[/dim]", "[dim]Exit without configuring[/dim]")
-
- description = Text(
- "Pipelex can collect anonymous usage data to help improve the product.",
- style="dim",
- )
-
- return Panel(
- Group(description, Text(""), table),
- title="[bold yellow]Telemetry Configuration[/bold yellow]",
- border_style="yellow",
- padding=(1, 2),
- )
-
-
-def prompt_telemetry_mode(console: Console) -> TelemetryMode:
- """Prompt user to select telemetry mode with validation.
-
- Args:
- console: Rich Console instance for user interaction.
-
- Returns:
- Selected TelemetryMode.
-
- Raises:
- typer.Exit: If user chooses to quit.
- """
- # Map choice to telemetry mode
- mode_map: dict[str, TelemetryMode] = {
- "1": TelemetryMode.OFF,
- "2": TelemetryMode.ANONYMOUS,
- "3": TelemetryMode.IDENTIFIED,
- "off": TelemetryMode.OFF,
- "anonymous": TelemetryMode.ANONYMOUS,
- "identified": TelemetryMode.IDENTIFIED,
- }
-
- # Loop until valid input
- telemetry_mode: TelemetryMode | None = None
- while telemetry_mode is None:
- choice_str = Prompt.ask("[bold]Enter your choice[/bold]", console=console)
- choice_input = choice_str.lower().strip()
-
- # Handle quit option
- if choice_input in {"q", "quit"}:
- console.print("\n[yellow]Exiting without configuring telemetry.[/yellow]")
- raise typer.Exit(code=0)
-
- if choice_input in mode_map:
- telemetry_mode = mode_map[choice_input]
- else:
- console.print(
- f"[red]Invalid choice: '{choice_str}'.[/red] "
- "Please enter [cyan]1[/cyan], [cyan]2[/cyan], [cyan]3[/cyan], or [cyan]q[/cyan] to quit.\n"
- )
-
- return telemetry_mode
diff --git a/pipelex/cli/commands/run_cmd.py b/pipelex/cli/commands/run_cmd.py
index 3789e4277..7e3738b00 100644
--- a/pipelex/cli/commands/run_cmd.py
+++ b/pipelex/cli/commands/run_cmd.py
@@ -9,13 +9,12 @@ import typer
from posthog import tag
from pipelex import log
+from pipelex.cli.cli_factory import make_pipelex_for_cli
from pipelex.cli.error_handlers import (
ErrorContext,
handle_model_availability_error,
handle_model_choice_error,
- handle_model_deck_preset_error,
)
-from pipelex.cogt.exceptions import ModelDeckPresetValidatonError
from pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError
from pipelex.core.pipes.inputs.exceptions import PipeInputError
from pipelex.hub import get_console, get_telemetry_manager
@@ -196,10 +195,7 @@ def run_cmd(
typer.secho("✅ Pipeline execution completed successfully", fg=typer.colors.GREEN)
# Initialize Pipelex BEFORE telemetry context to ensure proper setup
- try:
- pipelex_instance = Pipelex.make(integration_mode=IntegrationMode.CLI)
- except ModelDeckPresetValidatonError as model_deck_error:
- handle_model_deck_preset_error(model_deck_error, context=ErrorContext.VALIDATION_BEFORE_PIPE_RUN)
+ make_pipelex_for_cli(context=ErrorContext.VALIDATION_BEFORE_PIPE_RUN)
try:
with get_telemetry_manager().telemetry_context():
@@ -225,4 +221,4 @@ def run_cmd(
raise typer.Exit(1) from exc
finally:
- pipelex_instance.teardown()
+ Pipelex.teardown_if_needed()
diff --git a/pipelex/cli/commands/show_cmd.py b/pipelex/cli/commands/show_cmd.py
index 125e212d1..0cd5553cf 100644
--- a/pipelex/cli/commands/show_cmd.py
+++ b/pipelex/cli/commands/show_cmd.py
@@ -11,12 +11,9 @@ from rich.table import Table
from pipelex import pretty_print
from pipelex.base_exceptions import PipelexConfigError
-from pipelex.cli.error_handlers import (
- ErrorContext,
- handle_model_deck_preset_error,
-)
+from pipelex.cli.cli_factory import make_pipelex_for_cli
+from pipelex.cli.error_handlers import ErrorContext
from pipelex.cli.exceptions import PipelexCLIError
-from pipelex.cogt.exceptions import ModelDeckPresetValidatonError
from pipelex.cogt.model_backends.backend_library import InferenceBackendLibrary
from pipelex.cogt.model_backends.model_lists import ModelLister
from pipelex.hub import (
@@ -196,22 +193,22 @@ def list_pipes_cmd() -> None:
This includes pipes from your project's .plx files and any
pipes from imported packages.
"""
- try:
- Pipelex.make(integration_mode=IntegrationMode.CLI)
- except ModelDeckPresetValidatonError as model_deck_error:
- handle_model_deck_preset_error(model_deck_error, context=ErrorContext.VALIDATION_BEFORE_SHOW_PIPES)
+ make_pipelex_for_cli(context=ErrorContext.VALIDATION_BEFORE_SHOW_PIPES)
- library_manager = get_library_manager()
- library_id, _ = library_manager.open_library()
- set_current_library(library_id=library_id)
- library_manager.load_libraries(library_id=library_id, library_dirs=[Path.cwd()])
+ try:
+ library_manager = get_library_manager()
+ library_id, _ = library_manager.open_library()
+ set_current_library(library_id=library_id)
+ library_manager.load_libraries(library_id=library_id, library_dirs=[Path.cwd()])
- with get_telemetry_manager().telemetry_context():
- tag(name=EventProperty.INTEGRATION, value=IntegrationMode.CLI)
- tag(name=EventProperty.PIPELEX_VERSION, value=get_package_version())
- tag(name=EventProperty.CLI_COMMAND, value=f"{COMMAND} {SUB_COMMAND_PIPES}")
+ with get_telemetry_manager().telemetry_context():
+ tag(name=EventProperty.INTEGRATION, value=IntegrationMode.CLI)
+ tag(name=EventProperty.PIPELEX_VERSION, value=get_package_version())
+ tag(name=EventProperty.CLI_COMMAND, value=f"{COMMAND} {SUB_COMMAND_PIPES}")
- do_list_pipes()
+ do_list_pipes()
+ finally:
+ Pipelex.teardown_if_needed()
@show_app.command("pipe", help="Display the detailed definition of a specific pipe")
@@ -224,22 +221,22 @@ def show_pipe_cmd(
Example:
pipelex show pipe hello_world
"""
- try:
- Pipelex.make(integration_mode=IntegrationMode.CLI)
- except ModelDeckPresetValidatonError as model_deck_error:
- handle_model_deck_preset_error(model_deck_error, context=ErrorContext.VALIDATION_BEFORE_SHOW_PIPE)
+ make_pipelex_for_cli(context=ErrorContext.VALIDATION_BEFORE_SHOW_PIPE)
- library_manager = get_library_manager()
- library_id, _ = library_manager.open_library()
- set_current_library(library_id=library_id)
- library_manager.load_libraries(library_id=library_id, library_dirs=[Path.cwd()])
+ try:
+ library_manager = get_library_manager()
+ library_id, _ = library_manager.open_library()
+ set_current_library(library_id=library_id)
+ library_manager.load_libraries(library_id=library_id, library_dirs=[Path.cwd()])
- with get_telemetry_manager().telemetry_context():
- tag(name=EventProperty.INTEGRATION, value=IntegrationMode.CLI)
- tag(name=EventProperty.PIPELEX_VERSION, value=get_package_version())
- tag(name=EventProperty.CLI_COMMAND, value=f"{COMMAND} {SUB_COMMAND_PIPE}")
+ with get_telemetry_manager().telemetry_context():
+ tag(name=EventProperty.INTEGRATION, value=IntegrationMode.CLI)
+ tag(name=EventProperty.PIPELEX_VERSION, value=get_package_version())
+ tag(name=EventProperty.CLI_COMMAND, value=f"{COMMAND} {SUB_COMMAND_PIPE}")
- do_show_pipe(pipe_code=pipe_code)
+ do_show_pipe(pipe_code=pipe_code)
+ finally:
+ Pipelex.teardown_if_needed()
@show_app.command("models", help="List available AI models from a specific backend provider")
@@ -259,10 +256,7 @@ def show_models_cmd(
pipelex show models openai
pipelex show models anthropic --flat
"""
- try:
- pipelex_instance = Pipelex.make(integration_mode=IntegrationMode.CLI)
- except ModelDeckPresetValidatonError as model_deck_error:
- handle_model_deck_preset_error(model_deck_error, context=ErrorContext.VALIDATION_BEFORE_SHOW_MODELS)
+ make_pipelex_for_cli(context=ErrorContext.VALIDATION_BEFORE_SHOW_MODELS)
try:
with get_telemetry_manager().telemetry_context():
@@ -277,7 +271,7 @@ def show_models_cmd(
)
)
finally:
- pipelex_instance.teardown()
+ Pipelex.teardown_if_needed()
@show_app.command("backends", help="Display backend configurations and active routing profile")
@@ -292,14 +286,14 @@ def show_backends_cmd(
pipelex show backends
pipelex show backends --all
"""
- try:
- Pipelex.make(integration_mode=IntegrationMode.CLI)
- except ModelDeckPresetValidatonError as model_deck_error:
- handle_model_deck_preset_error(model_deck_error, context=ErrorContext.VALIDATION_BEFORE_SHOW_BACKENDS)
+ make_pipelex_for_cli(context=ErrorContext.VALIDATION_BEFORE_SHOW_BACKENDS)
- with get_telemetry_manager().telemetry_context():
- tag(name=EventProperty.INTEGRATION, value=IntegrationMode.CLI)
- tag(name=EventProperty.PIPELEX_VERSION, value=get_package_version())
- tag(name=EventProperty.CLI_COMMAND, value=f"{COMMAND} {SUB_COMMAND_BACKENDS}")
+ try:
+ with get_telemetry_manager().telemetry_context():
+ tag(name=EventProperty.INTEGRATION, value=IntegrationMode.CLI)
+ tag(name=EventProperty.PIPELEX_VERSION, value=get_package_version())
+ tag(name=EventProperty.CLI_COMMAND, value=f"{COMMAND} {SUB_COMMAND_BACKENDS}")
- do_show_backends(show_all=show_all_backends)
+ do_show_backends(show_all=show_all_backends)
+ finally:
+ Pipelex.teardown_if_needed()
diff --git a/pipelex/cli/commands/validate_cmd.py b/pipelex/cli/commands/validate_cmd.py
index 26b29ddaf..4c3a5fd3b 100644
--- a/pipelex/cli/commands/validate_cmd.py
+++ b/pipelex/cli/commands/validate_cmd.py
@@ -10,14 +10,13 @@ from posthog import tag
from rich.traceback import Traceback
from pipelex import log
+from pipelex.cli.cli_factory import make_pipelex_for_cli
from pipelex.cli.error_handlers import (
ErrorContext,
handle_model_availability_error,
handle_model_choice_error,
- handle_model_deck_preset_error,
handle_validate_bundle_error,
)
-from pipelex.cogt.exceptions import ModelDeckPresetValidatonError
from pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError
from pipelex.hub import get_console, get_library_manager, get_required_pipe, get_telemetry_manager, set_current_library
from pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityError
@@ -78,12 +77,13 @@ def validate_cmd(
pipelex validate --bundle my_bundle.plx --pipe my_pipe
pipelex validate all
"""
- pipelex_instance: Pipelex
# Check for "all" keyword
if target == "all" and not pipe and not bundle:
- pipelex_instance = Pipelex.make(integration_mode=IntegrationMode.CLI)
- do_validate_all_libraries_and_dry_run()
- pipelex_instance.teardown()
+ try:
+ make_pipelex_for_cli(context=ErrorContext.VALIDATION)
+ do_validate_all_libraries_and_dry_run()
+ finally:
+ Pipelex.teardown_if_needed()
return
# Validate mutual exclusivity
@@ -159,10 +159,7 @@ def validate_cmd(
typer.secho("Failed to validate: no pipe code or bundle specified", fg=typer.colors.RED, err=True)
raise typer.Exit(1)
- try:
- pipelex_instance = Pipelex.make(integration_mode=IntegrationMode.CLI)
- except ModelDeckPresetValidatonError as model_deck_error:
- handle_model_deck_preset_error(model_deck_error, context=ErrorContext.VALIDATION)
+ make_pipelex_for_cli(context=ErrorContext.VALIDATION)
try:
with get_telemetry_manager().telemetry_context():
@@ -179,4 +176,4 @@ def validate_cmd(
except PipeOperatorModelAvailabilityError as exc:
handle_model_availability_error(exc, context=ErrorContext.VALIDATION)
finally:
- pipelex_instance.teardown()
+ Pipelex.teardown_if_needed()
diff --git a/pipelex/cli/dev_cli/_dev_cli.py b/pipelex/cli/dev_cli/_dev_cli.py
index a2c418a48..6e643e197 100644
--- a/pipelex/cli/dev_cli/_dev_cli.py
+++ b/pipelex/cli/dev_cli/_dev_cli.py
@@ -10,6 +10,7 @@ from typing_extensions import override
from pipelex.cli.dev_cli.commands.check_config_sync_cmd import LeadingConfig, check_config_sync_cmd
from pipelex.cli.dev_cli.commands.check_rules_sync_cmd import check_rules_sync_cmd
+from pipelex.cli.dev_cli.commands.check_urls_cmd import DEFAULT_TIMEOUT, check_urls_cmd
from pipelex.hub import get_console
from pipelex.tools.misc.package_utils import get_package_version
@@ -20,7 +21,7 @@ class PipelexDevCLI(TyperGroup):
@override
def list_commands(self, ctx: Context) -> list[str]:
"""List commands in proper order."""
- return ["check-config-sync", "check-rules"]
+ return ["check-config-sync", "check-rules", "check-urls"]
@override
def get_command(self, ctx: Context, cmd_name: str) -> Command | None:
@@ -84,3 +85,12 @@ def check_rules_command(
) -> None:
"""Verify that installed agent rules match kit templates."""
check_rules_sync_cmd(show_diff=show_diff, quiet=quiet)
+
+
[email protected](name="check-urls", help="Check all URLs in pipelex/urls.py for broken links")
+def check_urls_command(
+ quiet: Annotated[bool, typer.Option("--quiet", "-q", help="Output only a single validation line")] = False,
+ timeout: Annotated[int, typer.Option("--timeout", "-t", help="Request timeout in seconds")] = DEFAULT_TIMEOUT,
+) -> None:
+ """Check all URLs in pipelex/urls.py for broken links."""
+ check_urls_cmd(quiet=quiet, timeout=timeout)
diff --git a/pipelex/cli/dev_cli/commands/check_config_sync_cmd.py b/pipelex/cli/dev_cli/commands/check_config_sync_cmd.py
index 254911543..06b2e899e 100644
--- a/pipelex/cli/dev_cli/commands/check_config_sync_cmd.py
+++ b/pipelex/cli/dev_cli/commands/check_config_sync_cmd.py
@@ -11,6 +11,12 @@ from pipelex.hub import get_console
from pipelex.tools.misc.diff import has_diff_dirs, make_diff_dirs_pretty
from pipelex.types import StrEnum
+# Files excluded from config sync check because they have intentionally different values
+# between the template (for new users) and the dev config (for developers/tests).
+# - pipelex_service.toml: Contains terms_accepted which is False in template
+# (for new users) but True in dev config (for developers/tests)
+CONFIG_SYNC_EXCLUDE_FILES = {"pipelex_service.toml"}
+
class LeadingConfig(StrEnum):
"""Enum for leading configuration options."""
@@ -71,8 +77,8 @@ def check_config_sync_cmd(
left_label = "pipelex/kit/configs"
right_label = ".pipelex"
- # Check for differences
- has_diff = has_diff_dirs(left_dir, right_dir)
+ # Check for differences (excluding files that intentionally differ)
+ has_diff = has_diff_dirs(left_dir, right_dir, exclude_files=CONFIG_SYNC_EXCLUDE_FILES)
if not has_diff:
# No differences found
@@ -107,7 +113,7 @@ def check_config_sync_cmd(
if show_diff:
console.print()
- pretty_diff = make_diff_dirs_pretty(left_dir, right_dir)
+ pretty_diff = make_diff_dirs_pretty(left_dir, right_dir, exclude_files=CONFIG_SYNC_EXCLUDE_FILES)
console.print(pretty_diff)
console.print()
diff --git a/pipelex/cli/dev_cli/commands/check_urls_cmd.py b/pipelex/cli/dev_cli/commands/check_urls_cmd.py
new file mode 100644
index 000000000..0053c4ace
--- /dev/null
+++ b/pipelex/cli/dev_cli/commands/check_urls_cmd.py
@@ -0,0 +1,231 @@
+"""Command to check all URLs defined in pipelex/urls.py for broken links."""
+
+from __future__ import annotations
+
+import asyncio
+import inspect
+import sys
+
+import httpx
+from pydantic import BaseModel
+from rich.panel import Panel
+from rich.table import Table
+
+from pipelex.hub import get_console
+from pipelex.urls import URLs
+
+# Default timeout in seconds for HTTP requests
+DEFAULT_TIMEOUT = 10
+
+# Connection limits for httpx client
+# - max_connections: Total concurrent connections across all hosts
+# - max_keepalive_connections: Connections to keep alive for reuse
+HTTP_LIMITS = httpx.Limits(max_connections=20, max_keepalive_connections=10)
+
+
+class URLCheckResult(BaseModel):
+ """Result of checking a single URL."""
+
+ name: str
+ url: str
+ status_code: int | None
+ is_ok: bool
+ error_message: str | None = None
+
+
+def get_all_urls_from_class() -> list[tuple[str, str]]:
+ """Extract all URL attributes from the URLs class.
+
+ Returns:
+ List of tuples containing (attribute_name, url_value)
+ """
+ url_pairs: list[tuple[str, str]] = []
+ for name, value in inspect.getmembers(URLs):
+ # Skip private attributes and methods
+ if name.startswith("_"):
+ continue
+ # Only include string values that look like URLs
+ if isinstance(value, str) and value.startswith("http"):
+ url_pairs.append((name, value))
+ return url_pairs
+
+
+async def check_single_url_async(
+ client: httpx.AsyncClient,
+ name: str,
+ url: str,
+) -> URLCheckResult:
+ """Check if a single URL is accessible asynchronously.
+
+ Args:
+ client: The async HTTP client to use
+ name: The attribute name of the URL
+ url: The URL to check
+
+ Returns:
+ URLCheckResult with the check outcome
+ """
+ try:
+ response = await client.head(url)
+ # Some servers don't support HEAD, fallback to GET
+ if response.status_code == 405:
+ response = await client.get(url)
+ is_ok = response.status_code < 400
+ return URLCheckResult(
+ name=name,
+ url=url,
+ status_code=response.status_code,
+ is_ok=is_ok,
+ error_message=None if is_ok else f"HTTP {response.status_code}",
+ )
+ except httpx.TimeoutException:
+ return URLCheckResult(
+ name=name,
+ url=url,
+ status_code=None,
+ is_ok=False,
+ error_message="Timeout",
+ )
+ except httpx.ConnectError as exc:
+ return URLCheckResult(
+ name=name,
+ url=url,
+ status_code=None,
+ is_ok=False,
+ error_message=f"Connection error: {exc}",
+ )
+ except httpx.HTTPError as exc:
+ return URLCheckResult(
+ name=name,
+ url=url,
+ status_code=None,
+ is_ok=False,
+ error_message=f"HTTP error: {exc}",
+ )
+
+
+async def check_all_urls_async(
+ url_pairs: list[tuple[str, str]],
+ request_timeout: int,
+) -> list[URLCheckResult]:
+ """Check all URLs concurrently with connection pooling.
+
+ Uses httpx.Limits for connection management which automatically handles
+ per-host connection limits and connection reuse.
+
+ Args:
+ url_pairs: List of (name, url) tuples to check
+ request_timeout: Request timeout in seconds
+
+ Returns:
+ List of URLCheckResult for all URLs
+ """
+ async with httpx.AsyncClient(
+ follow_redirects=True,
+ timeout=request_timeout,
+ limits=HTTP_LIMITS,
+ ) as client:
+ tasks = [check_single_url_async(client, name, url) for name, url in url_pairs]
+ results = await asyncio.gather(*tasks)
+ return list(results)
+
+
+def check_urls_cmd(quiet: bool = False, timeout: int = DEFAULT_TIMEOUT) -> None:
+ """Check all URLs defined in pipelex/urls.py for broken links.
+
+ Args:
+ quiet: If True, output only a single validation line (for use in Make targets)
+ timeout: Request timeout in seconds
+ """
+ console = get_console()
+
+ # Get all URLs from the URLs class
+ url_pairs = get_all_urls_from_class()
+
+ if not url_pairs:
+ if quiet:
+ console.print("[yellow]⚠ URL check: No URLs found[/yellow]")
+ else:
+ console.print()
+ console.print("[yellow]⚠[/yellow] No URLs found in pipelex/urls.py")
+ console.print()
+ return
+
+ if not quiet:
+ console.print()
+ console.print("[bold]Checking URLs defined in pipelex/urls.py...[/bold]")
+ console.print(f" Found [cyan]{len(url_pairs)}[/cyan] URLs to check (running in parallel)")
+ console.print()
+
+ # Check all URLs concurrently
+ results = asyncio.run(check_all_urls_async(url_pairs, request_timeout=timeout))
+
+ # Sort results by name for consistent output
+ results.sort(key=lambda result: result.name)
+
+ # Display individual results if not quiet
+ if not quiet:
+ for result in results:
+ if result.is_ok:
+ console.print(f" [dim]{result.name}[/dim] [green]✓[/green] {result.status_code}")
+ else:
+ console.print(f" [dim]{result.name}[/dim] [red]✗[/red] {result.error_message}")
+
+ # Count successes and failures
+ ok_count = sum(1 for result in results if result.is_ok)
+ broken_count = len(results) - ok_count
+ broken_results = [result for result in results if not result.is_ok]
+
+ if broken_count == 0:
+ # All URLs are OK
+ if quiet:
+ console.print(f"[green]✓ URL check: PASSED[/green] ({ok_count} URLs checked)")
+ else:
+ console.print()
+ success_message = (
+ f"[green]✓[/green] All {ok_count} URLs are accessible!\n\n"
+ "[dim]All URLs defined in pipelex/urls.py returned successful responses.[/dim]"
+ )
+ success_panel = Panel(
+ success_message,
+ title="[bold green]URL Check: PASSED[/bold green]",
+ border_style="green",
+ padding=(1, 2),
+ )
+ console.print(success_panel)
+ console.print()
+ else:
+ # Some URLs are broken
+ if quiet:
+ console.print(f"[red]✗ URL check: FAILED[/red] ({broken_count} broken out of {len(results)})")
+ console.print(" Run [cyan]make cu[/cyan] for details")
+ else:
+ console.print()
+ error_panel = Panel(
+ f"[red]✗[/red] Found [bold]{broken_count}[/bold] broken URL(s)!\n\n[dim]{ok_count} URLs are OK, {broken_count} need attention.[/dim]",
+ title="[bold red]URL Check: FAILED[/bold red]",
+ border_style="red",
+ padding=(1, 2),
+ )
+ console.print(error_panel)
+ console.print()
+
+ # Display table of broken URLs
+ table = Table(title="Broken URLs", show_header=True, header_style="bold red")
+ table.add_column("Attribute", style="cyan")
+ table.add_column("URL", style="dim")
+ table.add_column("Error", style="red")
+
+ for result in broken_results:
+ table.add_row(result.name, result.url, result.error_message or "Unknown error")
+
+ console.print(table)
+ console.print()
+
+ console.print("[bold yellow]Recommended Actions:[/bold yellow]")
+ console.print(" • Verify the URLs are correct in [cyan]pipelex/urls.py[/cyan]")
+ console.print(" • Check if the target pages have moved or been removed")
+ console.print(" • Update any broken URLs with correct paths")
+ console.print()
+
+ sys.exit(1)
diff --git a/pipelex/cli/error_handlers.py b/pipelex/cli/error_handlers.py
index 140f540cb..b4c66ba14 100644
--- a/pipelex/cli/error_handlers.py
+++ b/pipelex/cli/error_handlers.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, NoReturn
+from typing import NoReturn
import typer
@@ -6,12 +6,18 @@ from pipelex.cogt.exceptions import ModelDeckPresetValidatonError
from pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError
from pipelex.hub import get_console
from pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityError
+from pipelex.pipeline.validate_bundle import ValidateBundleError
+from pipelex.system.pipelex_service.exceptions import (
+ GatewayApiKeyMissingError,
+ GatewayDoNotTrackConflictError,
+ GatewayTermsNotAcceptedError,
+ RemoteConfigFetchError,
+ RemoteConfigValidationError,
+)
+from pipelex.system.telemetry.exceptions import TelemetryConfigValidationError
from pipelex.types import StrEnum
from pipelex.urls import URLs
-if TYPE_CHECKING:
- from pipelex.pipeline.validate_bundle import ValidateBundleError
-
class ErrorContext(StrEnum):
"""Context for error messages in CLI commands."""
@@ -115,7 +121,7 @@ def handle_model_deck_preset_error(exc: ModelDeckPresetValidatonError, context:
raise typer.Exit(1) from exc
-def handle_validate_bundle_error(exc: "ValidateBundleError", bundle_path: str | None = None) -> NoReturn:
+def handle_validate_bundle_error(exc: ValidateBundleError, bundle_path: str | None = None) -> NoReturn:
"""Handle and display ValidateBundleError with formatted output.
Args:
@@ -172,3 +178,187 @@ def handle_validate_bundle_error(exc: "ValidateBundleError", bundle_path: str |
console.print(f"[dim]Learn more: {URLs.documentation}[/dim]")
console.print(f"[dim]Join our Discord for help: {URLs.discord}[/dim]\n")
raise typer.Exit(1) from exc
+
+
+def handle_telemetry_config_validation_error(exc: TelemetryConfigValidationError) -> NoReturn:
+ """Handle and display TelemetryConfigValidationError with migration guidance.
+
+ This error typically occurs when users have an old telemetry.toml format
+ that doesn't match the new nested structure.
+
+ Args:
+ exc: The telemetry config validation error exception
+ """
+ console = get_console()
+ console.print("\n[bold red]❌ Telemetry configuration format has changed[/bold red]\n")
+
+ console.print(
+ "[bold yellow]⚠ Breaking Change:[/bold yellow] The telemetry.toml format has been updated.\n"
+ "Your existing configuration uses the old flat format.\n"
+ )
+
+ console.print("[bold green]💡 To fix:[/bold green] Run [cyan]pipelex init telemetry[/cyan] to create a new config\n")
+
+ console.print("[dim]This update brings powerful new telemetry options:[/dim]")
+ console.print("[dim] • Langfuse integration for LLM observability[/dim]")
+ console.print("[dim] • Support for any OpenTelemetry backend via OTLP exporters[/dim]")
+ console.print("[dim] • Cleaner separation of PostHog, Langfuse, and OTLP settings[/dim]")
+ console.print()
+
+ console.print(f"[dim]Join our Discord for help: {URLs.discord}[/dim]\n")
+ raise typer.Exit(1) from exc
+
+
+def handle_gateway_terms_not_accepted_error(exc: GatewayTermsNotAcceptedError) -> NoReturn:
+ """Handle and display GatewayTermsNotAcceptedError with user-friendly guidance.
+
+ This error occurs when Pipelex Gateway is enabled but the user hasn't
+ accepted the terms of service yet.
+
+ Args:
+ exc: The gateway terms not accepted error exception
+ """
+ console = get_console()
+ console.print("\n[bold red]❌ Pipelex Gateway terms not accepted[/bold red]\n")
+
+ console.print("[bold yellow]⚠ Action Required:[/bold yellow] Pipelex Gateway is enabled but you haven't accepted\nthe terms of service yet.\n")
+
+ console.print("[bold green]💡 To fix:[/bold green] Run [cyan]pipelex init config[/cyan] to configure your backends and accept the terms\n")
+
+ console.print("[dim]Alternatively, you can:[/dim]")
+ console.print("[dim] • Disable pipelex_gateway in .pipelex/inference/backends.toml[/dim]")
+ console.print("[dim] • Use your own API keys with direct provider backends[/dim]")
+ console.print()
+
+ console.print(f"[dim]For more information: {URLs.gateway_docs}[/dim]")
+ console.print(f"[dim]Join our Discord for help: {URLs.discord}[/dim]\n")
+ raise typer.Exit(1) from exc
+
+
+def handle_gateway_api_key_missing_error(exc: GatewayApiKeyMissingError) -> NoReturn:
+ """Handle and display GatewayApiKeyMissingError with user-friendly guidance.
+
+ This error occurs when Pipelex Gateway is enabled but the PIPELEX_GATEWAY_API_KEY
+ environment variable is not set.
+
+ Args:
+ exc: The gateway API key missing error exception
+ """
+ console = get_console()
+ console.print("\n[bold red]❌ Pipelex Gateway API key not set[/bold red]\n")
+
+ console.print("[bold yellow]⚠ Action Required:[/bold yellow] Pipelex Gateway is enabled but the API key\nenvironment variable is not set.\n")
+
+ console.print("[bold green]💡 To fix:[/bold green]")
+ console.print(f" • Get your API key at: [cyan]{URLs.app}[/cyan]")
+ console.print(" • Set the [cyan]PIPELEX_GATEWAY_API_KEY[/cyan] environment variable")
+ console.print()
+
+ console.print("[dim]Alternatively, you can:[/dim]")
+ console.print("[dim] • Disable pipelex_gateway in .pipelex/inference/backends.toml[/dim]")
+ console.print("[dim] • Use your own API keys with direct provider backends[/dim]")
+ console.print()
+
+ console.print(f"[dim]For more information: {URLs.gateway_docs}[/dim]")
+ console.print(f"[dim]Join our Discord for help: {URLs.discord}[/dim]\n")
+ raise typer.Exit(1) from exc
+
+
+def handle_gateway_do_not_track_conflict_error(exc: GatewayDoNotTrackConflictError) -> NoReturn:
+ """Handle and display GatewayDoNotTrackConflictError with user-friendly guidance.
+
+ This error occurs when Pipelex Gateway is enabled but the user has set
+ a DO_NOT_TRACK environment variable, which conflicts with gateway's telemetry requirement.
+
+ Args:
+ exc: The gateway do not track conflict error exception
+ """
+ console = get_console()
+ console.print("\n[bold red]❌ Pipelex Gateway requires telemetry[/bold red]\n")
+
+ console.print(
+ "[bold yellow]⚠ Conflict:[/bold yellow] Pipelex Gateway requires telemetry for service monitoring,\n"
+ "but you have set DO_NOT_TRACK. We respect your privacy preference.\n"
+ )
+
+ console.print("[bold green]💡 To fix, choose one option:[/bold green]")
+ console.print(" • [cyan]Unset[/cyan] the DO_NOT_TRACK environment variable to use Gateway")
+ console.print(" • [cyan]Or[/cyan] disable pipelex_gateway in .pipelex/inference/backends.toml")
+ console.print(" and use your own API keys with direct provider backends")
+ console.print()
+
+ console.print(f"[dim]For more information: {URLs.gateway_docs}[/dim]")
+ console.print(f"[dim]Join our Discord for help: {URLs.discord}[/dim]\n")
+ raise typer.Exit(1) from exc
+
+
+def handle_remote_config_fetch_error(exc: RemoteConfigFetchError) -> NoReturn:
+ """Handle and display RemoteConfigFetchError with user-friendly guidance.
+
+ This error occurs when Pipelex Gateway is enabled but the remote configuration
+ cannot be fetched (network issues, server unreachable, etc.).
+
+ Args:
+ exc: The remote config fetch error exception
+ """
+ console = get_console()
+ console.print("\n[bold red]❌ Could not connect to Pipelex Gateway[/bold red]\n")
+
+ console.print(
+ "[bold yellow]⚠ Network Issue:[/bold yellow] Pipelex Gateway requires network access to fetch\n"
+ "configuration, but we couldn't reach the Pipelex servers.\n"
+ )
+
+ console.print("[bold cyan]Error details:[/bold cyan]")
+ console.print(f" {exc}\n")
+
+ console.print("[bold green]💡 To fix:[/bold green]")
+ console.print(" • Check your internet connection")
+ console.print(" • Verify that firewall/proxy settings allow outbound HTTPS requests")
+ console.print(" • Try again in a few moments (servers may be temporarily unavailable)")
+ console.print()
+
+ console.print("[dim]Alternatively, you can:[/dim]")
+ console.print("[dim] • Disable pipelex_gateway in .pipelex/inference/backends.toml[/dim]")
+ console.print("[dim] • Use your own API keys with direct provider backends[/dim]")
+ console.print()
+
+ console.print(f"[dim]For more information: {URLs.gateway_docs}[/dim]")
+ console.print(f"[dim]Join our Discord for help: {URLs.discord}[/dim]\n")
+ raise typer.Exit(1) from exc
+
+
+def handle_remote_config_validation_error(exc: RemoteConfigValidationError) -> NoReturn:
+ """Handle and display RemoteConfigValidationError with user-friendly guidance.
+
+ This error occurs when Pipelex Gateway remote configuration was fetched but
+ the data is malformed or doesn't match the expected schema.
+
+ Args:
+ exc: The remote config validation error exception
+ """
+ console = get_console()
+ console.print("\n[bold red]❌ Pipelex Gateway configuration is invalid[/bold red]\n")
+
+ console.print(
+ "[bold yellow]⚠ Server Issue:[/bold yellow] The Pipelex Gateway configuration was received but\n"
+ "couldn't be validated. This is a server-side issue that we need to fix.\n"
+ )
+
+ console.print("[bold cyan]Error details:[/bold cyan]")
+ console.print(f" {exc}\n")
+
+ console.print("[bold red]🚨 Please report this![/bold red]")
+ console.print(" This error shouldn't happen and we want to fix it ASAP.")
+ console.print(" Please copy-paste this error to:")
+ console.print(f" • Discord: [cyan]{URLs.discord}[/cyan]")
+ console.print(f" • GitHub Issues: [cyan]{URLs.repository}/issues[/cyan]")
+ console.print()
+
+ console.print("[dim]In the meantime, you can:[/dim]")
+ console.print("[dim] • Disable pipelex_gateway in .pipelex/inference/backends.toml[/dim]")
+ console.print("[dim] • Use your own API keys with direct provider backends[/dim]")
+ console.print()
+
+ console.print(f"[dim]For more information: {URLs.gateway_docs}[/dim]\n")
+ raise typer.Exit(1) from exc
diff --git a/pipelex/client/client.py b/pipelex/client/client.py
index 169357abf..7277114c3 100644
--- a/pipelex/client/client.py
+++ b/pipelex/client/client.py
@@ -20,7 +20,7 @@ class PipelexClient(PipelexProtocol):
the remote API.
Args:
- api_token: The API token to use for authentication. If not provided, it will be loaded from the PIPELEX_API_TOKEN environment variable.
+ api_token: The API token to use for authentication. If not provided, it will be loaded from the PIPELEX_API_KEY environment variable.
If the environment variable is not set, an error will be raised.
"""
diff --git a/pipelex/cogt/config_cogt.py b/pipelex/cogt/config_cogt.py
index 4d8c0aac8..a52c6aaa2 100644
--- a/pipelex/cogt/config_cogt.py
+++ b/pipelex/cogt/config_cogt.py
@@ -1,3 +1,5 @@
+from pydantic import Field
+
from pipelex.cogt.exceptions import LLMConfigError
from pipelex.cogt.img_gen.img_gen_job_components import ImgGenJobConfig, ImgGenJobParams, ImgGenJobParamsDefaults
from pipelex.cogt.llm.llm_job_components import LLMJobConfig
@@ -43,8 +45,16 @@ class LLMConfig(ConfigModel):
return template
+class TenacityConfig(ConfigModel):
+ max_retries: int = Field(..., ge=1, le=100, description="Maximum number of retry attempts before giving up")
+ wait_multiplier: float = Field(..., ge=0.1, le=10, description="Multiplier applied to the wait time between retries (in seconds)")
+ wait_max: float = Field(..., ge=0.1, le=20, description="Maximum wait time between retries (in seconds)")
+ wait_exp_base: float = Field(..., ge=1.1, le=10, description="Base for exponential backoff calculation")
+
+
class Cogt(ConfigModel):
model_deck_config: ModelDeckConfig
+ tenacity_config: TenacityConfig
llm_config: LLMConfig
img_gen_config: ImgGenConfig
extract_config: ExtractConfig
diff --git a/pipelex/cogt/exceptions.py b/pipelex/cogt/exceptions.py
index 67b8330c3..b62958d85 100644
--- a/pipelex/cogt/exceptions.py
+++ b/pipelex/cogt/exceptions.py
@@ -169,6 +169,10 @@ class ExtractCapabilityError(CogtError):
pass
+class ExtractJobFailureError(CogtError):
+ pass
+
+
class RoutingProfileLibraryNotFoundError(CogtError):
pass
diff --git a/pipelex/cogt/extract/extract_worker_factory.py b/pipelex/cogt/extract/extract_worker_factory.py
index b7b60b1e4..88ac06832 100644
--- a/pipelex/cogt/extract/extract_worker_factory.py
+++ b/pipelex/cogt/extract/extract_worker_factory.py
@@ -9,8 +9,9 @@ from pipelex.reporting.reporting_protocol import ReportingProtocol
class ExtractWorkerFactory:
+ @classmethod
def make_extract_worker(
- self,
+ cls,
inference_model: InferenceModelSpec,
reporting_delegate: ReportingProtocol | None = None,
) -> ExtractWorkerAbstract:
@@ -19,6 +20,21 @@ class ExtractWorkerFactory:
plugin_sdk_registry = get_plugin_manager().plugin_sdk_registry
extract_worker: ExtractWorkerAbstract
match plugin.sdk:
+ case "gateway_extract":
+ from pipelex.plugins.gateway.gateway_extract_worker import PortkeyExtractWorker # noqa: PLC0415
+ from pipelex.plugins.gateway.gateway_factory import GatewayFactory # noqa: PLC0415
+
+ extract_sdk_instance = plugin_sdk_registry.get_sdk_instance(plugin=plugin) or plugin_sdk_registry.set_sdk_instance(
+ plugin=plugin,
+ sdk_instance=GatewayFactory.make_portkey_client(backend=backend),
+ )
+
+ extract_worker = PortkeyExtractWorker(
+ sdk_instance=extract_sdk_instance,
+ extra_config=backend.extra_config,
+ inference_model=inference_model,
+ reporting_delegate=reporting_delegate,
+ )
case "mistral":
if importlib.util.find_spec("mistralai") is None:
lib_name = "mistralai"
diff --git a/pipelex/cogt/image/prompt_image.py b/pipelex/cogt/image/prompt_image.py
index 269479de0..e06a5d24b 100644
--- a/pipelex/cogt/image/prompt_image.py
+++ b/pipelex/cogt/image/prompt_image.py
@@ -1,6 +1,6 @@
import base64
-from abc import ABC
-from typing import Union
+from abc import ABC, abstractmethod
+from typing import Literal, Union
from pydantic import BaseModel
from typing_extensions import override
@@ -13,6 +13,17 @@ from pipelex.tools.misc.filetype_utils import (
detect_file_type_from_path,
)
from pipelex.tools.typing.pydantic_utils import CustomBaseModel
+from pipelex.types import StrEnum
+
+
+class PromptImageDetail(StrEnum):
+ HIGH = "high"
+ LOW = "low"
+ AUTO = "auto"
+
+ @property
+ def as_openai_detail(self) -> Literal["high", "low", "auto"]:
+ return self.value
class PromptImageTypedBase64(CustomBaseModel):
@@ -24,7 +35,9 @@ PromptImageTypedUrlOrBase64 = Union[str, PromptImageTypedBase64]
class PromptImage(BaseModel, ABC):
- pass
+ @abstractmethod
+ def short_description(self) -> str:
+ pass
class PromptImagePath(PromptImage):
@@ -40,6 +53,10 @@ class PromptImagePath(PromptImage):
def __str__(self) -> str:
return f"PromptImagePath(file_path='{self.file_path}')"
+ @override
+ def short_description(self) -> str:
+ return f"file path: {self.file_path}"
+
class PromptImageUrl(PromptImage):
url: str
@@ -53,6 +70,10 @@ class PromptImageUrl(PromptImage):
def __format__(self, format_spec: str) -> str:
return self.__str__()
+ @override
+ def short_description(self) -> str:
+ return self.url
+
class PromptImageBase64(PromptImage):
base_64: bytes
@@ -83,6 +104,10 @@ class PromptImageBase64(PromptImage):
def make_prompt_image_typed_base64(self) -> PromptImageTypedBase64:
return PromptImageTypedBase64(base_64=self.base_64, file_type=self.get_file_type())
+ @override
+ def short_description(self) -> str:
+ return f"base64: {self.base_64[:100].decode('ascii', errors='replace')}..."
+
class PromptImageBinary(PromptImage):
binary: bytes
@@ -100,3 +125,7 @@ class PromptImageBinary(PromptImage):
@override
def __repr__(self) -> str:
return self.__str__()
+
+ @override
+ def short_description(self) -> str:
+ return f"binary: {self.binary[:50].hex()}..."
diff --git a/pipelex/cogt/image/prompt_image_factory.py b/pipelex/cogt/image/prompt_image_factory.py
index 1790087a1..9d7d99039 100644
--- a/pipelex/cogt/image/prompt_image_factory.py
+++ b/pipelex/cogt/image/prompt_image_factory.py
@@ -4,12 +4,12 @@ from pipelex.cogt.image.prompt_image import (
PromptImageBase64,
PromptImageBinary,
PromptImagePath,
+ PromptImageTypedBase64,
PromptImageUrl,
)
from pipelex.tools.misc.base_64_utils import (
encode_to_base64_async,
- load_binary_as_base64_async,
- load_binary_async,
+ make_base_64_url,
strip_base_64_str_if_needed,
)
from pipelex.tools.misc.file_fetch_utils import fetch_file_from_url_httpx_async
@@ -55,29 +55,8 @@ class PromptImageFactory:
return PromptImageBinary(binary=raw_image_bytes)
@classmethod
- async def promptimage_to_b64_async(cls, prompt_image: PromptImage) -> bytes:
- match prompt_image:
- case PromptImagePath():
- return await load_binary_as_base64_async(prompt_image.file_path)
- case PromptImageBase64():
- return prompt_image.base_64
- case PromptImageUrl():
- image_bytes = await cls.make_promptimagebase64_from_url_async(prompt_image)
- return image_bytes.base_64
- case _:
- msg = f"Unknown PromptImage type: {prompt_image}"
- raise PromptImageFactoryError(msg)
-
- @classmethod
- async def promptimage_to_bytes_async(cls, prompt_image: PromptImage) -> bytes:
- match prompt_image:
- case PromptImagePath():
- return await load_binary_async(prompt_image.file_path)
- case PromptImageBase64():
- return prompt_image.get_decoded_bytes()
- case PromptImageUrl():
- image_bytes = await cls.make_promptimagebinary_from_url_async(prompt_image)
- return image_bytes.binary
- case _:
- msg = f"Unknown PromptImage type: {prompt_image}"
- raise PromptImageFactoryError(msg)
+ def make_base_64_url_from_prompt_image_typed_base64(
+ cls,
+ prompt_image: PromptImageTypedBase64,
+ ) -> str:
+ return make_base_64_url(base_64=prompt_image.base_64, file_type=prompt_image.file_type)
diff --git a/pipelex/cogt/image/prompt_image_utils.py b/pipelex/cogt/image/prompt_image_utils.py
new file mode 100644
index 000000000..6e198195d
--- /dev/null
+++ b/pipelex/cogt/image/prompt_image_utils.py
@@ -0,0 +1,82 @@
+import asyncio
+
+from pipelex.cogt.exceptions import PromptImageFactoryError
+from pipelex.cogt.image.prompt_image import (
+ PromptImage,
+ PromptImageBase64,
+ PromptImagePath,
+ PromptImageTypedBase64,
+ PromptImageTypedUrlOrBase64,
+ PromptImageUrl,
+)
+from pipelex.cogt.image.prompt_image_factory import PromptImageFactory
+from pipelex.tools.misc.base_64_utils import (
+ load_binary_as_base64_async,
+ load_binary_async,
+)
+from pipelex.tools.misc.filetype_utils import detect_file_type_from_base64
+from pipelex.tools.misc.path_utils import clarify_path_or_url
+
+
+async def promptimage_to_b64_async(prompt_image: PromptImage) -> bytes:
+ match prompt_image:
+ case PromptImagePath():
+ return await load_binary_as_base64_async(prompt_image.file_path)
+ case PromptImageBase64():
+ return prompt_image.base_64
+ case PromptImageUrl():
+ image_bytes = await PromptImageFactory.make_promptimagebase64_from_url_async(prompt_image)
+ return image_bytes.base_64
+ case _:
+ msg = f"Unknown PromptImage type: {prompt_image}"
+ raise PromptImageFactoryError(msg)
+
+
+async def promptimage_to_bytes_async(prompt_image: PromptImage) -> bytes:
+ match prompt_image:
+ case PromptImagePath():
+ return await load_binary_async(prompt_image.file_path)
+ case PromptImageBase64():
+ return prompt_image.get_decoded_bytes()
+ case PromptImageUrl():
+ image_bytes = await PromptImageFactory.make_promptimagebinary_from_url_async(prompt_image)
+ return image_bytes.binary
+ case _:
+ msg = f"Unknown PromptImage type: {prompt_image}"
+ raise PromptImageFactoryError(msg)
+
+
+async def promptimage_to_typed_bytes_or_url(
+ prompt_image: PromptImage,
+ is_http_url_enabled: bool,
+) -> PromptImageTypedUrlOrBase64:
+ typed_bytes_or_url: PromptImageTypedUrlOrBase64
+ if isinstance(prompt_image, PromptImageBase64):
+ typed_bytes_or_url = prompt_image.make_prompt_image_typed_base64()
+ elif isinstance(prompt_image, PromptImageUrl):
+ file_path, url = clarify_path_or_url(path_or_uri=prompt_image.url)
+ if url:
+ if is_http_url_enabled:
+ typed_bytes_or_url = prompt_image.url
+ else:
+ image_bytes = await PromptImageFactory.make_promptimagebase64_from_url_async(prompt_image_url=prompt_image)
+ file_type = detect_file_type_from_base64(image_bytes.base_64)
+ typed_bytes_or_url = PromptImageTypedBase64(base_64=image_bytes.base_64, file_type=file_type)
+ elif file_path:
+ prompt_image_path = PromptImagePath(file_path=file_path)
+ return await promptimage_to_typed_bytes_or_url(prompt_image=prompt_image_path, is_http_url_enabled=is_http_url_enabled)
+ else:
+ msg = "No file path or URL found"
+ raise PromptImageFactoryError(msg)
+ elif isinstance(prompt_image, PromptImagePath):
+ b64 = await load_binary_as_base64_async(prompt_image.file_path)
+ typed_bytes_or_url = PromptImageTypedBase64(base_64=b64, file_type=prompt_image.get_file_type())
+ else:
+ msg = f"Unsupported PromptImage type: '{type(prompt_image).__name__}'"
+ raise PromptImageFactoryError(msg)
+ return typed_bytes_or_url
+
+
+async def prep_prompt_images(prompt_images: list[PromptImage], is_http_url_enabled: bool) -> list[PromptImageTypedUrlOrBase64]:
+ tasks_to_prep_images = [promptimage_to_typed_bytes_or_url(prompt_image, is_http_url_enabled) for prompt_image in prompt_images]
+ return await asyncio.gather(*tasks_to_prep_images)
diff --git a/pipelex/cogt/img_gen/img_gen_worker_factory.py b/pipelex/cogt/img_gen/img_gen_worker_factory.py
index 7336e8fe7..ecb7fc25c 100644
--- a/pipelex/cogt/img_gen/img_gen_worker_factory.py
+++ b/pipelex/cogt/img_gen/img_gen_worker_factory.py
@@ -1,11 +1,12 @@
+import importlib.util
+
from pipelex.cogt.exceptions import MissingDependencyError
from pipelex.cogt.img_gen.img_gen_worker_abstract import ImgGenWorkerAbstract
from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
-from pipelex.hub import get_models_manager, get_plugin_manager, get_secret
+from pipelex.hub import get_models_manager, get_plugin_manager
from pipelex.plugins.plugin_sdk_registry import Plugin
from pipelex.reporting.reporting_protocol import ReportingProtocol
from pipelex.system.exceptions import CredentialsError
-from pipelex.tools.secrets.secrets_errors import SecretNotFoundError
class FalCredentialsError(CredentialsError):
@@ -13,8 +14,9 @@ class FalCredentialsError(CredentialsError):
class ImgGenWorkerFactory:
+ @classmethod
def make_img_gen_worker(
- self,
+ cls,
inference_model: InferenceModelSpec,
reporting_delegate: ReportingProtocol | None = None,
) -> ImgGenWorkerAbstract:
@@ -24,15 +26,7 @@ class ImgGenWorkerFactory:
img_gen_worker: ImgGenWorkerAbstract
match plugin.sdk:
case "fal":
- try:
- fal_api_key = get_secret(secret_id="FAL_API_KEY")
- except SecretNotFoundError as exc:
- msg = "FAL_API_KEY not found"
- raise FalCredentialsError(msg) from exc
-
- try:
- from fal_client import AsyncClient as FalAsyncClient # noqa: PLC0415
- except ImportError as exc:
+ if importlib.util.find_spec("fal_client") is None:
lib_name = "fal-client"
lib_extra_name = "fal"
msg = "The fal-client SDK is required in order to use FAL models (generation of images)."
@@ -40,13 +34,15 @@ class ImgGenWorkerFactory:
lib_name,
lib_extra_name,
msg,
- ) from exc
+ )
+
+ from fal_client import AsyncClient as FalAsyncClient # noqa: PLC0415
from pipelex.plugins.fal.fal_img_gen_worker import FalImgGenWorker # noqa: PLC0415
img_gen_sdk_instance = plugin_sdk_registry.get_sdk_instance(plugin=plugin) or plugin_sdk_registry.set_sdk_instance(
plugin=plugin,
- sdk_instance=FalAsyncClient(key=fal_api_key),
+ sdk_instance=FalAsyncClient(key=backend.api_key),
)
img_gen_worker = FalImgGenWorker(
@@ -54,13 +50,13 @@ class ImgGenWorkerFactory:
inference_model=inference_model,
reporting_delegate=reporting_delegate,
)
- case "openai":
- from pipelex.plugins.openai.openai_factory import OpenAIFactory # noqa: PLC0415
+ case "openai_img_gen":
+ from pipelex.plugins.openai.openai_client_factory import OpenAIClientFactory # noqa: PLC0415
from pipelex.plugins.openai.openai_img_gen_worker import OpenAIImgGenWorker # noqa: PLC0415
img_gen_sdk_instance = plugin_sdk_registry.get_sdk_instance(plugin=plugin) or plugin_sdk_registry.set_sdk_instance(
plugin=plugin,
- sdk_instance=OpenAIFactory.make_openai_client(
+ sdk_instance=OpenAIClientFactory.make_openai_client(
plugin=plugin,
backend=backend,
),
@@ -72,12 +68,12 @@ class ImgGenWorkerFactory:
reporting_delegate=reporting_delegate,
)
case "openai_alt_img_gen":
- from pipelex.plugins.openai.openai_factory import OpenAIFactory # noqa: PLC0415
+ from pipelex.plugins.openai.openai_client_factory import OpenAIClientFactory # noqa: PLC0415
from pipelex.plugins.openai.openai_img_gen_alt_worker import OpenAIImgGenAlternativeWorker # noqa: PLC0415
img_gen_sdk_instance = plugin_sdk_registry.get_sdk_instance(plugin=plugin) or plugin_sdk_registry.set_sdk_instance(
plugin=plugin,
- sdk_instance=OpenAIFactory.make_openai_client(
+ sdk_instance=OpenAIClientFactory.make_openai_client(
plugin=plugin,
backend=backend,
),
@@ -88,7 +84,7 @@ class ImgGenWorkerFactory:
inference_model=inference_model,
reporting_delegate=reporting_delegate,
)
- case "azure_rest":
+ case "azure_rest_img_gen":
from pipelex.plugins.azure_rest.azure_img_gen_worker import AzureImgGenWorker # noqa: PLC0415
img_gen_worker = AzureImgGenWorker(
diff --git a/pipelex/cogt/inference/inference_manager.py b/pipelex/cogt/inference/inference_manager.py
index 38b405b74..1bdd3e7c2 100644
--- a/pipelex/cogt/inference/inference_manager.py
+++ b/pipelex/cogt/inference/inference_manager.py
@@ -14,17 +14,12 @@ from pipelex.hub import get_models_manager, get_report_delegate
class InferenceManager(InferenceManagerProtocol):
def __init__(self):
- # TODO: we don't need instances of the factories, we can just use them via class methods
- self.img_gen_worker_factory = ImgGenWorkerFactory()
- self.extract_worker_factory = ExtractWorkerFactory()
self.llm_workers: dict[str, LLMWorkerAbstract] = {}
self.img_gen_workers: dict[str, ImgGenWorkerAbstract] = {}
self.extract_workers: dict[str, ExtractWorkerAbstract] = {}
@override
def teardown(self):
- self.img_gen_worker_factory = ImgGenWorkerFactory()
- self.extract_worker_factory = ExtractWorkerFactory()
for llm_worker in self.llm_workers.values():
llm_worker.teardown()
self.llm_workers = {}
@@ -91,7 +86,7 @@ class InferenceManager(InferenceManagerProtocol):
def _setup_one_img_gen_worker(self, img_gen_handle: str) -> ImgGenWorkerAbstract:
inference_model = get_models_manager().get_inference_model(model_handle=img_gen_handle)
log.verbose(f"Setting up Image Generation Worker for '{img_gen_handle}'")
- img_gen_worker = self.img_gen_worker_factory.make_img_gen_worker(
+ img_gen_worker = ImgGenWorkerFactory.make_img_gen_worker(
inference_model=inference_model,
reporting_delegate=get_report_delegate(),
)
@@ -114,7 +109,7 @@ class InferenceManager(InferenceManagerProtocol):
extract_handle: str,
) -> ExtractWorkerAbstract:
inference_model = get_models_manager().get_inference_model(model_handle=extract_handle)
- extract_worker = self.extract_worker_factory.make_extract_worker(
+ extract_worker = ExtractWorkerFactory.make_extract_worker(
inference_model=inference_model,
reporting_delegate=get_report_delegate(),
)
diff --git a/pipelex/cogt/llm/llm_constants.py b/pipelex/cogt/llm/llm_constants.py
new file mode 100644
index 000000000..53e9fb5b4
--- /dev/null
+++ b/pipelex/cogt/llm/llm_constants.py
@@ -0,0 +1,18 @@
+from pipelex.types import StrEnum
+
+
+class LLMOutputType(StrEnum):
+ TEXT = "Text"
+ OBJECT = "Object"
+
+ @classmethod
+ def is_text(cls, output_desc: str) -> bool:
+ try:
+ output_desc_enum = cls(output_desc)
+ except ValueError:
+ return False
+ match output_desc_enum:
+ case cls.TEXT:
+ return True
+ case cls.OBJECT:
+ return False
diff --git a/pipelex/cogt/llm/llm_job.py b/pipelex/cogt/llm/llm_job.py
index 49217293f..129a85383 100644
--- a/pipelex/cogt/llm/llm_job.py
+++ b/pipelex/cogt/llm/llm_job.py
@@ -15,6 +15,8 @@ class LLMJob(InferenceJobAbstract):
job_config: LLMJobConfig
job_report: LLMJobReport = LLMJobReport()
+ applied_job_params: LLMJobParams | None = None
+
@property
def params_desc(self) -> str:
return f"temp={self.job_params.temperature}, max_tokens={self.job_params.max_tokens}"
diff --git a/pipelex/cogt/llm/llm_job_components.py b/pipelex/cogt/llm/llm_job_components.py
index 3711b8ac1..e303774a3 100644
--- a/pipelex/cogt/llm/llm_job_components.py
+++ b/pipelex/cogt/llm/llm_job_components.py
@@ -1,5 +1,6 @@
from pydantic import BaseModel, Field
+from pipelex.cogt.image.prompt_image import PromptImageDetail
from pipelex.cogt.llm.llm_report import LLMTokensUsage
########################################################################
@@ -10,11 +11,11 @@ from pipelex.cogt.llm.llm_report import LLMTokensUsage
class LLMJobParams(BaseModel):
temperature: float = Field(..., ge=0, le=1)
max_tokens: int | None = Field(None, gt=0)
+ image_detail: PromptImageDetail | None = None
seed: int | None = Field(None, ge=0)
class LLMJobConfig(BaseModel):
- is_streaming_enabled: bool
max_retries: int = Field(..., ge=1, le=10)
diff --git a/pipelex/cogt/llm/llm_setting.py b/pipelex/cogt/llm/llm_setting.py
index 5e5933b41..ea9577fdf 100644
--- a/pipelex/cogt/llm/llm_setting.py
+++ b/pipelex/cogt/llm/llm_setting.py
@@ -2,6 +2,7 @@ from typing import Literal, Union
from pydantic import Field, field_validator
+from pipelex.cogt.image.prompt_image import PromptImageDetail
from pipelex.cogt.llm.llm_job_components import LLMJobParams
from pipelex.cogt.model_backends.prompting_target import PromptingTarget
from pipelex.system.configuration.config_model import ConfigModel
@@ -12,6 +13,7 @@ class LLMSetting(ConfigModel):
model: str
temperature: float = Field(..., ge=0, le=1)
max_tokens: int | None = None
+ image_detail: PromptImageDetail | None = Field(default=None, strict=False)
prompting_target: PromptingTarget | None = Field(default=None, strict=False)
@field_validator("max_tokens", mode="before")
@@ -26,6 +28,7 @@ class LLMSetting(ConfigModel):
return LLMJobParams(
temperature=self.temperature,
max_tokens=self.max_tokens,
+ image_detail=self.image_detail,
seed=None,
)
diff --git a/pipelex/cogt/llm/llm_worker_abstract.py b/pipelex/cogt/llm/llm_worker_abstract.py
index 4836deaa7..abf64de94 100644
--- a/pipelex/cogt/llm/llm_worker_abstract.py
+++ b/pipelex/cogt/llm/llm_worker_abstract.py
@@ -3,13 +3,31 @@ from __future__ import annotations
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any
+from opentelemetry import trace
+from opentelemetry.trace import NonRecordingSpan, Span, SpanContext, SpanKind, Status, StatusCode, TraceFlags
from typing_extensions import override
from pipelex import log
from pipelex.cogt.inference.inference_worker_abstract import InferenceWorkerAbstract
+from pipelex.cogt.llm.llm_constants import LLMOutputType
+from pipelex.cogt.usage.token_category import TokenCategory
+from pipelex.pipeline.exceptions import JobMetadataError
from pipelex.pipeline.job_metadata import UnitJobId
+from pipelex.system.telemetry.otel_constants import (
+ GenAISpanAttr,
+ LangfuseSpanAttr,
+ PipelexSpanAttr,
+ SpanCategory,
+ make_otel_gen_ai_output_type,
+)
+from pipelex.system.telemetry.otel_factory import OtelFactory
+from pipelex.system.telemetry.telemetry_manager_abstract import TelemetryManagerAbstract
+from pipelex.tools.misc.package_utils import get_package_version
if TYPE_CHECKING:
+ from opentelemetry.util.types import AttributeValue
+ from pydantic import BaseModel
+
from pipelex.cogt.llm.llm_job import LLMJob
from pipelex.reporting.reporting_protocol import ReportingProtocol
from pipelex.tools.typing.pydantic_utils import BaseModelTypeVar
@@ -47,6 +65,250 @@ class LLMWorkerAbstract(InferenceWorkerAbstract, ABC):
def is_vision_supported(self) -> bool:
return False
+ #########################################################
+ # OTel helper methods - override in subclasses with model info
+ #########################################################
+
+ def _get_provider_name(self) -> str:
+ """Get the GenAI provider name (e.g., 'openai', 'anthropic'). Override in subclass."""
+ return "unknown"
+
+ def _get_request_model_name(self) -> str:
+ """Get the request model name. Override in subclass."""
+ return "unknown"
+
+ def _get_response_model_name(self) -> str:
+ """Get the response model name. Override in subclass."""
+ return "unknown"
+
+ def _start_otel_span_llm(self, llm_job: LLMJob, output_type: LLMOutputType, output_class_name: str | None = None) -> Span | None:
+ """Start an OTel span for the LLM job and return it.
+
+ Always includes full (non-redacted) values in Pipelex attributes for PostHog exporters.
+ Redaction is handled by individual exporters based on their TelemetryRedactionConfig.
+ Safe to call if otel_context is None.
+ """
+ # Get context from job metadata
+ job_metadata = llm_job.job_metadata
+ otel_context = job_metadata.otel_context
+ job_params = llm_job.applied_job_params or llm_job.job_params
+
+ # Skip if telemetry is disabled (no otel_context)
+ if otel_context is None:
+ log.verbose("[OTel] No otel_context - skipping LLM span")
+ return None
+
+ tracer = TelemetryManagerAbstract.get_instance_tracer()
+ if tracer is None:
+ log.verbose("[OTel] No tracer available for LLM span")
+ return None
+
+ unit_job_id = job_metadata.unit_job_id
+ if not unit_job_id:
+ msg = "unit_job_id is required for LLM span"
+ raise JobMetadataError(msg)
+ pipe_code = job_metadata.pipe_code
+ if not pipe_code:
+ msg = "pipe_code is required for LLM span"
+ raise JobMetadataError(msg)
+ pipeline_run_id = job_metadata.pipeline_run_id
+
+ # Build output description for span name (full values - exporter handles redaction)
+ output_desc: str
+ match output_type:
+ case LLMOutputType.TEXT:
+ output_desc = output_type
+ case LLMOutputType.OBJECT:
+ # Always use full class name in span name, exporter will redact if needed
+ output_desc = output_class_name or output_type
+
+ model_name = self._get_request_model_name()
+ # Always use full pipe code and class name - exporter handles redaction
+ span_name = f"{pipe_code}: {unit_job_id} ({model_name}) -> {output_desc}"
+
+ # Build all span attributes with FULL (non-redacted) values
+ # PostHog exporters will apply redaction based on their TelemetryRedactionConfig
+ span_attributes: dict[str, AttributeValue] = {
+ # GenAI standard attributes
+ GenAISpanAttr.OPERATION_NAME: unit_job_id,
+ GenAISpanAttr.OUTPUT_TYPE: make_otel_gen_ai_output_type(output_type=output_type).value,
+ GenAISpanAttr.PROVIDER_NAME: self._get_provider_name(),
+ GenAISpanAttr.REQUEST_MODEL: model_name,
+ GenAISpanAttr.RESPONSE_MODEL: self._get_response_model_name(),
+ GenAISpanAttr.REQUEST_TEMPERATURE: job_params.temperature,
+ # Pipelex specific context attributes (always full values, exporters redact as needed)
+ PipelexSpanAttr.TRACE_NAME: otel_context.trace_name,
+ PipelexSpanAttr.TRACE_NAME_REDACTED: otel_context.trace_name_redacted,
+ PipelexSpanAttr.SPAN_CATEGORY: SpanCategory.INFERENCE,
+ PipelexSpanAttr.PIPELINE_RUN_ID: pipeline_run_id,
+ PipelexSpanAttr.PIPE_CODE: pipe_code, # Full pipe code, exporter handles redaction
+ }
+
+ # Store output class name as separate attribute so exporter can rebuild span name with redaction
+ if output_class_name:
+ span_attributes[PipelexSpanAttr.OUTPUT_CLASS_NAME] = output_class_name
+
+ if TelemetryManagerAbstract.get_langfuse_enabled():
+ span_attributes[LangfuseSpanAttr.TRACE_NAME] = otel_context.trace_name
+ span_attributes[LangfuseSpanAttr.RELEASE] = get_package_version()
+ if job_params.max_tokens:
+ span_attributes[GenAISpanAttr.REQUEST_MAX_TOKENS] = job_params.max_tokens
+ if job_params.seed:
+ span_attributes[GenAISpanAttr.REQUEST_SEED] = job_params.seed
+
+ # Always capture full prompt content - exporters handle redaction as needed
+ messages: list[dict[str, Any]] = []
+ if llm_job.llm_prompt.system_text:
+ system_text_dict = {
+ "role": "system",
+ "content": llm_job.llm_prompt.system_text,
+ }
+ messages.append(system_text_dict)
+ if llm_job.llm_prompt.user_text or llm_job.llm_prompt.user_images:
+ content_dict: list[dict[str, Any]] = []
+ if llm_job.llm_prompt.user_text:
+ user_text_dict = {
+ "type": "text",
+ "text": llm_job.llm_prompt.user_text,
+ }
+ content_dict.append(user_text_dict)
+ for prompt_image in llm_job.llm_prompt.user_images:
+ image_dict = {
+ "type": "image",
+ "image": prompt_image.short_description(),
+ }
+ content_dict.append(image_dict)
+ user_dict = {
+ "role": "user",
+ "content": content_dict,
+ }
+ messages.append(user_dict)
+
+ messages_json = OtelFactory.stringify_json(json_conent=messages)
+ span_attributes[GenAISpanAttr.PROMPT_CONTENT] = messages_json
+ if TelemetryManagerAbstract.get_langfuse_enabled():
+ span_attributes[LangfuseSpanAttr.OBSERVATION_INPUT] = messages_json
+
+ # Use trace_id and span_id from otel_context (precomputed)
+ # The span_id in otel_context is the parent pipe's span - use it as parent
+ parent_span_id = otel_context.span_id
+ log.verbose(f"[OTel] LLM span:\n pipe_code='{pipe_code}'\n pipeline_run_id='{pipeline_run_id}'\n parent_span_id={parent_span_id:016x}")
+
+ parent_span_context = SpanContext(
+ trace_id=otel_context.trace_id,
+ span_id=parent_span_id,
+ is_remote=True,
+ trace_flags=TraceFlags(TraceFlags.SAMPLED),
+ )
+ parent_ctx = trace.set_span_in_context(NonRecordingSpan(parent_span_context))
+
+ # Start span with our context and all attributes
+ span = tracer.start_span(
+ name=span_name,
+ kind=SpanKind.CLIENT,
+ context=parent_ctx,
+ attributes=span_attributes,
+ )
+
+ # Debug logging
+ span_ctx = span.get_span_context()
+ log.verbose(
+ f"[OTel] LLM SPAN STARTED:\n"
+ f" pipe_code='{pipe_code}'\n"
+ f" pipeline_run_id='{pipeline_run_id}'\n"
+ f" trace_id={span_ctx.trace_id:032x}\n"
+ f" span_id={span_ctx.span_id:016x}\n"
+ f" parent_span_id={parent_span_id:016x}"
+ )
+
+ return span
+
+ def _end_otel_span_with_completion_text(self, span: Span | None, llm_job: LLMJob, completion_text: str) -> None:
+ """End the OTel span, recording usage and status. Safe to call if span is None."""
+ if span is None:
+ return
+
+ job_metadata = llm_job.job_metadata
+ span_ctx = span.get_span_context()
+ log.verbose(
+ f"[OTel] LLM SPAN ENDING:\n"
+ f" pipe_code='{job_metadata.pipe_code}'\n"
+ f" pipeline_run_id='{job_metadata.pipeline_run_id}'\n"
+ f" trace_id={span_ctx.trace_id:032x}\n"
+ f" span_id={span_ctx.span_id:016x}"
+ )
+
+ # Record token usage if available
+ if llm_job.job_report.llm_tokens_usage:
+ tokens = llm_job.job_report.llm_tokens_usage.nb_tokens_by_category
+ input_tokens = tokens.get(TokenCategory.INPUT, 0)
+ output_tokens = tokens.get(TokenCategory.OUTPUT, 0)
+ span.set_attribute(GenAISpanAttr.USAGE_INPUT_TOKENS, input_tokens)
+ span.set_attribute(GenAISpanAttr.USAGE_OUTPUT_TOKENS, output_tokens)
+
+ # Always capture full completion content - exporters handle redaction as needed
+ span.set_attribute(GenAISpanAttr.COMPLETION_CONTENT, completion_text)
+ if TelemetryManagerAbstract.get_langfuse_enabled():
+ span.set_attribute(LangfuseSpanAttr.OBSERVATION_OUTPUT, completion_text)
+
+ span.set_status(Status(StatusCode.OK))
+ span.end()
+
+ def _end_otel_span_with_completion_object(self, span: Span | None, llm_job: LLMJob, completion_object: BaseModel) -> None:
+ """End the OTel span, recording usage and status. Safe to call if span is None."""
+ if span is None:
+ return
+
+ job_metadata = llm_job.job_metadata
+ span_ctx = span.get_span_context()
+ log.verbose(
+ f"[OTel] LLM SPAN ENDING:\n"
+ f" pipe_code='{job_metadata.pipe_code}'\n"
+ f" pipeline_run_id='{job_metadata.pipeline_run_id}'\n"
+ f" trace_id={span_ctx.trace_id:032x}\n"
+ f" span_id={span_ctx.span_id:016x}"
+ )
+
+ # Record token usage if available
+ if llm_job.job_report.llm_tokens_usage:
+ tokens = llm_job.job_report.llm_tokens_usage.nb_tokens_by_category
+ input_tokens = tokens.get(TokenCategory.INPUT, 0)
+ output_tokens = tokens.get(TokenCategory.OUTPUT, 0)
+ span.set_attribute(GenAISpanAttr.USAGE_INPUT_TOKENS, input_tokens)
+ span.set_attribute(GenAISpanAttr.USAGE_OUTPUT_TOKENS, output_tokens)
+
+ # Always capture full completion content - exporters handle redaction as needed
+ completion_object_json = OtelFactory.stringify_json(json_conent=completion_object.model_dump(serialize_as_any=True))
+ span.set_attribute(GenAISpanAttr.COMPLETION_CONTENT, completion_object_json)
+ if TelemetryManagerAbstract.get_langfuse_enabled():
+ span.set_attribute(LangfuseSpanAttr.OBSERVATION_OUTPUT, completion_object_json)
+
+ span.set_status(Status(StatusCode.OK))
+ span.end()
+
+ def _end_otel_span_with_error(self, span: Span | None, llm_job: LLMJob, error: Exception) -> None:
+ """End the OTel span, recording the error. Safe to call if span is None."""
+ if span is None:
+ return
+
+ job_metadata = llm_job.job_metadata
+ span_ctx = span.get_span_context()
+ log.verbose(
+ f"[OTel] LLM SPAN ENDING WITH ERROR:\n"
+ f" pipe_code='{job_metadata.pipe_code}'\n"
+ f" pipeline_run_id='{job_metadata.pipeline_run_id}'\n"
+ f" trace_id={span_ctx.trace_id:032x}\n"
+ f" span_id={span_ctx.span_id:016x}"
+ )
+
+ span.record_exception(error)
+ span.set_status(Status(StatusCode.ERROR, str(error)))
+ span.end()
+
+ #########################################################
+ # Job lifecycle methods
+ #########################################################
+
async def _before_job(
self,
llm_job: LLMJob,
@@ -57,16 +319,34 @@ class LLMWorkerAbstract(InferenceWorkerAbstract, ABC):
# Verify feasibility
self._check_can_perform_job(llm_job=llm_job)
- async def _after_job(
+ async def _after_text_job(
self,
+ span: Span | None,
llm_job: LLMJob,
- result: Any, # noqa: ARG002
+ result_text: str,
):
# Report job
llm_job.llm_job_after_complete()
if self.reporting_delegate:
self.reporting_delegate.report_inference_job(inference_job=llm_job)
+ # End OTel span with success status and usage data
+ self._end_otel_span_with_completion_text(span=span, llm_job=llm_job, completion_text=result_text)
+
+ async def _after_object_job(
+ self,
+ span: Span | None,
+ llm_job: LLMJob,
+ result_object: BaseModel,
+ ):
+ # Report job
+ llm_job.llm_job_after_complete()
+ if self.reporting_delegate:
+ self.reporting_delegate.report_inference_job(inference_job=llm_job)
+
+ # End OTel span with success status and usage data
+ self._end_otel_span_with_completion_object(span=span, llm_job=llm_job, completion_object=result_object)
+
def _check_can_perform_job(self, llm_job: LLMJob):
# This can be overridden by subclasses for specific checks
pass
@@ -83,11 +363,18 @@ class LLMWorkerAbstract(InferenceWorkerAbstract, ABC):
await self._before_job(llm_job=llm_job)
- result = await self._gen_text(llm_job=llm_job)
+ # Start OTel span after _before_job (which may set model info)
+ span = self._start_otel_span_llm(llm_job=llm_job, output_type=LLMOutputType.TEXT)
+
+ try:
+ text_result = await self._gen_text(llm_job=llm_job)
+ except Exception as exc:
+ self._end_otel_span_with_error(span=span, llm_job=llm_job, error=exc)
+ raise
- await self._after_job(llm_job=llm_job, result=result)
+ await self._after_text_job(span=span, llm_job=llm_job, result_text=text_result)
- return result
+ return text_result
@abstractmethod
async def _gen_text(
@@ -109,16 +396,22 @@ class LLMWorkerAbstract(InferenceWorkerAbstract, ABC):
await self._before_job(llm_job=llm_job)
- # Execute job
- result = await self._gen_object(llm_job=llm_job, schema=schema)
+ # Start OTel span after _before_job (which may set model info)
+ span = self._start_otel_span_llm(llm_job=llm_job, output_type=LLMOutputType.OBJECT, output_class_name=schema.__name__)
+
+ try:
+ object_result = await self._gen_object(llm_job=llm_job, schema=schema)
- # Cleanup result
- if hasattr(result, "_raw_response"):
- delattr(result, "_raw_response")
+ # Cleanup result
+ if hasattr(object_result, "_raw_response"):
+ delattr(object_result, "_raw_response")
+ except Exception as exc:
+ self._end_otel_span_with_error(span=span, llm_job=llm_job, error=exc)
+ raise
- await self._after_job(llm_job=llm_job, result=result)
+ await self._after_object_job(span=span, llm_job=llm_job, result_object=object_result)
- return result
+ return object_result
@abstractmethod
async def _gen_object(
diff --git a/pipelex/cogt/llm/llm_worker_factory.py b/pipelex/cogt/llm/llm_worker_factory.py
index 2e3f73824..17835ea34 100644
--- a/pipelex/cogt/llm/llm_worker_factory.py
+++ b/pipelex/cogt/llm/llm_worker_factory.py
@@ -19,19 +19,126 @@ class LLMWorkerFactory:
plugin_sdk_registry = get_plugin_manager().plugin_sdk_registry
llm_worker: LLMWorkerInternalAbstract
match plugin.sdk:
+ case "gateway_completions":
+ from pipelex.plugins.gateway.gateway_completions_factory import GatewayCompletionsFactory # noqa: PLC0415
+ from pipelex.plugins.openai.openai_completions_llm_worker import OpenAICompletionsLLMWorker # noqa: PLC0415
+
+ sdk_instance = plugin_sdk_registry.get_sdk_instance(plugin=plugin) or plugin_sdk_registry.set_sdk_instance(
+ plugin=plugin,
+ sdk_instance=GatewayCompletionsFactory.make_portkey_openai_client_for_completions(
+ plugin=plugin,
+ backend=backend,
+ ),
+ )
+
+ gateway_completions_factory = GatewayCompletionsFactory(is_http_url_enabled=False)
+
+ llm_worker = OpenAICompletionsLLMWorker(
+ openai_completions_factory=gateway_completions_factory,
+ sdk_instance=sdk_instance,
+ inference_model=inference_model,
+ reporting_delegate=reporting_delegate,
+ )
+ case "gateway_responses":
+ from pipelex.plugins.gateway.gateway_responses_factory import GatewayResponsesFactory # noqa: PLC0415
+ from pipelex.plugins.openai.openai_responses_factory import OpenAIResponsesFactory # noqa: PLC0415
+ from pipelex.plugins.openai.openai_responses_llm_worker import OpenAIResponsesLLMWorker # noqa: PLC0415
+
+ sdk_instance = plugin_sdk_registry.get_sdk_instance(plugin=plugin) or plugin_sdk_registry.set_sdk_instance(
+ plugin=plugin,
+ sdk_instance=GatewayResponsesFactory.make_portkey_openai_client_for_responses(
+ plugin=plugin,
+ backend=backend,
+ ),
+ )
+
+ gateway_responses_factory = GatewayResponsesFactory(is_http_url_enabled=False)
+
+ llm_worker = OpenAIResponsesLLMWorker(
+ openai_responses_factory=gateway_responses_factory,
+ sdk_instance=sdk_instance,
+ inference_model=inference_model,
+ reporting_delegate=reporting_delegate,
+ )
+ case "portkey_completions":
+ from pipelex.plugins.openai.openai_completions_llm_worker import OpenAICompletionsLLMWorker # noqa: PLC0415
+ from pipelex.plugins.portkey.portkey_completions_factory import PortkeyCompletionsFactory # noqa: PLC0415
+
+ sdk_instance = plugin_sdk_registry.get_sdk_instance(plugin=plugin) or plugin_sdk_registry.set_sdk_instance(
+ plugin=plugin,
+ sdk_instance=PortkeyCompletionsFactory.make_portkey_openai_client_for_completions(
+ plugin=plugin,
+ backend=backend,
+ ),
+ )
+
+ portkey_completions_factory = PortkeyCompletionsFactory(is_http_url_enabled=False)
+
+ llm_worker = OpenAICompletionsLLMWorker(
+ openai_completions_factory=portkey_completions_factory,
+ sdk_instance=sdk_instance,
+ inference_model=inference_model,
+ reporting_delegate=reporting_delegate,
+ )
+ case "portkey_responses":
+ from pipelex.plugins.openai.openai_responses_factory import OpenAIResponsesFactory # noqa: PLC0415
+ from pipelex.plugins.openai.openai_responses_llm_worker import OpenAIResponsesLLMWorker # noqa: PLC0415
+ from pipelex.plugins.portkey.portkey_responses_factory import PortkeyResponsesFactory # noqa: PLC0415
+
+ sdk_instance = plugin_sdk_registry.get_sdk_instance(plugin=plugin) or plugin_sdk_registry.set_sdk_instance(
+ plugin=plugin,
+ sdk_instance=PortkeyResponsesFactory.make_portkey_openai_client_for_responses(
+ plugin=plugin,
+ backend=backend,
+ ),
+ )
+
+ portkey_responses_factory = PortkeyResponsesFactory(is_http_url_enabled=False)
+
+ llm_worker = OpenAIResponsesLLMWorker(
+ openai_responses_factory=portkey_responses_factory,
+ sdk_instance=sdk_instance,
+ inference_model=inference_model,
+ reporting_delegate=reporting_delegate,
+ )
+ case "openai_responses" | "azure_openai_responses":
+ from pipelex.plugins.openai.openai_client_factory import OpenAIClientFactory # noqa: PLC0415
+ from pipelex.plugins.openai.openai_responses_factory import OpenAIResponsesFactory # noqa: PLC0415
+ from pipelex.plugins.openai.openai_responses_llm_worker import OpenAIResponsesLLMWorker # noqa: PLC0415
+
+ sdk_instance = plugin_sdk_registry.get_sdk_instance(plugin=plugin) or plugin_sdk_registry.set_sdk_instance(
+ plugin=plugin,
+ sdk_instance=OpenAIClientFactory.make_openai_client(
+ plugin=plugin,
+ backend=backend,
+ ),
+ )
+
+ openai_responses_factory = OpenAIResponsesFactory(is_http_url_enabled=True)
+
+ llm_worker = OpenAIResponsesLLMWorker(
+ openai_responses_factory=openai_responses_factory,
+ sdk_instance=sdk_instance,
+ inference_model=inference_model,
+ reporting_delegate=reporting_delegate,
+ )
case "openai" | "azure_openai":
- from pipelex.plugins.openai.openai_factory import OpenAIFactory # noqa: PLC0415
- from pipelex.plugins.openai.openai_llm_worker import OpenAILLMWorker # noqa: PLC0415
+ from pipelex.plugins.openai.openai_client_factory import OpenAIClientFactory # noqa: PLC0415
+ from pipelex.plugins.openai.openai_completions_factory import OpenAICompletionsFactory # noqa: PLC0415
+ from pipelex.plugins.openai.openai_completions_llm_worker import OpenAICompletionsLLMWorker # noqa: PLC0415
sdk_instance = plugin_sdk_registry.get_sdk_instance(plugin=plugin) or plugin_sdk_registry.set_sdk_instance(
plugin=plugin,
- sdk_instance=OpenAIFactory.make_openai_client(
+ sdk_instance=OpenAIClientFactory.make_openai_client(
plugin=plugin,
backend=backend,
),
)
- llm_worker = OpenAILLMWorker(
+ openai_completions_factory = OpenAICompletionsFactory(is_http_url_enabled=True)
+
+ llm_worker = OpenAICompletionsLLMWorker(
+ openai_completions_factory=openai_completions_factory,
sdk_instance=sdk_instance,
inference_model=inference_model,
reporting_delegate=reporting_delegate,
@@ -89,6 +196,7 @@ class LLMWorkerFactory:
)
llm_worker = MistralLLMWorker(
+ mistral_factory=MistralFactory(),
sdk_instance=sdk_instance,
inference_model=inference_model,
reporting_delegate=reporting_delegate,
diff --git a/pipelex/cogt/llm/llm_worker_internal_abstract.py b/pipelex/cogt/llm/llm_worker_internal_abstract.py
index 0356b3a5a..3be145931 100644
--- a/pipelex/cogt/llm/llm_worker_internal_abstract.py
+++ b/pipelex/cogt/llm/llm_worker_internal_abstract.py
@@ -1,10 +1,14 @@
+from opentelemetry.trace import Span
+from pydantic import BaseModel
from typing_extensions import override
from pipelex import log
from pipelex.cogt.exceptions import LLMCapabilityError
from pipelex.cogt.llm.llm_job import LLMJob
+from pipelex.cogt.llm.llm_job_components import LLMJobParams
from pipelex.cogt.llm.llm_utils import dump_prompt, dump_response_from_text_gen
from pipelex.cogt.llm.llm_worker_abstract import LLMWorkerAbstract
+from pipelex.cogt.model_backends.constraints import ListedConstraint, ValuedConstraint
from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
from pipelex.config import get_config
from pipelex.reporting.reporting_protocol import ReportingProtocol
@@ -45,6 +49,29 @@ class LLMWorkerInternalAbstract(LLMWorkerAbstract):
def is_vision_supported(self) -> bool:
return self.inference_model.is_vision_supported
+ #########################################################
+ # OTel helper method overrides
+ #########################################################
+
+ @override
+ def _get_provider_name(self) -> str:
+ """Get the GenAI provider name from the inference model SDK."""
+ return self.inference_model.backend_name
+
+ @override
+ def _get_request_model_name(self) -> str:
+ """Get the model name from the inference model."""
+ return self.inference_model.name
+
+ @override
+ def _get_response_model_name(self) -> str:
+ """Get the response model name from the inference model."""
+ return self.inference_model.model_id
+
+ #########################################################
+ # Job lifecycle overrides
+ #########################################################
+
@override
async def _before_job(
self,
@@ -53,18 +80,73 @@ class LLMWorkerInternalAbstract(LLMWorkerAbstract):
log.dev(f"✨ {self.desc} ✨")
await super()._before_job(llm_job=llm_job)
llm_job.llm_job_before_start(inference_model=self.inference_model)
+ llm_job.applied_job_params = self._apply_constraints(llm_job=llm_job)
if get_config().cogt.llm_config.is_dump_text_prompts_enabled:
dump_prompt(llm_prompt=llm_job.llm_prompt)
+ def _apply_constraints(self, llm_job: LLMJob) -> LLMJobParams | None:
+ """Apply constraints from the inference model to job params.
+
+ Args:
+ llm_job: The LLM job containing the original job params
+
+ Returns:
+ A copy of job_params with constraints applied, or None if no changes were needed
+
+ """
+ original_params = llm_job.job_params
+ new_temperature = original_params.temperature
+ max_tokens = original_params.max_tokens or self.inference_model.max_tokens
+ new_max_tokens = max_tokens
+ has_changes = False
+
+ # Temperature constraints
+ if ListedConstraint.TEMPERATURE_MUST_BE_MULTIPLIED_BY_2 in self.inference_model.listed_constraints:
+ new_temperature *= 2
+ has_changes = True
+ fixed_temperature = self.inference_model.valued_constraints.get(ValuedConstraint.FIXED_TEMPERATURE)
+ if fixed_temperature is not None and new_temperature != fixed_temperature:
+ log.warning(
+ f"Model {self.inference_model.desc} used with temperature {new_temperature}, "
+ f"but it must be {fixed_temperature} for this model so we forced it to {fixed_temperature}"
+ )
+ new_temperature = fixed_temperature
+ has_changes = True
+
+ # Max tokens limit (valued constraint)
+ max_limit = self.inference_model.valued_constraints.get(ValuedConstraint.MAX_OUTPUT_TOKENS_LIMIT)
+ if max_limit is not None and max_tokens is not None and max_tokens > max_limit:
+ # TODO: support streaming to avoid timeout errors with high max tokens
+ log.warning(f"Max tokens {new_max_tokens} is greater than the limit {max_limit}, reducing to {max_limit}")
+ new_max_tokens = max_limit
+ has_changes = True
+
+ if not has_changes:
+ return None
+
+ return original_params.model_copy(update={"temperature": new_temperature, "max_tokens": new_max_tokens})
+
+ @override
+ async def _after_text_job(
+ self,
+ span: Span | None,
+ llm_job: LLMJob,
+ result_text: str,
+ ):
+ if get_config().cogt.llm_config.is_dump_response_text_enabled:
+ dump_response_from_text_gen(response=result_text)
+ await super()._after_text_job(span=span, llm_job=llm_job, result_text=result_text)
+
@override
- async def _after_job(
+ async def _after_object_job(
self,
+ span: Span | None,
llm_job: LLMJob,
- result: str,
+ result_object: BaseModel,
):
if get_config().cogt.llm_config.is_dump_response_text_enabled:
- dump_response_from_text_gen(response=result)
- await super()._after_job(llm_job=llm_job, result=result)
+ dump_response_from_text_gen(response=result_object)
+ await super()._after_object_job(span=span, llm_job=llm_job, result_object=result_object)
@override
def _check_can_perform_job(self, llm_job: LLMJob):
diff --git a/pipelex/cogt/model_backends/backend.py b/pipelex/cogt/model_backends/backend.py
index 8aca3a190..c56e1d47b 100644
--- a/pipelex/cogt/model_backends/backend.py
+++ b/pipelex/cogt/model_backends/backend.py
@@ -2,8 +2,38 @@ from typing import Any
from pydantic import Field
+from pipelex.cogt.model_backends.constraints import ListedConstraint, ValuedConstraint
from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
from pipelex.system.configuration.config_model import ConfigModel
+from pipelex.tools.typing.pydantic_utils import empty_dict_factory_of, empty_list_factory_of
+from pipelex.types import StrEnum
+
+
+class PipelexBackend(StrEnum):
+ """Special Pipelex-managed inference backends."""
+
+ GATEWAY = "pipelex_gateway"
+ LEGACY_INFERENCE = "pipelex_inference" # Legacy, deprecated
+
+ @property
+ def display_name(self) -> str:
+ match self:
+ case PipelexBackend.GATEWAY:
+ return "Pipelex Gateway"
+ case PipelexBackend.LEGACY_INFERENCE:
+ return "Pipelex Inference (deprecated)"
+
+ @classmethod
+ def is_gateway_backend(cls, backend_name: str) -> bool:
+ try:
+ the_backend = cls(backend_name)
+ except ValueError:
+ return False
+ match the_backend:
+ case PipelexBackend.GATEWAY:
+ return True
+ case PipelexBackend.LEGACY_INFERENCE:
+ return False
class InferenceBackend(ConfigModel):
@@ -12,6 +42,8 @@ class InferenceBackend(ConfigModel):
enabled: bool = True
endpoint: str | None = None
api_key: str | None = None
+ listed_constraints: list[ListedConstraint] = Field(default_factory=empty_list_factory_of(ListedConstraint))
+ valued_constraints: dict[ValuedConstraint, Any] = Field(default_factory=empty_dict_factory_of(ValuedConstraint))
extra_config: dict[str, Any] = Field(default_factory=dict)
model_specs: dict[str, InferenceModelSpec] = Field(default_factory=dict)
diff --git a/pipelex/cogt/model_backends/backend_credentials.py b/pipelex/cogt/model_backends/backend_credentials.py
new file mode 100644
index 000000000..b2ecad349
--- /dev/null
+++ b/pipelex/cogt/model_backends/backend_credentials.py
@@ -0,0 +1,156 @@
+from pipelex.cogt.model_backends.backend import PipelexBackend
+from pipelex.system.configuration.config_model import ConfigModel
+from pipelex.tools.secrets.env_secrets_provider import EnvSecretsProvider
+from pipelex.tools.secrets.secrets_provider_abstract import SecretsProviderAbstract
+
+
+class BackendCredentialsReport(ConfigModel):
+ """Report of credential status for a backend."""
+
+ backend_name: str
+ required_vars: list[str]
+ missing_vars: list[str]
+ placeholder_vars: list[str]
+ all_credentials_valid: bool
+
+
+class CredentialsValidationReport(ConfigModel):
+ """Complete report of credentials validation across all backends."""
+
+ backend_reports: dict[str, BackendCredentialsReport]
+ all_backends_valid: bool
+
+
+class BackendCredentialsErrorMsgFactory:
+ @classmethod
+ def make_one_variable_missing_error_msg(
+ cls,
+ secrets_provider: SecretsProviderAbstract,
+ backend_name: str,
+ var_name: str,
+ ) -> str:
+ """Build an error message for a single missing credential variable.
+
+ Args:
+ secrets_provider: The secrets provider being used
+ backend_name: Name of the backend with the missing credential
+ var_name: Name of the missing variable
+ """
+ error_msg: str
+ if isinstance(secrets_provider, EnvSecretsProvider):
+ error_msg = (
+ f"Could not get credentials for inference backend '{backend_name}':\n\n"
+ f"Credential issue:\n • '{backend_name}': missing '{var_name}'\n\n"
+ "You have two options:\n\n"
+ "1. Add the missing environment variable\n"
+ f" Add the variable to your environment or .env file:\n"
+ f" - '{var_name}'=<your_api_key>\n"
+ "\n2. Disable this backend\n"
+ rf" Add 'enabled = false' under '\[{backend_name}]' in '.pipelex/inference/backends.toml'" + "\n"
+ )
+ else:
+ error_msg = (
+ f"Could not get credentials for inference backend '{backend_name}':\n\n"
+ f"Credential issue:\n • '{backend_name}': missing '{var_name}'\n\n"
+ "You have two options:\n\n"
+ "1. Provide the missing secret\n"
+ f" Make sure '{var_name}' is available from your secrets provider.\n"
+ "\n2. Disable this backend\n"
+ rf" Add 'enabled = false' under '\[{backend_name}]' in '.pipelex/inference/backends.toml'" + "\n"
+ )
+
+ # Add pitch for Pipelex Gateway and BYOK (Bring Your Own Keys)
+ error_msg += (
+ f"\n💡 Tip: Get a free {PipelexBackend.GATEWAY.display_name} API key!\n"
+ f" With {PipelexBackend.GATEWAY.display_name}, you get unified access to multiple AI providers\n"
+ " (OpenAI, Anthropic, Google, Mistral, etc.) with a single API key.\n"
+ " Check the project's 'README.md' for details on obtaining your key.\n"
+ "\n🔑 Or bring your own keys:\n"
+ " Set your own provider keys (OPENAI_API_KEY, ANTHROPIC_API_KEY, GOOGLE_API_KEY,\n"
+ " MISTRAL_API_KEY, AZURE_API_KEY, etc.) and enable the corresponding backends\n"
+ " in '.pipelex/inference/backends.toml'.\n"
+ )
+
+ return error_msg
+
+ @classmethod
+ def make_comprehensive_error_msg(
+ cls,
+ backend_credential_reports: dict[str, BackendCredentialsReport],
+ secrets_provider: SecretsProviderAbstract | None = None,
+ ) -> str:
+ """Build a comprehensive error message for missing backend credentials.
+
+ Args:
+ secrets_provider: The secrets provider being used
+ backend_credential_reports: Dict of backend_name -> credential report for backends with issues
+ """
+ # Build the details section for each backend with issues
+ backend_details_lines: list[str] = []
+ all_missing_vars: list[str] = []
+ all_placeholder_vars: list[str] = []
+
+ for backend_name, report in backend_credential_reports.items():
+ issues: list[str] = []
+ if report.missing_vars:
+ all_missing_vars.extend(report.missing_vars)
+ quoted_missing = [f"'{var}'" for var in report.missing_vars]
+ issues.append(f"missing: {', '.join(quoted_missing)}")
+ if report.placeholder_vars:
+ all_placeholder_vars.extend(report.placeholder_vars)
+ quoted_placeholders = [f"'{var}'" for var in report.placeholder_vars]
+ issues.append(f"unresolved placeholders: {', '.join(quoted_placeholders)}")
+ if issues:
+ backend_details_lines.append(f" • '{backend_name}': {'; '.join(issues)}")
+
+ backend_details = "\n".join(backend_details_lines)
+ backend_names = list(backend_credential_reports.keys())
+ backends_list = ", ".join(f"'{name}'" for name in backend_names)
+
+ error_msg: str
+ if isinstance(secrets_provider, EnvSecretsProvider):
+ error_msg = (
+ f"Could not get credentials for inference backend(s): {backends_list}\n\n"
+ f"Credential issues:\n{backend_details}\n\n"
+ "You have two options:\n\n"
+ "1. Add the missing environment variables\n"
+ " Add the missing variables to your environment or .env file:\n"
+ )
+ if all_missing_vars:
+ for var_name in sorted(set(all_missing_vars)):
+ error_msg += f" - '{var_name}'=<your_api_key>\n"
+ if all_placeholder_vars:
+ error_msg += " (Also replace placeholder values like '${VAR}' with actual keys)\n"
+
+ error_msg += "\n2. Disable unused backends\n Disable backends you don't need in '.pipelex/inference/backends.toml':\n"
+ for backend_name in backend_names:
+ error_msg += rf" - Add 'enabled = false' under '\[{backend_name}]'" + "\n"
+ else:
+ error_msg = (
+ f"Could not get credentials for inference backend(s): {backends_list}\n\n"
+ f"Credential issues:\n{backend_details}\n\n"
+ "You have two options:\n\n"
+ "1. Provide the missing secrets\n"
+ " Make sure the following secrets are available from your secrets provider:\n"
+ )
+ all_vars = sorted(set(all_missing_vars + all_placeholder_vars))
+ for var_name in all_vars:
+ error_msg += f" - '{var_name}'\n"
+
+ error_msg += "\n2. Disable unused backends\n Disable backends you don't need in '.pipelex/inference/backends.toml':\n"
+ for backend_name in backend_names:
+ error_msg += rf" - Add 'enabled = false' under '\[{backend_name}]'" + "\n"
+
+ # Add pitch for Pipelex Gateway and BYOK (Bring Your Own Keys)
+ error_msg += (
+ f"\n💡 Tip: Get a free {PipelexBackend.GATEWAY.display_name} API key!\n"
+ f" With {PipelexBackend.GATEWAY.display_name}, you get unified access to multiple AI providers\n"
+ " (OpenAI, Anthropic, Google, Mistral, etc.) with a single API key.\n"
+ " Check the project's 'README.md' for details on obtaining your key.\n"
+ "\n🔑 Or bring your own keys:\n"
+ " Set your own provider keys (OPENAI_API_KEY, ANTHROPIC_API_KEY, GOOGLE_API_KEY,\n"
+ " MISTRAL_API_KEY, AZURE_API_KEY, etc.) and enable the corresponding backends\n"
+ " in '.pipelex/inference/backends.toml'.\n"
+ )
+
+ return error_msg
diff --git a/pipelex/cogt/model_backends/backend_factory.py b/pipelex/cogt/model_backends/backend_factory.py
index 9e458f01e..0c2f6cd79 100644
--- a/pipelex/cogt/model_backends/backend_factory.py
+++ b/pipelex/cogt/model_backends/backend_factory.py
@@ -1,19 +1,39 @@
from typing import Any
-from pydantic import Field
+from pydantic import Field, field_validator
from pipelex.cogt.model_backends.backend import InferenceBackend
+from pipelex.cogt.model_backends.constraints import ListedConstraint, ValuedConstraint
from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
from pipelex.plugins.openai.vertexai_factory import VertexAIFactory
from pipelex.system.configuration.config_model import ConfigModel
+from pipelex.tools.typing.pydantic_utils import empty_dict_factory_of, empty_list_factory_of
class InferenceBackendBlueprint(ConfigModel):
enabled: bool = True
endpoint: str | None = None
api_key: str | None = None
+ listed_constraints: list[ListedConstraint] = Field(default_factory=empty_list_factory_of(ListedConstraint))
+ valued_constraints: dict[ValuedConstraint, Any] = Field(default_factory=empty_dict_factory_of(ValuedConstraint))
extra_config: dict[str, Any] = Field(default_factory=dict)
+ @field_validator("listed_constraints", mode="before")
+ @classmethod
+ def validate_listed_constraints(cls, value: list[str]) -> list[ListedConstraint]:
+ return ConfigModel.transform_list_of_str_to_enum(
+ input_list=value,
+ enum_cls=ListedConstraint,
+ )
+
+ @field_validator("valued_constraints", mode="before")
+ @classmethod
+ def validate_valued_constraints(cls, value: dict[str, Any]) -> dict[ValuedConstraint, Any]:
+ return ConfigModel.transform_dict_keys_str_to_enum(
+ input_dict=value,
+ key_enum_cls=ValuedConstraint,
+ )
+
class InferenceBackendFactory:
@classmethod
@@ -37,6 +57,8 @@ class InferenceBackendFactory:
enabled=blueprint.enabled,
endpoint=endpoint,
api_key=api_key,
+ listed_constraints=blueprint.listed_constraints,
+ valued_constraints=blueprint.valued_constraints,
extra_config=extra_config,
model_specs=model_specs,
)
diff --git a/pipelex/cogt/model_backends/backend_library.py b/pipelex/cogt/model_backends/backend_library.py
index ea5f0d182..797e051eb 100644
--- a/pipelex/cogt/model_backends/backend_library.py
+++ b/pipelex/cogt/model_backends/backend_library.py
@@ -11,24 +11,26 @@ from pipelex.cogt.exceptions import (
InferenceBackendLibraryValidationError,
InferenceModelSpecError,
)
-from pipelex.cogt.model_backends.backend import InferenceBackend
+from pipelex.cogt.model_backends.backend import InferenceBackend, PipelexBackend
+from pipelex.cogt.model_backends.backend_credentials import BackendCredentialsReport, CredentialsValidationReport
from pipelex.cogt.model_backends.backend_factory import (
InferenceBackendBlueprint,
InferenceBackendFactory,
)
from pipelex.cogt.model_backends.model_spec_factory import (
+ BackendModelSpecs,
InferenceModelSpecBlueprint,
InferenceModelSpecFactory,
)
-from pipelex.system.configuration.config_model import ConfigModel
from pipelex.system.environment import get_optional_env
+from pipelex.system.pipelex_service.gateway_config_merger import GatewayConfigMerger
from pipelex.system.runtime import runtime_manager
from pipelex.tools.misc.dict_utils import (
apply_to_strings_recursive,
extract_vars_from_strings_recursive,
)
from pipelex.tools.misc.placeholder import value_is_placeholder
-from pipelex.tools.misc.toml_utils import load_toml_from_path
+from pipelex.tools.misc.toml_utils import load_toml_from_path, load_toml_from_path_if_exists
from pipelex.tools.secrets.secrets_provider_abstract import SecretsProviderAbstract
from pipelex.tools.secrets.secrets_utils import (
UnknownVarPrefixError,
@@ -45,31 +47,6 @@ if TYPE_CHECKING:
InferenceBackendLibraryRoot = dict[str, InferenceBackend]
-class BackendCredentialStatus(ConfigModel):
- """Status of a single credential variable."""
-
- var_name: str
- is_set: bool
- is_placeholder: bool # True if value exists but is a placeholder like "${VAR}"
-
-
-class BackendCredentialsReport(ConfigModel):
- """Report of credential status for a backend."""
-
- backend_name: str
- required_vars: list[str]
- missing_vars: list[str]
- placeholder_vars: list[str]
- all_credentials_valid: bool
-
-
-class CredentialsValidationReport(ConfigModel):
- """Complete report of credentials validation across all backends."""
-
- backend_reports: dict[str, BackendCredentialsReport]
- all_backends_valid: bool
-
-
class InferenceBackendLibrary(RootModel[InferenceBackendLibraryRoot]):
root: InferenceBackendLibraryRoot = Field(default_factory=dict)
@@ -80,7 +57,25 @@ class InferenceBackendLibrary(RootModel[InferenceBackendLibraryRoot]):
def make_empty(cls) -> Self:
return cls(root={})
- def load(self, secrets_provider: SecretsProviderAbstract, backends_library_path: str, backends_dir_path: str, include_disabled: bool = False):
+ def load(
+ self,
+ secrets_provider: SecretsProviderAbstract,
+ backends_library_path: str,
+ backends_dir_path: str,
+ include_disabled: bool = False,
+ gateway_model_specs: BackendModelSpecs | None = None,
+ ):
+ """Load backend configurations from TOML files.
+
+ For pipelex_gateway, uses the provided remote config and merges with local overrides.
+
+ Args:
+ secrets_provider: Provider for secrets/credentials.
+ backends_library_path: Path to backends.toml.
+ backends_dir_path: Path to directory containing per-backend TOML files.
+ include_disabled: Whether to include disabled backends.
+ gateway_model_specs: Remote model specs for Pipelex Gateway backend.
+ """
try:
backends_dict = load_toml_from_path(path=backends_library_path)
except FileNotFoundError as file_not_found_exc:
@@ -94,9 +89,10 @@ class InferenceBackendLibrary(RootModel[InferenceBackendLibraryRoot]):
# Create a partial function with the secrets provider bound
substitute_vars_with_provider = partial(substitute_vars, secrets_provider=secrets_provider)
+ # We'll split the read settings into standard fields and extra config
+ backend_blueprint_standard_fields = InferenceBackendBlueprint.model_fields.keys()
+ model_spec_blueprint_standard_fields = InferenceModelSpecBlueprint.model_fields.keys()
for backend_name, backend_dict in backends_dict.items():
- # We'll split the read settings into standard fields and extra config
- standard_fields = InferenceBackendBlueprint.model_fields.keys()
extra_config: dict[str, Any] = {}
inference_backend_blueprint_dict_raw = backend_dict.copy()
enabled = inference_backend_blueprint_dict_raw.get("enabled", True)
@@ -138,27 +134,34 @@ class InferenceBackendLibrary(RootModel[InferenceBackendLibraryRoot]):
key_name=unknown_var_prefix_exc.var_name,
) from unknown_var_prefix_exc
- for key in backend_dict:
- if key not in standard_fields:
- extra_config[key] = inference_backend_blueprint_dict.pop(key)
+ for backend_blueprint_key in backend_dict:
+ if backend_blueprint_key not in backend_blueprint_standard_fields:
+ extra_config[backend_blueprint_key] = inference_backend_blueprint_dict.pop(backend_blueprint_key)
backend_blueprint = InferenceBackendBlueprint.model_validate(inference_backend_blueprint_dict)
- path_to_model_specs_toml = f"{backends_dir_path}/{backend_name}.toml"
- try:
- model_specs_dict_raw = load_toml_from_path(path=path_to_model_specs_toml)
- try:
- model_specs_dict = apply_to_strings_recursive(model_specs_dict_raw, substitute_vars_with_provider)
- except (VarNotFoundError, UnknownVarPrefixError) as exc:
- msg = f"Variable substitution failed in file '{path_to_model_specs_toml}': {exc}"
- raise InferenceModelSpecError(msg) from exc
- except (FileNotFoundError, InferenceModelSpecError) as exc:
- msg = f"Failed to load inference model specs from file '{path_to_model_specs_toml}': {exc}"
- raise InferenceBackendLibraryError(msg) from exc
+ # Handle pipelex_gateway specially - use remote config
+ backend_config_source: str
+ if PipelexBackend.is_gateway_backend(backend_name):
+ if gateway_model_specs is None:
+ msg = "Pipelex Gateway backend is enabled but remote model specs were not provided"
+ raise InferenceBackendLibraryError(msg)
+ model_specs_dict, backend_config_source = self._load_gateway_model_specs(
+ gateway_model_specs=gateway_model_specs,
+ backends_dir_path=backends_dir_path,
+ substitute_vars_with_provider=substitute_vars_with_provider,
+ )
+ else:
+ model_specs_dict, backend_config_source = self._load_local_model_specs(
+ backend_name=backend_name,
+ backends_dir_path=backends_dir_path,
+ substitute_vars_with_provider=substitute_vars_with_provider,
+ )
+
defaults_dict: dict[str, Any] = model_specs_dict.pop("defaults", {})
backend_model_specs: dict[str, InferenceModelSpec] = {}
for model_spec_name, value in model_specs_dict.items():
if not isinstance(value, dict):
- msg = f"Model spec '{model_spec_name}' for backend '{backend_name}' at path '{path_to_model_specs_toml}' is not a dictionary"
+ msg = f"Model spec '{model_spec_name}' for backend '{backend_name}' from {backend_config_source} is not a dictionary"
raise InferenceModelSpecError(msg)
model_spec_dict: dict[str, Any] = cast("dict[str, Any]", value)
try:
@@ -166,24 +169,31 @@ class InferenceBackendLibrary(RootModel[InferenceBackendLibraryRoot]):
model_spec_blueprint_dict = defaults_dict.copy()
# Override with the attributes from the model spec dict
model_spec_blueprint_dict.update(model_spec_dict)
+
+ # We'll split the read settings into standard fields and extra headers
+ extra_headers: dict[str, str] = {}
+ for model_spec_key in model_spec_dict:
+ if model_spec_key not in model_spec_blueprint_standard_fields:
+ extra_headers[model_spec_key] = model_spec_blueprint_dict.pop(model_spec_key)
model_spec_blueprint = InferenceModelSpecBlueprint.model_validate(model_spec_blueprint_dict)
model_spec = InferenceModelSpecFactory.make_inference_model_spec(
backend_name=backend_name,
name=model_spec_name,
blueprint=model_spec_blueprint,
+ backend_listed_constraints=backend_blueprint.listed_constraints,
+ backend_valued_constraints=backend_blueprint.valued_constraints,
+ extra_headers=extra_headers,
)
backend_model_specs[model_spec_name] = model_spec
except ValidationError as validation_error:
validation_error_msg = format_pydantic_validation_error(validation_error)
msg = (
f"Invalid inference model spec '{model_spec_name}' for backend '{backend_name}' "
- f"in file '{path_to_model_specs_toml}': {validation_error_msg}"
+ f"from {backend_config_source}: {validation_error_msg}"
)
raise InferenceBackendLibraryError(msg) from validation_error
except InferenceModelSpecError as exc:
- msg = (
- f"Failed to load inference model spec '{model_spec_name}' for backend '{backend_name}' from file '{path_to_model_specs_toml}'"
- )
+ msg = f"Failed to load inference model spec '{model_spec_name}' for backend '{backend_name}' from {backend_config_source}"
raise InferenceBackendLibraryError(msg) from exc
backend = InferenceBackendFactory.make_inference_backend(
name=backend_name,
@@ -193,6 +203,76 @@ class InferenceBackendLibrary(RootModel[InferenceBackendLibraryRoot]):
)
self.root[backend_name] = backend
+ def _load_gateway_model_specs(
+ self,
+ gateway_model_specs: BackendModelSpecs,
+ backends_dir_path: str,
+ substitute_vars_with_provider: Any,
+ ) -> tuple[BackendModelSpecs, str]:
+ """Load model specs for pipelex_gateway from remote config.
+
+ Args:
+ gateway_model_specs: dict of the model specs from the Pipelex Gateway.
+ backends_dir_path: Path to directory containing local override file.
+ substitute_vars_with_provider: Function to substitute variables.
+
+ Returns:
+ Model specs dictionary merged from remote and local overrides.
+
+ Raises:
+ InferenceModelSpecError: If variable substitution fails.
+ """
+ # Load local overrides if they exist
+ path_to_local_overrides = f"{backends_dir_path}/{PipelexBackend.GATEWAY}.toml"
+ local_overrides = load_toml_from_path_if_exists(path=path_to_local_overrides) or {}
+
+ # Merge remote config with local overrides
+ model_specs_dict = GatewayConfigMerger.merge(
+ gateway_model_specs=gateway_model_specs,
+ local_overrides=local_overrides,
+ )
+
+ # Apply variable substitution (in case remote config has any variables)
+ try:
+ model_specs_dict = apply_to_strings_recursive(model_specs_dict, substitute_vars_with_provider)
+ except (VarNotFoundError, UnknownVarPrefixError) as exc:
+ msg = f"Variable substitution failed in remote gateway config: {exc}"
+ raise InferenceModelSpecError(msg) from exc
+
+ return model_specs_dict, f"remote config with local overrides from '{path_to_local_overrides}'"
+
+ def _load_local_model_specs(
+ self,
+ backend_name: str,
+ backends_dir_path: str,
+ substitute_vars_with_provider: Any,
+ ) -> tuple[BackendModelSpecs, str]:
+ """Load model specs from local TOML file.
+
+ Args:
+ backend_name: Name of the backend.
+ backends_dir_path: Path to directory containing TOML files.
+ substitute_vars_with_provider: Function to substitute variables.
+
+ Returns:
+ Model specs dictionary from local TOML.
+
+ Raises:
+ InferenceBackendLibraryError: If loading fails.
+ """
+ path_to_model_specs_toml = f"{backends_dir_path}/{backend_name}.toml"
+ try:
+ model_specs_dict_raw = load_toml_from_path(path=path_to_model_specs_toml)
+ try:
+ model_specs_dict = apply_to_strings_recursive(model_specs_dict_raw, substitute_vars_with_provider)
+ except (VarNotFoundError, UnknownVarPrefixError) as exc:
+ msg = f"Variable substitution failed in file '{path_to_model_specs_toml}': {exc}"
+ raise InferenceModelSpecError(msg) from exc
+ except (FileNotFoundError, InferenceModelSpecError) as exc:
+ msg = f"Failed to load inference model specs from file '{path_to_model_specs_toml}': {exc}"
+ raise InferenceBackendLibraryError(msg) from exc
+ return model_specs_dict, f"file '{path_to_model_specs_toml}'"
+
def check_backend_credentials(self, path: str, include_disabled: bool = False) -> CredentialsValidationReport:
"""Check if required environment variables are set for enabled backends.
diff --git a/pipelex/cogt/model_backends/model_constraints.py b/pipelex/cogt/model_backends/constraints.py
similarity index 52%
rename from pipelex/cogt/model_backends/model_constraints.py
rename to pipelex/cogt/model_backends/constraints.py
index f5ed7881e..d3ec8788c 100644
--- a/pipelex/cogt/model_backends/model_constraints.py
+++ b/pipelex/cogt/model_backends/constraints.py
@@ -1,7 +1,11 @@
from pipelex.types import StrEnum
-class ModelConstraints(StrEnum):
- TEMPERATURE_MUST_BE_1 = "temperature_must_be_1"
+class ListedConstraint(StrEnum):
TEMPERATURE_MUST_BE_MULTIPLIED_BY_2 = "temperature_must_be_multiplied_by_2"
MAX_TOKENS_MUST_BE_HIGH_ENOUGH = "max_tokens_must_be_high_enough"
+
+
+class ValuedConstraint(StrEnum):
+ MAX_OUTPUT_TOKENS_LIMIT = "max_output_tokens_limit"
+ FIXED_TEMPERATURE = "fixed_temperature"
diff --git a/pipelex/cogt/model_backends/model_lists.py b/pipelex/cogt/model_backends/model_lists.py
index 24e280fdd..339df1fd2 100644
--- a/pipelex/cogt/model_backends/model_lists.py
+++ b/pipelex/cogt/model_backends/model_lists.py
@@ -1,26 +1,10 @@
from __future__ import annotations
import importlib.util
-from datetime import datetime
-from typing import TYPE_CHECKING, Any
-from rich import box
-from rich.table import Table
-
-from pipelex.cogt.exceptions import MissingDependencyError
-from pipelex.config import get_config
-from pipelex.hub import get_console
-
-if TYPE_CHECKING:
- from anthropic.types import ModelInfo
- from openai.types import Model
-
- from pipelex.cogt.model_backends.backend import InferenceBackend
from pipelex.cli.exceptions import PipelexCLIError
-from pipelex.hub import get_models_manager
-from pipelex.plugins.openai.openai_llms import openai_list_available_models
-from pipelex.plugins.plugin_sdk_registry import Plugin
-from pipelex.tools.aws.aws_config import AwsCredentialsError
+from pipelex.cogt.exceptions import MissingDependencyError
+from pipelex.hub import get_console, get_models_manager
class ModelLister:
@@ -66,8 +50,10 @@ class ModelLister:
for sdk in models_by_sdk:
try:
match sdk:
- case "openai" | "azure_openai":
- await cls._list_openai_models(
+ case "openai" | "azure_openai" | "openai_responses" | "azure_openai_responses":
+ from pipelex.plugins.openai.openai_list import list_openai_models # noqa: PLC0415
+
+ await list_openai_models(
sdk=sdk,
backend_name=backend_name,
backend=backend,
@@ -76,7 +62,7 @@ class ModelLister:
)
any_listed = True
- case "anthropic" | "bedrock_anthropic":
+ case "anthropic":
if importlib.util.find_spec("anthropic") is None:
lib_name = "anthropic"
lib_extra_name = "anthropic"
@@ -92,9 +78,10 @@ class ModelLister:
)
from pipelex.plugins.anthropic.anthropic_exceptions import AnthropicSDKUnsupportedError # noqa: PLC0415
+ from pipelex.plugins.anthropic.anthropic_list import list_anthropic_models # noqa: PLC0415
try:
- await cls._list_anthropic_models(
+ await list_anthropic_models(
sdk=sdk,
backend_name=backend_name,
backend=backend,
@@ -121,7 +108,9 @@ class ModelLister:
msg,
)
- cls._list_mistral_models(
+ from pipelex.plugins.mistral.mistral_list import list_mistral_models # noqa: PLC0415
+
+ list_mistral_models(
sdk=sdk,
backend_name=backend_name,
flat=flat,
@@ -129,6 +118,28 @@ class ModelLister:
)
any_listed = True
+ case "google":
+ if importlib.util.find_spec("google.genai") is None:
+ lib_name = "google-genai"
+ lib_extra_name = "google"
+ msg = "The google-genai SDK is required to use Google GenAI models."
+ raise MissingDependencyError(
+ lib_name,
+ lib_extra_name,
+ msg,
+ )
+
+ from pipelex.plugins.google.google_list import list_google_models # noqa: PLC0415
+
+ await list_google_models(
+ sdk=sdk,
+ backend_name=backend_name,
+ backend=backend,
+ flat=flat,
+ any_listed=any_listed,
+ )
+ any_listed = True
+
case "bedrock" | "bedrock_aioboto3":
if importlib.util.find_spec("boto3") is None or importlib.util.find_spec("aioboto3") is None:
lib_name = "boto3,aioboto3"
@@ -140,7 +151,9 @@ class ModelLister:
msg,
)
- await cls._list_bedrock_models(
+ from pipelex.plugins.bedrock.bedrock_list import list_bedrock_models # noqa: PLC0415
+
+ list_bedrock_models(
sdk=sdk,
backend_name=backend_name,
backend=backend,
@@ -169,365 +182,6 @@ class ModelLister:
flat=flat,
)
- @classmethod
- async def _list_openai_models(
- cls,
- sdk: str,
- backend_name: str,
- backend: InferenceBackend,
- flat: bool,
- any_listed: bool,
- ) -> None:
- """List OpenAI models."""
- plugin = Plugin(sdk=sdk, backend=backend_name)
- openai_models = await openai_list_available_models(
- plugin=plugin,
- backend=backend,
- )
-
- if flat:
- cls._display_openai_models_flat(
- models=openai_models,
- sdk=sdk,
- backend_name=backend_name,
- any_listed=any_listed,
- )
- else:
- cls._display_openai_models_table(
- models=openai_models,
- sdk=sdk,
- backend_name=backend_name,
- )
-
- @classmethod
- async def _list_anthropic_models(
- cls,
- sdk: str,
- backend_name: str,
- backend: InferenceBackend,
- flat: bool,
- any_listed: bool,
- ) -> None:
- """List Anthropic models."""
- if importlib.util.find_spec("anthropic") is None:
- lib_name = "anthropic"
- lib_extra_name = "anthropic"
- msg = (
- "The anthropic SDK is required in order to use Anthropic models via the anthropic client. "
- "However, you can use Anthropic models through bedrock directly "
- "by using the 'bedrock-anthropic-claude' llm family. (eg: bedrock-anthropic-claude)"
- )
- raise MissingDependencyError(
- lib_name,
- lib_extra_name,
- msg,
- )
-
- from anthropic import AuthenticationError # noqa: PLC0415
-
- from pipelex.plugins.anthropic.anthropic_llms import anthropic_list_available_models # noqa: PLC0415
-
- plugin = Plugin(sdk=sdk, backend=backend_name)
- try:
- anthropic_models = await anthropic_list_available_models(
- plugin=plugin,
- backend=backend,
- )
-
- if flat:
- cls._display_anthropic_models_flat(
- models=anthropic_models,
- sdk=sdk,
- backend_name=backend_name,
- any_listed=any_listed,
- )
- else:
- cls._display_anthropic_models_table(
- models=anthropic_models,
- sdk=sdk,
- backend_name=backend_name,
- )
- except AuthenticationError as auth_exc:
- msg = f"Authentication error for SDK '{sdk}' in backend '{backend_name}': {auth_exc}"
- raise PipelexCLIError(msg) from auth_exc
-
- @classmethod
- def _list_mistral_models(
- cls,
- sdk: str,
- backend_name: str,
- flat: bool,
- any_listed: bool,
- ) -> None:
- """List Mistral models."""
- if importlib.util.find_spec("mistralai") is None:
- lib_name = "mistralai"
- lib_extra_name = "mistral"
- msg = (
- "The mistralai SDK is required in order to use Mistral models through the mistralai client. "
- "However, you can use Mistral models through bedrock directly "
- "by using the 'bedrock-mistral' llm family. (eg: bedrock-mistral-large)"
- )
- raise MissingDependencyError(
- lib_name,
- lib_extra_name,
- msg,
- )
-
- from pipelex.plugins.mistral.mistral_llms import mistral_list_available_models # noqa: PLC0415
-
- mistral_models = mistral_list_available_models()
-
- if flat:
- cls._display_mistral_models_flat(
- models=mistral_models,
- sdk=sdk,
- backend_name=backend_name,
- any_listed=any_listed,
- )
- else:
- cls._display_mistral_models_table(
- models=mistral_models,
- sdk=sdk,
- backend_name=backend_name,
- )
-
- @classmethod
- async def _list_bedrock_models(
- cls,
- sdk: str,
- backend_name: str,
- backend: InferenceBackend,
- flat: bool,
- any_listed: bool,
- ) -> None:
- """List Bedrock models."""
- if importlib.util.find_spec("boto3") is None or importlib.util.find_spec("aioboto3") is None:
- lib_name = "boto3,aioboto3"
- lib_extra_name = "bedrock"
- msg = "The boto3 and aioboto3 SDKs are required to use Bedrock models."
- raise MissingDependencyError(
- lib_name,
- lib_extra_name,
- msg,
- )
-
- from pipelex.plugins.bedrock.bedrock_llms import bedrock_list_available_models # noqa: PLC0415
-
- plugin = Plugin(sdk=sdk, backend=backend_name)
-
- try:
- # Get AWS region for display
- aws_config = get_config().pipelex.aws_config
- _, _, aws_region = aws_config.get_aws_access_keys()
- except AwsCredentialsError as exc:
- msg = f"Error getting AWS credentials for Bedrock: {exc}"
- raise PipelexCLIError(msg) from exc
-
- try:
- # List available models using the plugin-specific function
- bedrock_models_list = bedrock_list_available_models(
- plugin=plugin,
- backend=backend,
- )
-
- if flat:
- cls._display_bedrock_models_flat(
- models=bedrock_models_list,
- sdk=sdk,
- backend_name=backend_name,
- aws_region=aws_region,
- any_listed=any_listed,
- )
- else:
- cls._display_bedrock_models_table(
- models=bedrock_models_list,
- sdk=sdk,
- aws_region=aws_region,
- )
-
- except Exception as exc:
- msg = f"Error listing Bedrock models: {exc}"
- raise PipelexCLIError(msg) from exc
-
- @staticmethod
- def _display_openai_models_flat(
- models: list[Model],
- sdk: str,
- backend_name: str,
- any_listed: bool,
- ) -> None:
- """Display OpenAI models in CSV format."""
- console = get_console()
- if not any_listed:
- console.print("model_id,created,owned_by,sdk,backend")
- for model in models:
- # Convert Unix timestamp to formatted date
- if hasattr(model, "created") and model.created:
- created = datetime.fromtimestamp(model.created).strftime("%Y-%m-%d") # noqa: DTZ006
- else:
- created = "N/A"
- owned_by = model.owned_by if hasattr(model, "owned_by") else "N/A"
- console.print(f"{model.id},{created},{owned_by},{sdk},{backend_name}")
-
- @staticmethod
- def _display_openai_models_table(
- models: list[Model],
- sdk: str,
- backend_name: str,
- ) -> None:
- """Display OpenAI models in table format."""
- table = Table(
- title=f"Available Models for Backend '{backend_name}' (SDK: {sdk})",
- show_header=True,
- header_style="bold cyan",
- box=box.SQUARE_DOUBLE_HEAD,
- )
- table.add_column("Model ID", style="green")
- table.add_column("Created", style="yellow")
- table.add_column("Owned By", style="blue")
-
- for model in models:
- # Convert Unix timestamp to formatted date
- if hasattr(model, "created") and model.created:
- created = datetime.fromtimestamp(model.created).strftime("%Y-%m-%d") # noqa: DTZ006
- else:
- created = "N/A"
- owned_by = model.owned_by if hasattr(model, "owned_by") else "N/A"
- table.add_row(model.id, created, owned_by)
- console = get_console()
- console.print("\n")
- console.print(table)
- console.print("\n")
-
- @staticmethod
- def _display_anthropic_models_flat(
- models: list[ModelInfo],
- sdk: str,
- backend_name: str,
- any_listed: bool,
- ) -> None:
- """Display Anthropic models in CSV format."""
- console = get_console()
- if not any_listed:
- console.print("model_id,display_name,created_at,sdk,backend")
- for anthropic_model in models:
- created_date = anthropic_model.created_at.strftime("%Y-%m-%d") if anthropic_model.created_at else "N/A"
- display_name = anthropic_model.display_name.replace(",", ";") if anthropic_model.display_name else "N/A"
- console.print(f"{anthropic_model.id},{display_name},{created_date},{sdk},{backend_name}")
-
- @staticmethod
- def _display_anthropic_models_table(
- models: list[ModelInfo],
- sdk: str,
- backend_name: str,
- ) -> None:
- """Display Anthropic models in table format."""
- table = Table(
- title=f"Available Models for Backend '{backend_name}' (SDK: {sdk})",
- show_header=True,
- header_style="bold cyan",
- box=box.SQUARE_DOUBLE_HEAD,
- )
- table.add_column("Model ID", style="green")
- table.add_column("Display Name", style="blue")
- table.add_column("Created At", style="yellow")
-
- for anthropic_model in models:
- created_date = anthropic_model.created_at.strftime("%Y-%m-%d") if anthropic_model.created_at else "N/A"
- table.add_row(anthropic_model.id, anthropic_model.display_name, created_date)
-
- console = get_console()
- console.print("\n")
- console.print(table)
- console.print("\n")
-
- @staticmethod
- def _display_mistral_models_flat(
- models: list[Any],
- sdk: str,
- backend_name: str,
- any_listed: bool,
- ) -> None:
- """Display Mistral models in CSV format."""
- console = get_console()
- if not any_listed:
- console.print("model_id,max_context_length,sdk,backend")
- for mistral_model in models:
- max_ctx = str(mistral_model.max_context_length) if mistral_model.max_context_length else "N/A"
- console.print(f"{mistral_model.id},{max_ctx},{sdk},{backend_name}")
-
- @staticmethod
- def _display_mistral_models_table(
- models: list[Any],
- sdk: str,
- backend_name: str,
- ) -> None:
- """Display Mistral models in table format."""
- table = Table(
- title=f"Available Models for Backend '{backend_name}' (SDK: {sdk})",
- show_header=True,
- header_style="bold cyan",
- box=box.SQUARE_DOUBLE_HEAD,
- )
- table.add_column("Model ID", style="green")
- table.add_column("Max Context Length", style="yellow")
-
- for mistral_model in models:
- max_ctx = str(mistral_model.max_context_length) if mistral_model.max_context_length else "N/A"
- table.add_row(mistral_model.id, max_ctx)
-
- console = get_console()
- console.print("\n")
- console.print(table)
- console.print("\n")
-
- @staticmethod
- def _display_bedrock_models_flat(
- models: list[dict[str, Any]],
- sdk: str,
- backend_name: str,
- aws_region: str,
- any_listed: bool,
- ) -> None:
- """Display Bedrock models in CSV format."""
- console = get_console()
- if not any_listed:
- console.print("model_id,provider,model_arn,sdk,backend,region")
- for bedrock_model in models: # pyright: ignore[reportUnknownVariableType]
- model_id = bedrock_model.get("modelId", "N/A") # pyright: ignore[reportUnknownMemberType,reportUnknownVariableType]
- provider = bedrock_model.get("providerName", "N/A") # pyright: ignore[reportUnknownMemberType,reportUnknownVariableType]
- model_arn = bedrock_model.get("modelArn", "N/A") # pyright: ignore[reportUnknownMemberType,reportUnknownVariableType]
- console.print(f"{model_id},{provider},{model_arn},{sdk},{backend_name},{aws_region}") # pyright: ignore[reportUnknownArgumentType]
-
- @staticmethod
- def _display_bedrock_models_table(
- models: list[dict[str, Any]],
- sdk: str,
- aws_region: str,
- ) -> None:
- """Display Bedrock models in table format."""
- table = Table(
- title=f"Available Bedrock Models in {aws_region} (SDK: {sdk})",
- show_header=True,
- header_style="bold cyan",
- box=box.SQUARE_DOUBLE_HEAD,
- )
- table.add_column("Model ID", style="green")
- table.add_column("Provider", style="blue")
- table.add_column("Model ARN", style="yellow")
-
- for bedrock_model in models: # pyright: ignore[reportUnknownVariableType]
- model_id = bedrock_model.get("modelId", "N/A") # pyright: ignore[reportUnknownMemberType,reportUnknownVariableType]
- provider = bedrock_model.get("providerName", "N/A") # pyright: ignore[reportUnknownMemberType,reportUnknownVariableType]
- model_arn = bedrock_model.get("modelArn", "N/A") # pyright: ignore[reportUnknownMemberType,reportUnknownVariableType]
- table.add_row(model_id, provider, model_arn) # pyright: ignore[reportUnknownArgumentType]
-
- console = get_console()
- console.print("\n")
- console.print(table)
- console.print("\n")
-
@staticmethod
def _display_unsupported_sdks_message(
any_listed: bool,
@@ -540,10 +194,10 @@ class ModelLister:
if not any_listed and unsupported_sdks:
console = get_console()
if not flat:
- console.print(f"\n[yellow]Note: Backend '{backend_name}' has models using SDKs that don't support remote listing:[/yellow]")
+ console.print(f"\n[yellow]Note: Backend '{backend_name}' has models using SDKs that we don't support for remote listing:[/yellow]")
for sdk in unsupported_sdks:
console.print(f" • {sdk} ({len(models_by_sdk[sdk])} configured model(s))")
console.print("\n[dim]Configured models are still available for use in pipelines.[/dim]\n")
else:
# In flat mode, just print a simple comment
- console.print(f"# Note: Backend '{backend_name}' has {len(unsupported_sdks)} SDK(s) that don't support remote listing")
+ console.print(f"# Note: Backend '{backend_name}' has {len(unsupported_sdks)} SDK(s) that we don't support for remote listing")
diff --git a/pipelex/cogt/model_backends/model_spec.py b/pipelex/cogt/model_backends/model_spec.py
index d42caf1c8..aad39abe6 100644
--- a/pipelex/cogt/model_backends/model_spec.py
+++ b/pipelex/cogt/model_backends/model_spec.py
@@ -1,13 +1,15 @@
+from typing import Any
+
from instructor import Mode as InstructorMode
from pydantic import Field
from pipelex.cogt.llm.structured_output import StructureMethod
-from pipelex.cogt.model_backends.model_constraints import ModelConstraints
+from pipelex.cogt.model_backends.constraints import ListedConstraint, ValuedConstraint
from pipelex.cogt.model_backends.model_type import ModelType
from pipelex.cogt.model_backends.prompting_target import PromptingTarget
from pipelex.cogt.usage.cost_category import CostsByCategoryDict
from pipelex.system.configuration.config_model import ConfigModel
-from pipelex.tools.typing.pydantic_utils import empty_list_factory_of
+from pipelex.tools.typing.pydantic_utils import empty_dict_factory_of, empty_list_factory_of
class InferenceModelSpec(ConfigModel):
@@ -23,7 +25,9 @@ class InferenceModelSpec(ConfigModel):
max_tokens: int | None
max_prompt_images: int | None
prompting_target: PromptingTarget | None = Field(default=None, strict=False)
- constraints: list[ModelConstraints] = Field(default_factory=empty_list_factory_of(ModelConstraints))
+ listed_constraints: list[ListedConstraint] = Field(default_factory=empty_list_factory_of(ListedConstraint))
+ valued_constraints: dict[ValuedConstraint, Any] = Field(default_factory=empty_dict_factory_of(ValuedConstraint))
+ extra_headers: dict[str, str] | None = None
@property
def tag(self) -> str:
diff --git a/pipelex/cogt/model_backends/model_spec_factory.py b/pipelex/cogt/model_backends/model_spec_factory.py
index 82ee288fe..23650d3c5 100644
--- a/pipelex/cogt/model_backends/model_spec_factory.py
+++ b/pipelex/cogt/model_backends/model_spec_factory.py
@@ -1,20 +1,24 @@
+from typing import Any
+
from pydantic import BaseModel, Field, field_validator
from pipelex.cogt.llm.structured_output import StructureMethod
-from pipelex.cogt.model_backends.model_constraints import ModelConstraints
+from pipelex.cogt.model_backends.constraints import ListedConstraint, ValuedConstraint
from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
from pipelex.cogt.model_backends.model_type import ModelType
from pipelex.cogt.model_backends.prompting_target import PromptingTarget
from pipelex.cogt.usage.cost_category import CostCategory, CostsByCategoryDict
from pipelex.system.configuration.config_model import ConfigModel
-from pipelex.tools.typing.pydantic_utils import empty_list_factory_of
+from pipelex.tools.typing.pydantic_utils import empty_dict_factory_of, empty_list_factory_of
+
+BackendModelSpecs = dict[str, Any]
class InferenceModelSpecBlueprint(ConfigModel):
enabled: bool = True
sdk: str
model_type: ModelType = Field(default=ModelType.LLM, strict=False)
- model_id: str
+ model_id: str | None = None
inputs: list[str] = Field(default_factory=list)
outputs: list[str] = Field(default_factory=list)
costs: CostsByCategoryDict = Field(strict=False)
@@ -22,7 +26,8 @@ class InferenceModelSpecBlueprint(ConfigModel):
max_tokens: int | None = None
max_prompt_images: int | None = None
prompting_target: PromptingTarget | None = Field(default=None, strict=False)
- constraints: list[ModelConstraints] = Field(default_factory=empty_list_factory_of(ModelConstraints))
+ listed_constraints: list[ListedConstraint] = Field(default_factory=empty_list_factory_of(ListedConstraint))
+ valued_constraints: dict[ValuedConstraint, Any] = Field(default_factory=empty_dict_factory_of(ValuedConstraint))
@field_validator("costs", mode="before")
@staticmethod
@@ -32,12 +37,20 @@ class InferenceModelSpecBlueprint(ConfigModel):
key_enum_cls=CostCategory,
)
- @field_validator("constraints", mode="before")
+ @field_validator("listed_constraints", mode="before")
@staticmethod
- def validate_constraints(value: list[str]) -> list[ModelConstraints]:
+ def validate_listed_constraints(value: list[str]) -> list[ListedConstraint]:
return ConfigModel.transform_list_of_str_to_enum(
input_list=value,
- enum_cls=ModelConstraints,
+ enum_cls=ListedConstraint,
+ )
+
+ @field_validator("valued_constraints", mode="before")
+ @staticmethod
+ def validate_valued_constraints(value: dict[str, Any]) -> dict[ValuedConstraint, Any]:
+ return ConfigModel.transform_dict_keys_str_to_enum(
+ input_dict=value,
+ key_enum_cls=ValuedConstraint,
)
@@ -48,13 +61,22 @@ class InferenceModelSpecFactory(BaseModel):
backend_name: str,
name: str,
blueprint: InferenceModelSpecBlueprint,
+ backend_listed_constraints: list[ListedConstraint],
+ backend_valued_constraints: dict[ValuedConstraint, Any],
+ extra_headers: dict[str, str] | None = None,
) -> InferenceModelSpec:
+ # Merge constraints: backend as base, model-level adds/overrides
+ # Listed constraints: union of backend + model (model can add, not remove)
+ merged_listed_constraints = list(set(backend_listed_constraints + blueprint.listed_constraints))
+ # Valued constraints: backend as base, model overrides
+ merged_valued_constraints = {**backend_valued_constraints, **blueprint.valued_constraints}
+
return InferenceModelSpec(
backend_name=backend_name,
name=name,
sdk=blueprint.sdk,
model_type=blueprint.model_type,
- model_id=blueprint.model_id,
+ model_id=blueprint.model_id or name,
inputs=blueprint.inputs,
outputs=blueprint.outputs,
costs=blueprint.costs,
@@ -62,5 +84,7 @@ class InferenceModelSpecFactory(BaseModel):
max_tokens=blueprint.max_tokens,
max_prompt_images=blueprint.max_prompt_images,
prompting_target=blueprint.prompting_target,
- constraints=blueprint.constraints,
+ listed_constraints=merged_listed_constraints,
+ valued_constraints=merged_valued_constraints,
+ extra_headers=extra_headers,
)
diff --git a/pipelex/cogt/model_routing/routing_profile.py b/pipelex/cogt/model_routing/routing_profile.py
index ae7d6aeef..92732f244 100644
--- a/pipelex/cogt/model_routing/routing_profile.py
+++ b/pipelex/cogt/model_routing/routing_profile.py
@@ -3,6 +3,16 @@ from pydantic import Field
from pipelex.cogt.model_routing.routing_models import BackendMatchForModel, BackendMatchingMethod
from pipelex.system.configuration.config_model import ConfigModel
from pipelex.tools.misc.string_utils import matches_wildcard_pattern
+from pipelex.types import StrEnum
+
+
+class PipelexRoutingProfile(StrEnum):
+ """Special Pipelex routing profiles."""
+
+ PIPELEX_GATEWAY_FIRST = "pipelex_gateway_first"
+ PIPELEX_FIRST = "pipelex_first" # Legacy, deprecated - use PIPELEX_GATEWAY_FIRST
+ ALL_PIPELEX_GATEWAY = "all_pipelex_gateway"
+ ALL_PIPELEX_INFERENCE = "all_pipelex_inference" # Legacy, deprecated
class RoutingProfile(ConfigModel):
diff --git a/pipelex/cogt/models/model_deck.py b/pipelex/cogt/models/model_deck.py
index f95b3dfee..431717b3f 100644
--- a/pipelex/cogt/models/model_deck.py
+++ b/pipelex/cogt/models/model_deck.py
@@ -21,7 +21,8 @@ from pipelex.cogt.llm.llm_setting import (
LLMSettingChoices,
LLMSettingChoicesDefaults,
)
-from pipelex.cogt.model_backends.model_constraints import ModelConstraints
+from pipelex.cogt.model_backends.backend import PipelexBackend
+from pipelex.cogt.model_backends.constraints import ValuedConstraint
from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
from pipelex.cogt.model_backends.model_type import ModelType
from pipelex.system.configuration.config_model import ConfigModel
@@ -163,10 +164,11 @@ class ModelDeck(ConfigModel):
f"which is greater than the model's max_tokens of {inference_model.max_tokens}"
)
raise LLMSettingsValidationError(msg)
- if ModelConstraints.TEMPERATURE_MUST_BE_1 in inference_model.constraints and llm_setting.temperature != 1:
+ fixed_temperature = inference_model.valued_constraints.get(ValuedConstraint.FIXED_TEMPERATURE)
+ if fixed_temperature is not None and llm_setting.temperature != fixed_temperature:
msg = (
f"LLM setting '{llm_setting.model}' has a temperature of {llm_setting.temperature}, "
- f"which is not allowed by the model's constraints: it must be 1"
+ f"which is not allowed by the model's constraints: it must be {fixed_temperature}"
)
raise LLMSettingsValidationError(msg)
@@ -199,7 +201,7 @@ class ModelDeck(ConfigModel):
def validate_llm_presets(self) -> Self:
for llm_preset_id, llm_setting in self.llm_presets.items():
if not self.is_model_handle_defined(model_handle=llm_setting.model):
- enabled_backends = {model.backend_name for model in self.inference_models.values()}
+ enabled_backends = self._get_enabled_backends()
msg = f"LLM handle '{llm_setting.model}' for llm preset '{llm_preset_id}' was not found in the model deck"
raise LLMHandleNotFoundError(
message=msg,
@@ -287,6 +289,10 @@ class ModelDeck(ConfigModel):
for model_handle in self.inference_models:
self.get_required_inference_model(model_handle=model_handle)
+ def _get_enabled_backends(self) -> set[str]:
+ """Return the set of backend names that have at least one model enabled."""
+ return {model.backend_name for model in self.inference_models.values()}
+
def _is_model_available_in_backend(self, model_handle: str, backend_name: str) -> bool | None:
"""Check if a model is available from a specific backend.
@@ -296,7 +302,7 @@ class ModelDeck(ConfigModel):
Args:
model_handle: The model handle/name to check for
- backend_name: The backend name (e.g., 'pipelex_inference')
+ backend_name: The backend name (e.g., 'bedrock')
Returns:
True if the model is defined in the backend's TOML file, False otherwise
@@ -346,14 +352,23 @@ class ModelDeck(ConfigModel):
f"and the workflow might fail due to feature limitations such as context window size, etc. "
f"Consider getting access to '{ideal_model_handle}'."
)
- enabled_backends = {model.backend_name for model in self.inference_models.values()}
- if "pipelex_inference" not in enabled_backends and self._is_model_available_in_backend(
- model_handle=ideal_model_handle, backend_name="pipelex_inference"
+ enabled_backends = self._get_enabled_backends()
+ if PipelexBackend.GATEWAY not in enabled_backends and self._is_model_available_in_backend(
+ model_handle=ideal_model_handle, backend_name=PipelexBackend.GATEWAY
):
msg += (
- f" Note that many high quality models such as '{ideal_model_handle}' are available from the Pipelex Inference "
- f"platform and you can get free credits to try them out, please see our docs for more details about setting up "
- f"Pipelex Inference or other inference backends:\n{URLs.backend_provider_docs}"
+ f" Note that many high quality models such as '{ideal_model_handle}' are available "
+ f"from the {PipelexBackend.GATEWAY.display_name} "
+ f"and you can get free credits to try them out."
+ )
+ if PipelexBackend.LEGACY_INFERENCE in enabled_backends:
+ msg += (
+ f"\nAlso note that {PipelexBackend.LEGACY_INFERENCE.display_name} is deprecated "
+ "and will be removed in the near future."
+ )
+ msg += (
+ f"\nPlease see our docs for more details about setting up "
+ f"{PipelexBackend.GATEWAY.display_name} or other inference backends:\n{URLs.backend_provider_docs}"
)
else:
msg += f" Please see our docs for more details about setting up inference backends:\n{URLs.backend_provider_docs}"
@@ -377,7 +392,7 @@ class ModelDeck(ConfigModel):
if inference_model is None:
msg = (
f"Model handle '{model_handle}' was not found in the model deck. "
- "Make sure it's defined in ond of the model decks '.pipelex/inference/deck/*.toml'. "
+ "Make sure it's defined in one of the model decks '.pipelex/inference/deck/*.toml'. "
"If the model handle is indeed in the deck, make sure the required backend for this model to run is enabled in "
"'.pipelex/inference/backends.toml' and that you have the necessary credentials. "
"To find what backend is required for this model, look at the routing profile in '.pipelex/inference/routing_profiles.toml' "
diff --git a/pipelex/cogt/models/model_manager.py b/pipelex/cogt/models/model_manager.py
index 3abc0cf95..f3be223fd 100644
--- a/pipelex/cogt/models/model_manager.py
+++ b/pipelex/cogt/models/model_manager.py
@@ -4,6 +4,7 @@ from pipelex.cogt.exceptions import ModelManagerError
from pipelex.cogt.model_backends.backend import InferenceBackend
from pipelex.cogt.model_backends.backend_library import InferenceBackendLibrary
from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
+from pipelex.cogt.model_backends.model_spec_factory import BackendModelSpecs
from pipelex.cogt.model_routing.routing_models import BackendMatchingMethod
from pipelex.cogt.model_routing.routing_profile import RoutingProfile
from pipelex.cogt.model_routing.routing_profile_loader import load_active_routing_profile
@@ -50,11 +51,16 @@ class ModelManager(ModelManagerAbstract):
self._routing_profile = None
@override
- def setup(self, secrets_provider: SecretsProviderAbstract) -> None:
+ def setup(
+ self,
+ secrets_provider: SecretsProviderAbstract,
+ gateway_model_specs: BackendModelSpecs | None,
+ ) -> None:
self.inference_backend_library.load(
secrets_provider=secrets_provider,
backends_library_path=ConfigPaths.BACKENDS_FILE_PATH,
backends_dir_path=ConfigPaths.BACKENDS_DIR_PATH,
+ gateway_model_specs=gateway_model_specs,
)
enabled_backends = self.inference_backend_library.all_enabled_backends()
self._routing_profile = load_active_routing_profile(
diff --git a/pipelex/cogt/models/model_manager_abstract.py b/pipelex/cogt/models/model_manager_abstract.py
index e97a35c64..6e62dad71 100644
--- a/pipelex/cogt/models/model_manager_abstract.py
+++ b/pipelex/cogt/models/model_manager_abstract.py
@@ -2,6 +2,7 @@ from abc import ABC, abstractmethod
from pipelex.cogt.model_backends.backend import InferenceBackend
from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
+from pipelex.cogt.model_backends.model_spec_factory import BackendModelSpecs
from pipelex.cogt.models.model_deck import ModelDeck
from pipelex.tools.secrets.secrets_provider_abstract import SecretsProviderAbstract
@@ -16,7 +17,11 @@ class ModelManagerAbstract(ABC):
pass
@abstractmethod
- def setup(self, secrets_provider: SecretsProviderAbstract) -> None:
+ def setup(
+ self,
+ secrets_provider: SecretsProviderAbstract,
+ gateway_model_specs: BackendModelSpecs | None,
+ ) -> None:
pass
@abstractmethod
diff --git a/pipelex/core/concepts/concept.py b/pipelex/core/concepts/concept.py
index 03c144c61..b6d671abe 100644
--- a/pipelex/core/concepts/concept.py
+++ b/pipelex/core/concepts/concept.py
@@ -12,6 +12,7 @@ from pipelex.core.concepts.concept_representation_generator import (
from pipelex.core.concepts.exceptions import ConceptCodeError, ConceptValueError
from pipelex.core.concepts.native.concept_native import NativeConceptCode
from pipelex.core.concepts.validation import validate_concept_code
+from pipelex.core.domains.domain import SpecialDomain
from pipelex.core.domains.exceptions import DomainCodeError
from pipelex.core.domains.validation import validate_domain_code
from pipelex.core.stuffs.image_field_search import search_for_nested_image_fields
@@ -65,6 +66,13 @@ class Concept(BaseModel):
def concept_string(self) -> str:
return f"{self.domain}.{self.code}"
+ @property
+ def simple_concept_string(self) -> str:
+ if SpecialDomain.is_native(domain=self.domain):
+ return self.code
+ else:
+ return self.concept_string
+
@classmethod
def sentence_from_concept(cls, concept: "Concept") -> str:
return pascal_case_to_sentence(name=concept.code)
diff --git a/pipelex/core/pipes/pipe_abstract.py b/pipelex/core/pipes/pipe_abstract.py
index 6772324f7..f2d1491a7 100644
--- a/pipelex/core/pipes/pipe_abstract.py
+++ b/pipelex/core/pipes/pipe_abstract.py
@@ -1,6 +1,8 @@
from abc import ABC, abstractmethod
from typing import Any, final
+from opentelemetry import trace
+from opentelemetry.trace import NonRecordingSpan, Span, SpanContext, SpanKind, Status, StatusCode, TraceFlags
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from pipelex import log
@@ -15,7 +17,18 @@ from pipelex.core.pipes.pipe_output import PipeOutput
from pipelex.pipe_run.pipe_run_mode import PipeRunMode
from pipelex.pipe_run.pipe_run_params import PipeRunParams
from pipelex.pipeline.exceptions import PipeStackOverflowError
-from pipelex.pipeline.job_metadata import JobMetadata
+from pipelex.pipeline.job_metadata import JobMetadata, OtelContext
+from pipelex.pipeline.pipeline_factory import PipelineFactory
+from pipelex.system.telemetry.otel_constants import (
+ LangfuseSpanAttr,
+ OTelConstants,
+ PipelexSpanAttr,
+ SpanCategory,
+ SpanOutcome,
+)
+from pipelex.system.telemetry.otel_factory import OtelFactory
+from pipelex.system.telemetry.telemetry_manager_abstract import TelemetryManagerAbstract
+from pipelex.tools.misc.package_utils import get_package_version
from pipelex.tools.misc.string_utils import is_snake_case
from pipelex.types import Self
@@ -288,6 +301,180 @@ class PipeAbstract(ABC, BaseModel):
) -> PipeOutput:
pass
+ def _start_pipe_span(
+ self,
+ parent_otel_context: OtelContext,
+ pipeline_run_id: str,
+ working_memory: WorkingMemory,
+ ) -> tuple[Span | None, bool]:
+ """Start an OTel span for this pipe execution.
+
+ Always includes full (non-redacted) pipe codes and content in span attributes.
+ Redaction is handled by individual exporters based on their TelemetryRedactionConfig.
+
+ Args:
+ parent_otel_context: The parent's OTel context.
+ pipeline_run_id: The pipeline run ID for span attributes.
+ working_memory: The working memory containing input stuffs for telemetry capture.
+
+ Returns:
+ A tuple of (span, is_root_span) where span is the started span or None if tracer
+ is unavailable, and is_root_span indicates if this is the trace root span.
+ """
+ tracer = TelemetryManagerAbstract.get_instance_tracer()
+ if tracer is None:
+ log.verbose(f"[OTel] No tracer available for pipe '{self.code}'")
+ return None, False
+
+ # Always use full pipe code - redaction is handled by exporters
+ span_name = f"{self.pipe_type}: {self.code}"
+
+ # For root spans: parent_otel_context.span_id is OTEL_VIRTUAL_ROOT_PARENT_SPAN_ID (1)
+ # This ensures OTel uses our trace_id (INVALID_SPAN_ID=0 makes context invalid).
+ # The exporter filters out this virtual parent when setting $ai_parent_id.
+ # For child spans: parent_otel_context.span_id is the actual parent's span_id
+ parent_span_id = parent_otel_context.span_id
+ is_root_span = parent_span_id == OTelConstants.OTEL_VIRTUAL_ROOT_PARENT_SPAN_ID
+
+ # Build all span attributes upfront with FULL (non-redacted) values
+ # PostHog exporters will apply redaction based on their TelemetryRedactionConfig
+ # Langfuse gets full data - users who configure Langfuse control their own data exposure
+ span_attributes: dict[str, str] = {
+ # Pipelex-specific attributes (always full values, exporters redact as needed)
+ PipelexSpanAttr.TRACE_NAME: parent_otel_context.trace_name,
+ PipelexSpanAttr.TRACE_NAME_REDACTED: parent_otel_context.trace_name_redacted,
+ PipelexSpanAttr.SPAN_CATEGORY: SpanCategory.PIPE,
+ PipelexSpanAttr.PIPELINE_RUN_ID: pipeline_run_id,
+ PipelexSpanAttr.PIPE_CATEGORY: self.pipe_category,
+ PipelexSpanAttr.PIPE_TYPE: self.pipe_type,
+ PipelexSpanAttr.PIPE_CODE: self.code, # Full pipe code, exporter handles redaction
+ }
+
+ # Langfuse-specific attributes: always send full data
+ if TelemetryManagerAbstract.get_langfuse_enabled():
+ span_attributes.update(
+ {
+ LangfuseSpanAttr.TRACE_NAME: parent_otel_context.trace_name,
+ LangfuseSpanAttr.RELEASE: get_package_version(),
+ LangfuseSpanAttr.OBSERVATION_TYPE: SpanCategory.PIPE,
+ LangfuseSpanAttr.OBSERVATION_PIPE_CATEGORY: self.pipe_category,
+ LangfuseSpanAttr.OBSERVATION_PIPE_TYPE: self.pipe_type,
+ LangfuseSpanAttr.OBSERVATION_PIPE_CODE: self.code,
+ LangfuseSpanAttr.OBSERVATION_PIPELINE_RUN_ID: pipeline_run_id,
+ }
+ )
+ if self.description:
+ span_attributes[LangfuseSpanAttr.OBSERVATION_DESCRIPTION] = self.description
+
+ # Capture full input content for Langfuse
+ needed_input_names = set(self.needed_inputs().required_names)
+ inputs_json = OtelFactory.make_inputs_json(
+ working_memory=working_memory,
+ needed_input_names=needed_input_names,
+ max_length=None, # No truncation for Langfuse
+ )
+ span_attributes[LangfuseSpanAttr.OBSERVATION_INPUT] = inputs_json
+
+ # For root span, also set trace-level input and metadata
+ if is_root_span:
+ span_attributes[LangfuseSpanAttr.TRACE_INPUT] = inputs_json
+ # Set trace-level metadata (filterable in Langfuse UI)
+ span_attributes[LangfuseSpanAttr.TRACE_PIPE_CODE] = self.code
+ span_attributes[LangfuseSpanAttr.TRACE_PIPE_TYPE] = self.pipe_type
+ span_attributes[LangfuseSpanAttr.TRACE_PIPE_CATEGORY] = self.pipe_category
+ span_attributes[LangfuseSpanAttr.TRACE_PIPELINE_RUN_ID] = pipeline_run_id
+ if self.description:
+ span_attributes[LangfuseSpanAttr.TRACE_DESCRIPTION] = self.description
+
+ parent_span_context = SpanContext(
+ trace_id=parent_otel_context.trace_id,
+ span_id=parent_span_id,
+ is_remote=True,
+ trace_flags=TraceFlags(TraceFlags.SAMPLED),
+ )
+ parent_ctx = trace.set_span_in_context(NonRecordingSpan(parent_span_context))
+
+ # Start span with attributes - OTel generates the span_id, we capture it after
+ span = tracer.start_span(
+ name=span_name,
+ kind=SpanKind.INTERNAL,
+ context=parent_ctx,
+ attributes=span_attributes,
+ )
+
+ # Debug logging
+ span_ctx = span.get_span_context()
+ log.verbose(
+ f"[OTel] PIPE SPAN STARTED:\n"
+ f" pipe_code='{self.code}'\n"
+ f" pipeline_run_id='{pipeline_run_id}'\n"
+ f" trace_id={span_ctx.trace_id:032x}\n"
+ f" span_id={span_ctx.span_id:016x}\n"
+ f" parent_span_id={parent_span_id:016x}\n"
+ f" is_root_span={is_root_span}"
+ )
+
+ return span, is_root_span
+
+ def _end_pipe_span_success(self, span: Span | None, pipe_output: PipeOutput, is_root_span: bool) -> None:
+ """End the pipe's OTel span with success status. Safe to call if span is None.
+
+ Args:
+ span: The OTel span to end, or None if telemetry is disabled.
+ pipe_output: The pipe output containing the result for telemetry capture.
+ is_root_span: Whether this is the root span of the trace.
+ """
+ if span is None:
+ return
+
+ span_ctx = span.get_span_context()
+ log.verbose(f"[OTel] PIPE SPAN ENDING:\n pipe_code='{self.code}'\n trace_id={span_ctx.trace_id:032x}\n span_id={span_ctx.span_id:016x}")
+
+ # Always capture full output content for Langfuse
+ if TelemetryManagerAbstract.get_langfuse_enabled():
+ output_json = OtelFactory.make_output_json(
+ pipe_output=pipe_output,
+ max_length=None, # No truncation for Langfuse
+ )
+ span.set_attribute(LangfuseSpanAttr.OBSERVATION_OUTPUT, output_json)
+
+ # For root span, also set trace-level output
+ if is_root_span:
+ span.set_attribute(LangfuseSpanAttr.TRACE_OUTPUT, output_json)
+
+ span.set_attribute(PipelexSpanAttr.OUTCOME, SpanOutcome.SUCCESS)
+ span.set_status(Status(StatusCode.OK))
+ if TelemetryManagerAbstract.get_langfuse_enabled():
+ span.set_attribute(LangfuseSpanAttr.OBSERVATION_OUTCOME, SpanOutcome.SUCCESS)
+ if is_root_span:
+ span.set_attribute(LangfuseSpanAttr.TRACE_OUTCOME, SpanOutcome.SUCCESS)
+ span.end()
+
+ def _end_pipe_span_error(self, span: Span | None, error: Exception, is_root_span: bool = False) -> None:
+ """End the pipe's OTel span with error status. Safe to call if span is None.
+
+ Args:
+ span: The OTel span to end, or None if telemetry is disabled.
+ error: The exception that caused the error.
+ is_root_span: Whether this is the root span of the trace.
+ """
+ if span is None:
+ return
+
+ span_ctx = span.get_span_context()
+ log.verbose(
+ f"[OTel] PIPE SPAN ENDING WITH ERROR:\n pipe_code='{self.code}'\n trace_id={span_ctx.trace_id:032x}\n span_id={span_ctx.span_id:016x}"
+ )
+
+ span.set_attribute(PipelexSpanAttr.OUTCOME, SpanOutcome.FAILURE)
+ span.record_exception(error)
+ span.set_status(Status(StatusCode.ERROR, str(error)))
+ if TelemetryManagerAbstract.get_langfuse_enabled():
+ span.set_attribute(LangfuseSpanAttr.OBSERVATION_OUTCOME, SpanOutcome.FAILURE)
+ if is_root_span:
+ span.set_attribute(LangfuseSpanAttr.TRACE_OUTCOME, SpanOutcome.FAILURE)
+ span.end()
+
@final
async def run_pipe(
self,
@@ -299,10 +486,7 @@ class PipeAbstract(ABC, BaseModel):
pipe_run_params.push_pipe_to_stack(pipe_code=self.code)
self.monitor_pipe_stack(pipe_run_params=pipe_run_params)
- updated_metadata = JobMetadata(
- pipe_job_ids=[self.code],
- )
- job_metadata.update(updated_metadata=updated_metadata)
+ # Check inputs ------------------------------------------------------------
# check we have the required inputs in the working memory
missing_inputs: dict[str, str] = {}
@@ -310,27 +494,80 @@ class PipeAbstract(ABC, BaseModel):
if not working_memory.is_stuff_exists(name=required_stuff_name):
missing_inputs[required_stuff_name] = requirement.concept.code
if missing_inputs:
- raise PipeRunInputsError(
+ error = PipeRunInputsError(
message=f"Missing required inputs for pipe '{self.code}': {missing_inputs}", pipe_code=self.code, missing_inputs=missing_inputs
)
+ raise error
pipe_run_info = self._format_pipe_run_info(pipe_run_params=pipe_run_params)
if pipe_run_params.run_mode == PipeRunMode.LIVE:
log.info(pipe_run_info)
- await self.validate_before_run(
- job_metadata=job_metadata, working_memory=working_memory, pipe_run_params=pipe_run_params, output_name=output_name
- )
+ # Handle telemetry ------------------------------------------------------------
- pipe_output = await self._run_pipe(
- job_metadata=job_metadata, working_memory=working_memory, pipe_run_params=pipe_run_params, output_name=output_name
- )
+ # Generate pipe_run_id (business ID, always set)
+ this_pipe_run_id = PipelineFactory.make_pipe_run_id()
+
+ # Derive OtelContext if telemetry is enabled (not dry mode and tracer available)
+ # The trace_id comes from parent's otel_context (already computed at pipeline start)
+ this_otel_context: OtelContext | None = None
+ span: Span | None = None
+ is_root_span: bool = False
+
+ parent_otel_context = job_metadata.otel_context
+ if not pipe_run_params.run_mode.is_dry and parent_otel_context is not None:
+ # Start OTel span first
+ span, is_root_span = self._start_pipe_span(
+ parent_otel_context=parent_otel_context,
+ pipeline_run_id=job_metadata.pipeline_run_id,
+ working_memory=working_memory,
+ )
+ # Get the actual span_id from OTel (OTel generates its own span_id)
+ if span:
+ span_context = span.get_span_context()
+ this_otel_context = OtelContext(
+ trace_id=parent_otel_context.trace_id,
+ trace_name=parent_otel_context.trace_name,
+ trace_name_redacted=parent_otel_context.trace_name_redacted,
+ span_id=span_context.span_id,
+ )
- await self.validate_after_run(
- job_metadata=job_metadata, working_memory=working_memory, pipe_run_params=pipe_run_params, output_name=output_name
+ # Create child metadata with updated pipe_code and pipe_run_id
+ # This passes down a modified copy rather than mutating the original
+ # otel_context is passed separately because it must always be set explicitly
+ # (even when None in dry mode) to avoid inheriting stale parent context
+ child_metadata = job_metadata.copy_with_update(
+ updated_metadata=JobMetadata(
+ pipe_code=self.code,
+ pipe_run_id=this_pipe_run_id,
+ ),
+ otel_context=this_otel_context,
)
+ # Run pipe ------------------------------------------------------------
+
+ try:
+ await self.validate_before_run(
+ job_metadata=child_metadata, working_memory=working_memory, pipe_run_params=pipe_run_params, output_name=output_name
+ )
+ pipe_output = await self._run_pipe(
+ job_metadata=child_metadata, working_memory=working_memory, pipe_run_params=pipe_run_params, output_name=output_name
+ )
+ await self.validate_after_run(
+ job_metadata=child_metadata, working_memory=working_memory, pipe_run_params=pipe_run_params, output_name=output_name
+ )
+ except Exception as exc:
+ self._end_pipe_span_error(span, error=exc, is_root_span=is_root_span)
+ raise
+
+ # Handle telemetry ------------------------------------------------------------
+
+ self._end_pipe_span_success(span=span, pipe_output=pipe_output, is_root_span=is_root_span)
+
+ # Cleanup ------------------------------------------------------------
+
pipe_run_params.pop_pipe_from_stack(pipe_code=self.code)
+
return pipe_output
diff --git a/pipelex/hub.py b/pipelex/hub.py
index 983363518..de493171b 100644
--- a/pipelex/hub.py
+++ b/pipelex/hub.py
@@ -3,6 +3,7 @@ from contextvars import ContextVar
from typing import ClassVar, Optional
from kajson.class_registry_abstract import ClassRegistryAbstract
+from opentelemetry.trace import Tracer as OTelTracer
from rich.console import Console
from pipelex import log
@@ -360,6 +361,10 @@ def get_telemetry_manager() -> TelemetryManagerAbstract:
return get_pipelex_hub().get_telemetry_manager()
+def get_otel_tracer() -> OTelTracer | None:
+ return get_telemetry_manager().get_otel_tracer()
+
+
# cogt
diff --git a/pipelex/kit/agent_rules/codex_commands.md b/pipelex/kit/agent_rules/codex_commands.md
index 244eb3592..d0b45a1ea 100644
--- a/pipelex/kit/agent_rules/codex_commands.md
+++ b/pipelex/kit/agent_rules/codex_commands.md
@@ -5,7 +5,7 @@
After making code changes, you must always lint using `make check`.
```bash
- make check
+ make format lint pyright mypy check-unused-imports check-config-sync check-rules pylint
# If the current system doesn't have the `make` command, lookup the "check" target in the Makefile and run the command manually.
```
@@ -13,6 +13,7 @@
- Pyright: Static type checking
- Ruff: Fast Python linter
- Mypy: Static type checker
+ - Other checks
Always fix any issues reported by these tools before proceeding.
diff --git a/pipelex/kit/agent_rules/pytest_standards.md b/pipelex/kit/agent_rules/pytest_standards.md
index 230a039c0..6834d125a 100644
--- a/pipelex/kit/agent_rules/pytest_standards.md
+++ b/pipelex/kit/agent_rules/pytest_standards.md
@@ -58,7 +58,6 @@ class TestFooBar:
- Never more than 1 class per test module.
- When testing one method, if possible, limit the number of test functions, but with different test cases in parameters
-- Sometimes it can be convenient to access the test's name in its body, for instance to include into a job_id. To achieve that, add the argument `request: FixtureRequest` into the signature and then you can get the test name using `cast(str, request.node.originalname), # type: ignore`.
### Test Data Organization
diff --git a/pipelex/kit/agent_rules/python_standards.md b/pipelex/kit/agent_rules/python_standards.md
index eba03917d..32c6fa9c3 100644
--- a/pipelex/kit/agent_rules/python_standards.md
+++ b/pipelex/kit/agent_rules/python_standards.md
@@ -12,6 +12,7 @@ This document outlines the core coding standards, best practices, and quality co
## Enums and tests
- When defining enums related to string values, always inherit from `StrEnum`
+ - When you need the enum value as a string, don't use `str(enum_var)` or `enum_var.value`, just use `enum_var` itself, that is the point of using StrEnum!
- Never test equality to an enum value: use match/case, even to single out 1 case out of 10 cases. To avoid heavy match/case code in awkward places, add methods to the enum class such as `is_foobar()`. This is to avoid bugs: when new enum values are added we want the linter to complain. Use the `|` operator to group cases
- As our match/case constructs over enums are always exhaustive, NEVER add a default `case _: ...`. Otherwise, you won't pass linting.
- `StrEnum` must be imported from `pipelex.types` (handles python retrocompatibility):
@@ -19,6 +20,10 @@ This document outlines the core coding standards, best practices, and quality co
from pipelex.types import StrEnum
```
+## Optionals
+
+- Don't write things like `a = b if b else c`, write `a = b or c` instead.
+
## Imports
### **Imports at the top of the file**
diff --git a/pipelex/kit/configs/inference/backends.toml b/pipelex/kit/configs/inference/backends.toml
index 2f002afc8..6191f4edd 100644
--- a/pipelex/kit/configs/inference/backends.toml
+++ b/pipelex/kit/configs/inference/backends.toml
@@ -10,16 +10,15 @@
#
####################################################################################################
-[pipelex_inference]
-display_name = "⭐ Pipelex Inference"
-enabled = true
-endpoint = "https://inference.pipelex.com/v1"
-api_key = "${PIPELEX_INFERENCE_API_KEY}"
+[pipelex_gateway]
+display_name = "⭐ Pipelex Gateway"
+enabled = true # Enable after accepting terms via `pipelex init config`
+api_key = "${PIPELEX_GATEWAY_API_KEY}"
[anthropic]
enabled = true
api_key = "${ANTHROPIC_API_KEY}"
-claude_4_tokens_limit = 8192
+valued_constraints = { max_output_tokens_limit = 8192 }
[azure_openai]
display_name = "Azure OpenAI"
@@ -69,6 +68,18 @@ display_name = "OpenAI"
enabled = true
api_key = "${OPENAI_API_KEY}"
+[portkey]
+display_name = "Portkey"
+enabled = true
+endpoint = "https://api.portkey.ai/v1"
+api_key = "${PORTKEY_API_KEY}"
+
+[scaleway]
+display_name = "Scaleway"
+enabled = true
+endpoint = "${SCALEWAY_ENDPOINT}"
+api_key = "${SCALEWAY_API_KEY}"
+
[vertexai]
display_name = "Google Vertex AI"
enabled = false # This is the only one we disable beacuse setting it up requires internet access just to get credentials so it fails in CI sandboxes
@@ -84,3 +95,10 @@ api_key = "${XAI_API_KEY}"
[internal] # software-only backend, runs internally, without AI
enabled = true
+
+# Deprecated
+[pipelex_inference]
+display_name = "🛑 Legacy Pipelex Inference"
+enabled = false
+endpoint = "https://inference.pipelex.com/v1"
+api_key = "${PIPELEX_INFERENCE_API_KEY}"
diff --git a/pipelex/kit/configs/inference/backends/anthropic.toml b/pipelex/kit/configs/inference/backends/anthropic.toml
index a3a485379..729e2d107 100644
--- a/pipelex/kit/configs/inference/backends/anthropic.toml
+++ b/pipelex/kit/configs/inference/backends/anthropic.toml
@@ -101,7 +101,7 @@ costs = { input = 1.0, output = 5.0 }
["claude-4.5-opus"]
model_id = "claude-opus-4-5-20251101"
-max_tokens = 32000
+max_tokens = 64000
inputs = ["text", "images"]
outputs = ["text", "structured"]
max_prompt_images = 100
diff --git a/pipelex/kit/configs/inference/backends/azure_openai.toml b/pipelex/kit/configs/inference/backends/azure_openai.toml
index ee04f7ad6..35ccb4820 100644
--- a/pipelex/kit/configs/inference/backends/azure_openai.toml
+++ b/pipelex/kit/configs/inference/backends/azure_openai.toml
@@ -22,9 +22,9 @@
[defaults]
model_type = "llm"
-sdk = "azure_openai"
+sdk = "azure_openai_responses"
prompting_target = "openai"
-structure_method = "instructor/openai_tools"
+structure_method = "instructor/openai_responses_tools"
################################################################################
# LANGUAGE MODELS
@@ -68,28 +68,28 @@ model_id = "o1-mini-2024-09-12"
inputs = ["text"]
outputs = ["text", "structured"]
costs = { input = 3.0, output = 12.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[o1]
model_id = "o1-2024-12-17"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 15.0, output = 60.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[o3-mini]
model_id = "o3-mini-2025-01-31"
inputs = ["text"]
outputs = ["text", "structured"]
costs = { input = 1.1, output = 4.4 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[o3]
model_id = "o3-2025-04-16"
inputs = ["text"]
outputs = ["text", "structured"]
costs = { input = 2, output = 8 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
# --- GPT-5 Series -------------------------------------------------------------
[gpt-5-mini]
@@ -97,28 +97,28 @@ model_id = "gpt-5-mini-2025-08-07"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 0.25, output = 2.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[gpt-5-nano]
model_id = "gpt-5-nano-2025-08-07"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 0.05, output = 0.4 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[gpt-5-chat]
model_id = "gpt-5-chat-2025-08-07"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 1.25, output = 10.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[gpt-5]
model_id = "gpt-5-2025-08-07"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 1.25, output = 10.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
# --- GPT-5.1 Series -------------------------------------------------------------
["gpt-5.1"]
@@ -126,14 +126,14 @@ model_id = "gpt-5.1-2025-11-13"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 1.25, output = 10.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
["gpt-5.1-chat"]
model_id = "gpt-5.1-chat-2025-11-13"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 1.25, output = 10.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
################################################################################
# IMAGE GENERATION MODELS
@@ -141,7 +141,7 @@ constraints = ["temperature_must_be_1"]
# --- OpenAI Image Generation --------------------------------------------------
[gpt-image-1]
-sdk = "azure_rest"
+sdk = "azure_rest_img_gen"
model_type = "img_gen"
model_id = "gpt-image-1-2025-04-15"
inputs = ["text"]
diff --git a/pipelex/kit/configs/inference/backends/blackboxai.toml b/pipelex/kit/configs/inference/backends/blackboxai.toml
index 405675b5c..e6cf9dde0 100644
--- a/pipelex/kit/configs/inference/backends/blackboxai.toml
+++ b/pipelex/kit/configs/inference/backends/blackboxai.toml
@@ -167,13 +167,13 @@ costs = { input = 0.06, output = 0.24 }
################################################################################
# --- DeepSeek Free Models -----------------------------------------------------
-[deepseek-chat-free]
+[deepseek-chat]
model_id = "blackboxai/deepseek/deepseek-chat:free"
inputs = ["text"]
outputs = ["text", "structured"]
costs = { input = 0.00, output = 0.00 }
-[deepseek-r1-free]
+[deepseek-r1]
model_id = "blackboxai/deepseek/deepseek-r1:free"
inputs = ["text"]
outputs = ["text", "structured"]
diff --git a/pipelex/kit/configs/inference/backends/groq.toml b/pipelex/kit/configs/inference/backends/groq.toml
index 72fc0b804..72bdae3fc 100644
--- a/pipelex/kit/configs/inference/backends/groq.toml
+++ b/pipelex/kit/configs/inference/backends/groq.toml
@@ -46,7 +46,7 @@ outputs = ["text", "structured"]
costs = { input = 0.59, output = 0.79 }
# --- Meta Llama Guard ---------------------------------------------------------
-["meta-llama/llama-guard-4-12b"]
+[llama-guard-4-12b]
model_id = "meta-llama/llama-guard-4-12b"
max_tokens = 1024
inputs = ["text"]
@@ -54,14 +54,14 @@ outputs = ["text", "structured"]
costs = { input = 0.20, output = 0.20 }
# --- OpenAI GPT-OSS Models ----------------------------------------------------
-["openai/gpt-oss-20b"]
+[gpt-oss-20b]
model_id = "openai/gpt-oss-20b"
max_tokens = 65536
inputs = ["text"]
outputs = ["text", "structured"]
costs = { input = 0.075, output = 0.30 }
-["openai/gpt-oss-120b"]
+[gpt-oss-120b]
model_id = "openai/gpt-oss-120b"
max_tokens = 65536
inputs = ["text"]
@@ -88,7 +88,7 @@ costs = { input = 0.10, output = 0.30 }
################################################################################
# --- Meta Llama 4 Vision Models (Preview) -------------------------------------
-["meta-llama/llama-4-scout-17b-16e-instruct"]
+[llama-4-scout-17b-16e-instruct]
model_id = "meta-llama/llama-4-scout-17b-16e-instruct"
max_tokens = 8192
inputs = ["text", "images"]
@@ -96,7 +96,7 @@ outputs = ["text", "structured"]
max_prompt_images = 5
costs = { input = 0.11, output = 0.34 }
-["meta-llama/llama-4-maverick-17b-128e-instruct"]
+[llama-4-maverick-17b-128e-instruct]
model_id = "meta-llama/llama-4-maverick-17b-128e-instruct"
max_tokens = 8192
inputs = ["text", "images"]
@@ -105,7 +105,7 @@ max_prompt_images = 5
costs = { input = 0.20, output = 0.60 }
# --- Moonshot Kimi K2 ---------------------------------------------------------
-["moonshotai/kimi-k2-instruct-0905"]
+[kimi-k2-instruct-0905]
model_id = "moonshotai/kimi-k2-instruct-0905"
max_tokens = 16384
inputs = ["text"]
@@ -113,7 +113,7 @@ outputs = ["text", "structured"]
costs = { input = 1.00, output = 3.00 }
# --- OpenAI Safety Model ------------------------------------------------------
-["openai/gpt-oss-safeguard-20b"]
+[gpt-oss-safeguard-20b]
model_id = "openai/gpt-oss-safeguard-20b"
max_tokens = 65536
inputs = ["text"]
@@ -121,7 +121,7 @@ outputs = ["text", "structured"]
costs = { input = 0.075, output = 0.30 }
# --- Qwen 3 -------------------------------------------------------------------
-["qwen/qwen3-32b"]
+[qwen3-32b]
model_id = "qwen/qwen3-32b"
max_tokens = 40960
inputs = ["text"]
diff --git a/pipelex/kit/configs/inference/backends/openai.toml b/pipelex/kit/configs/inference/backends/openai.toml
index 7fcf0afed..bfb3dd9ff 100644
--- a/pipelex/kit/configs/inference/backends/openai.toml
+++ b/pipelex/kit/configs/inference/backends/openai.toml
@@ -22,9 +22,9 @@
[defaults]
model_type = "llm"
-sdk = "openai"
+sdk = "openai_responses"
prompting_target = "openai"
-structure_method = "instructor/openai_tools"
+structure_method = "instructor/openai_responses_tools"
################################################################################
# LANGUAGE MODELS
@@ -93,40 +93,33 @@ outputs = ["text", "structured"]
costs = { input = 0.1, output = 0.4 }
# --- o Series ----------------------------------------------------------------
-[o1-mini]
-model_id = "o1-mini"
-inputs = ["text"]
-outputs = ["text"]
-costs = { input = 3.0, output = 12.0 }
-constraints = ["temperature_must_be_1"]
-
[o1]
model_id = "o1"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 15.0, output = 60.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[o3-mini]
model_id = "o3-mini"
inputs = ["text"]
outputs = ["text", "structured"]
costs = { input = 1.1, output = 4.4 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[o3]
model_id = "o3"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 10.0, output = 40.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[o4-mini]
model_id = "o4-mini"
inputs = ["text"]
outputs = ["text", "structured"]
costs = { input = 1.1, output = 4.4 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
# --- GPT-5 Series -------------------------------------------------------------
[gpt-5]
@@ -134,28 +127,28 @@ model_id = "gpt-5"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 1.25, output = 10.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[gpt-5-mini]
model_id = "gpt-5-mini"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 0.25, output = 2.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[gpt-5-nano]
model_id = "gpt-5-nano"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 0.05, output = 0.4 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
[gpt-5-chat]
model_id = "gpt-5-chat-latest"
inputs = ["text", "images"]
outputs = ["text"]
costs = { input = 1.25, output = 10.0 }
-constraints = ["temperature_must_be_1"]
+valued_constraints = { fixed_temperature = 1 }
# --- GPT-5.1 Series -------------------------------------------------------------
["gpt-5.1"]
@@ -170,6 +163,7 @@ costs = { input = 1.25, output = 10.0 }
# --- OpenAI Image Generation --------------------------------------------------
[gpt-image-1]
+sdk = "openai_img_gen"
model_type = "img_gen"
model_id = "gpt-image-1"
inputs = ["text"]
diff --git a/pipelex/kit/configs/inference/backends/pipelex_gateway.toml b/pipelex/kit/configs/inference/backends/pipelex_gateway.toml
new file mode 100644
index 000000000..bca075b7c
--- /dev/null
+++ b/pipelex/kit/configs/inference/backends/pipelex_gateway.toml
@@ -0,0 +1,41 @@
+################################################################################
+# Pipelex Gateway Local Overrides
+################################################################################
+#
+# TELEMETRY NOTICE:
+#
+# Using Pipelex Gateway enables identified telemetry tied to your API key
+# (hashed for security). This is independent from your telemetry.toml settings.
+#
+# We collect only technical data (model names, token counts, latency, error rates).
+# We do NOT collect prompts, completions, pipe codes, or business data.
+#
+# This allows us to monitor service quality, enforce fair usage, and support you.
+#
+################################################################################
+#
+# WARNING: USE AT YOUR OWN RISK!
+#
+# The actual model configuration is fetched remotely from Pipelex servers.
+# Any override in this file may cause unexpected behavior or failures,
+# as the remote configuration may change at any time.
+#
+# If you must override, you may ONLY use these keys per model:
+# - sdk
+# - structure_method
+#
+# All other keys will be ignored.
+#
+# If you need custom configurations, consider using your own API keys
+# with direct provider backends (openai, anthropic, etc.) instead.
+#
+# Documentation:
+# https://docs.pipelex.com/home/7-configuration/config-technical/inference-backend-config/
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+# Per-model overrides example:
+# [gpt-4o]
+# sdk = "gateway_completions"
+# structure_method = "instructor/openai_tools"
diff --git a/pipelex/kit/configs/inference/backends/pipelex_inference.toml b/pipelex/kit/configs/inference/backends/pipelex_inference.toml
index a7dbdfbc3..751c57021 100644
--- a/pipelex/kit/configs/inference/backends/pipelex_inference.toml
+++ b/pipelex/kit/configs/inference/backends/pipelex_inference.toml
@@ -36,66 +36,88 @@ model_id = "pipelex/gpt-4o"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 2.75, output = 11.00 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
[gpt-4o-mini]
model_id = "pipelex/gpt-4o-mini"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 0.17, output = 0.66 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
["gpt-4.1"]
model_id = "pipelex/gpt-4.1"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 2, output = 8 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
["gpt-4.1-mini"]
model_id = "pipelex/gpt-4.1-mini"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 0.4, output = 1.6 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
["gpt-4.1-nano"]
model_id = "pipelex/gpt-4.1-nano"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 0.1, output = 0.4 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
[gpt-5-nano]
model_id = "pipelex/gpt-5-nano"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 0.05, output = 0.40 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
[gpt-5-mini]
model_id = "pipelex/gpt-5-mini"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 0.25, output = 2.00 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
[gpt-5-chat]
model_id = "pipelex/gpt-5-chat"
inputs = ["text", "images"]
outputs = ["text"]
costs = { input = 1.25, output = 10.00 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
[gpt-5]
model_id = "pipelex/gpt-5"
inputs = ["text", "images"]
outputs = ["text"]
costs = { input = 1.25, output = 10.00 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
["gpt-5.1"]
model_id = "pipelex/gpt-5.1"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 1.25, output = 10.00 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
["gpt-5.1-chat"]
model_id = "pipelex/gpt-5.1-chat"
inputs = ["text", "images"]
outputs = ["text", "structured"]
costs = { input = 1.25, output = 10.00 }
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
# --- Claude LLMs --------------------------------------------------------------
["claude-4-sonnet"]
diff --git a/pipelex/kit/configs/inference/backends/portkey.toml b/pipelex/kit/configs/inference/backends/portkey.toml
new file mode 100644
index 000000000..2080d0e14
--- /dev/null
+++ b/pipelex/kit/configs/inference/backends/portkey.toml
@@ -0,0 +1,272 @@
+################################################################################
+# Portkey Configuration
+################################################################################
+#
+# This file defines the model specifications for the Portkey backend.
+# It contains model definitions for various AI models.
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots must be quoted (e.g., ["gpt-4.1"])
+# - Model costs are in USD per million tokens (input/output)
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "llm"
+sdk = "portkey_completions"
+structure_method = "instructor/openai_tools"
+prompting_target = "anthropic"
+
+################################################################################
+# LANGUAGE MODELS
+################################################################################
+
+# --- OpenAI LLMs --------------------------------------------------------------
+[gpt-4o-mini]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.6 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+[gpt-4o]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 2.5, output = 10.0 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+["gpt-4.1-nano"]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.1, output = 0.4 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+["gpt-4.1-mini"]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.4, output = 1.6 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+["gpt-4.1"]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 2, output = 8 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+[o1]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 15.0, output = 60.0 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+[o3-mini]
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 1.1, output = 4.4 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+[o3]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 2, output = 8 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+[o4-mini]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.1, output = 4.4 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+[gpt-5-nano]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.05, output = 0.4 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+[gpt-5-mini]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.25, output = 2.0 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+[gpt-5]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10.0 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+["gpt-5.1"]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10.0 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+["gpt-5.1-codex"]
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10.0 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+x-portkey-provider = "@openai"
+
+# --- Claude LLMs --------------------------------------------------------------
+[claude-3-haiku]
+model_id = "claude-3-haiku-20240307"
+max_tokens = 4096
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 0.25, output = 1.25 }
+x-portkey-provider = "@anthropic"
+
+[claude-3-opus]
+model_id = "claude-3-opus-20240229"
+max_tokens = 4096
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 15.0, output = 75.0 }
+x-portkey-provider = "@anthropic"
+
+["claude-3.7-sonnet"]
+model_id = "claude-3-7-sonnet-20250219"
+max_tokens = 8192
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+x-portkey-provider = "@anthropic"
+
+[claude-4-sonnet]
+model_id = "claude-sonnet-4-20250514"
+max_tokens = 64000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+x-portkey-provider = "@anthropic"
+
+[claude-4-opus]
+model_id = "claude-opus-4-20250514"
+max_tokens = 32000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+x-portkey-provider = "@anthropic"
+
+["claude-4.1-opus"]
+model_id = "claude-opus-4-1-20250805"
+max_tokens = 32000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+x-portkey-provider = "@anthropic"
+
+["claude-4.5-sonnet"]
+model_id = "claude-sonnet-4-5-20250929"
+max_tokens = 64000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+x-portkey-provider = "@anthropic"
+
+["claude-4.5-haiku"]
+model_id = "claude-haiku-4-5-20251001"
+max_tokens = 64000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 1.0, output = 5.0 }
+x-portkey-provider = "@anthropic"
+
+["claude-4.5-opus"]
+model_id = "claude-opus-4-5-20251101"
+max_tokens = 64000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 5.0, output = 25.0 }
+x-portkey-provider = "@anthropic"
+
+# --- Gemini LLMs --------------------------------------------------------------
+["gemini-2.0-flash"]
+model_id = "gemini-2.0-flash"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.10, output = 0.40 }
+x-portkey-provider = "@google"
+
+["gemini-2.5-pro"]
+model_id = "gemini-2.5-pro"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 3000
+costs = { input = 1.25, output = 10.0 }
+x-portkey-provider = "@google"
+
+["gemini-2.5-flash"]
+model_id = "gemini-2.5-flash"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.30, output = 2.50 }
+x-portkey-provider = "@google"
+
+["gemini-2.5-flash-lite"]
+model_id = "gemini-2.5-flash-lite"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.10, output = 0.40 }
+x-portkey-provider = "@google"
+
+["gemini-3.0-pro"]
+model_id = "gemini-3-pro-preview"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 3000
+costs = { input = 2, output = 12.0 }
+x-portkey-provider = "@google"
diff --git a/pipelex/kit/configs/inference/backends/scaleway.toml b/pipelex/kit/configs/inference/backends/scaleway.toml
new file mode 100644
index 000000000..20fe79205
--- /dev/null
+++ b/pipelex/kit/configs/inference/backends/scaleway.toml
@@ -0,0 +1,67 @@
+################################################################################
+# Groq Backend Configuration
+################################################################################
+#
+# This file defines the model specifications for Scaleway models.
+# It contains model definitions for various LLM models accessible through
+# the Groq API, including text-only and vision-capable models.
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots or slashes must be quoted (e.g., ["meta-llama/llama-4-scout"])
+# - Model costs are in USD per million tokens (input/output)
+# - Vision models support max 5 images per request, 33MP max resolution
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "llm"
+sdk = "openai"
+structure_method = "instructor/json"
+
+# --- DeepSeek Models ----------------------------------------------------------
+[deepseek-r1-distill-llama-70b]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.90, output = 0.90 }
+
+# --- Meta Llama 3.x Series ----------------------------------------------------
+["llama-3.1-8b-instruct"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.2, output = 0.2 }
+
+["llama-3.3-70b-instruct"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.90, output = 0.90 }
+
+# --- OpenAI GPT-OSS Models ----------------------------------------------------
+[gpt-oss-120b]
+max_tokens = 65536
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.60 }
+
+# --- Qwen 3 -------------------------------------------------------------------
+[qwen3-235b-a22b-instruct-2507]
+max_tokens = 40960
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.75, output = 2.25 }
+
+[qwen3-coder-30b-a3b-instruct]
+max_tokens = 40960
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.20, output = 0.80 }
diff --git a/pipelex/kit/configs/inference/deck/base_deck.toml b/pipelex/kit/configs/inference/deck/base_deck.toml
index 954a65d57..6fb0161d6 100644
--- a/pipelex/kit/configs/inference/deck/base_deck.toml
+++ b/pipelex/kit/configs/inference/deck/base_deck.toml
@@ -22,16 +22,16 @@ base-gpt = "gpt-4o"
base-gemini = "gemini-2.5-flash"
base-mistral = "mistral-medium"
base-groq = "llama-3.3-70b-versatile"
+base-grok = "grok-4-fast-non-reasoning"
-best-gpt = "gpt-4o"
-best-claude = "claude-4.1-opus"
-best-gemini = "gemini-2.5-pro"
+best-gpt = "gpt-5.1"
+best-claude = "claude-4.5-opus"
+best-gemini = "gemini-3.0-pro"
best-mistral = "mistral-medium"
-best-grok = "grok-3"
# Groq-specific aliases
fast-groq = "llama-3.1-8b-instant"
-vision-groq = "meta-llama/llama-4-scout-17b-16e-instruct"
+vision-groq = "llama-4-scout-17b-16e-instruct"
# Image generation aliases
base-img-gen = "flux-pro/v1.1"
@@ -43,35 +43,49 @@ fast-img-gen = "fast-lightning-sdxl"
####################################################################################################
[waterfalls]
+
+# --- Waterfalls for LLMs ---------------------------------------------------------------------
smart_llm = [
+ "claude-4.5-opus",
"claude-4.5-sonnet",
+ "gemini-3.0-pro",
+ "gpt-5.1",
"claude-4.1-opus",
- "claude-4-sonnet",
"gemini-2.5-pro",
- "gpt-4o", # we're using gpt-4o here rather than gpt-5 until we'll handle reasoning parameters
- "grok-3",
+ "claude-4-sonnet",
+ "grok-4",
]
smart_llm_with_vision = [
+ "claude-4.5-opus",
"claude-4.5-sonnet",
+ "gemini-3.0-pro",
+ "gpt-5.1",
"claude-4.1-opus",
- "claude-4-sonnet",
"gemini-2.5-pro",
- "gpt-4o", # we use gpt-4o here rather than gpt-5 until we handle reasoning parameters
- "grok-3",
+ "claude-4-sonnet",
+ "grok-4",
]
smart_llm_for_structured = [
+ "claude-4.5-opus",
"claude-4.5-sonnet",
+ "gemini-3.0-pro",
+ "gpt-5.1",
"claude-4.1-opus",
"claude-4-sonnet",
- "gpt-4o", # we use gpt-4o here rather than gpt-5 until we handle reasoning parameters
]
-llm_for_creativity = ["claude-4.1-opus", "gemini-2.5-pro", "gpt-4o"]
+llm_for_creativity = [
+ "claude-4.5-opus",
+ "claude-4.1-opus",
+ "gemini-2.5-pro",
+ "gpt-5.1",
+]
llm_for_large_codebase = [
"gemini-2.5-pro",
"claude-4.5-sonnet",
- "gpt-4o", # we use gpt-4o here rather than gpt-5 until we handle reasoning parameters
+ "gemini-3.0-pro",
+ "gpt-5.1",
"gemini-2.5-flash",
- "grok-3",
+ "grok-4",
]
cheap_llm = [
"gpt-4o-mini",
@@ -93,6 +107,10 @@ cheap_llm_for_creativity = [
"claude-4.5-haiku",
]
+# --- Waterfalls for Extracts ---------------------------------------------------------------------
+pdf_text_extractor = ["mistral-ocr", "pypdfium2-extract-text"]
+image_text_extractor = ["mistral-ocr"]
+
####################################################################################################
# LLM Presets
####################################################################################################
@@ -119,7 +137,7 @@ llm_to_analyze_large_codebase = { model = "base-claude", temperature = 0.1 }
# Vision skills
llm_for_img_to_text_cheap = { model = "gpt-4o-mini", temperature = 0.1 }
llm_for_img_to_text = { model = "base-claude", temperature = 0.1 }
-llm_for_diagram_to_text = { model = "base-claude", temperature = 0.3 }
+llm_for_diagram_to_text = { model = "best-claude", temperature = 0.3 }
llm_for_table_to_text = { model = "base-claude", temperature = 0.3 }
# Image generation prompting skills
diff --git a/pipelex/kit/configs/inference/routing_profiles.toml b/pipelex/kit/configs/inference/routing_profiles.toml
index 0910ff285..b3733ae23 100644
--- a/pipelex/kit/configs/inference/routing_profiles.toml
+++ b/pipelex/kit/configs/inference/routing_profiles.toml
@@ -9,27 +9,29 @@
# =========================================================================================
# Which profile to use (change this to switch routing)
-active = "pipelex_first"
+# TODO: TBD
+active = "pipelex_gateway_first" # Change to "pipelex_gateway_first" after enabling gateway
-# We recommend using the "pipelex_first" profile to get a head start with all models.
-# The Pipelex Inference backend is currently not recommended for production use,
-# but it's great for development and testing.
-# To use the Pipelex Inference backend (pipelex_first profile):
+# We recommend using the "pipelex_gateway_first" profile to get a head start with all models.
+# To use the Pipelex Gateway backend:
# 1. Join our Discord community to get your free API key (no credit card required):
# Visit https://go.pipelex.com/discord and request your key in the appropriate channel
-# 2. Set the environment variable: export PIPELEX_INFERENCE_API_KEY="your-api-key"
-# 3. The .pipelex/inference/backends.toml is already configured with api_key = "${PIPELEX_INFERENCE_API_KEY}"
-# which will get the key from the environment variable.
+# 2. Set the environment variable (or add it to your .env file):
+# - Linux/macOS: export PIPELEX_GATEWAY_API_KEY="your-api-key"
+# - Windows CMD: set PIPELEX_GATEWAY_API_KEY=your-api-key
+# - Windows PowerShell: $env:PIPELEX_GATEWAY_API_KEY="your-api-key"
+# 3. The .pipelex/inference/backends.toml is already configured with api_key = "${PIPELEX_GATEWAY_API_KEY}"
+# which will get the key from the environment variable.
# =========================================================================================
# Routing Profiles
# =========================================================================================
-[profiles.pipelex_first]
-description = "Use Pipelex Inference backend for all its supported models"
-default = "pipelex_inference"
+[profiles.pipelex_gateway_first]
+description = "Use Pipelex Gateway backend for all its supported models"
+default = "pipelex_gateway"
fallback_order = [
- "pipelex_inference",
+ "pipelex_gateway",
"azure_openai",
"bedrock",
"blackboxai",
@@ -37,19 +39,23 @@ fallback_order = [
"fal",
]
-[profiles.pipelex_first.routes]
+[profiles.pipelex_gateway_first.routes]
# Pattern matching: "model-pattern" = "backend-name"
-"gpt-*" = "pipelex_inference"
-"claude-*" = "pipelex_inference"
-"grok-*" = "pipelex_inference"
-"gemini-*" = "pipelex_inference"
+"gpt-*" = "pipelex_gateway"
+"claude-*" = "pipelex_gateway"
+"grok-*" = "pipelex_gateway"
+"gemini-*" = "pipelex_gateway"
-[profiles.pipelex_first.optional_routes] # Each optional route is considered only if its backend is available
+[profiles.pipelex_gateway_first.optional_routes] # Each optional route is considered only if its backend is available
"*-sdxl" = "fal"
"flux-*" = "fal"
"gpt-image-1" = "openai"
"mistral-ocr" = "mistral"
+[profiles.all_pipelex_gateway]
+description = "Use Pipelex Gateway for all its supported models"
+default = "pipelex_gateway"
+
[profiles.all_anthropic]
description = "Use Anthropic backend for all its supported models"
default = "anthropic"
@@ -90,14 +96,22 @@ default = "ollama"
description = "Use OpenAI backend for all its supported models"
default = "openai"
-[profiles.all_pipelex_inference]
-description = "Use Pipelex Inference backend for all its supported models"
-default = "pipelex_inference"
+[profiles.all_portkey]
+description = "Use Portkey backend for all its supported models"
+default = "portkey"
+
+[profiles.all_scaleway]
+description = "Use Scaleway backend for all its supported models"
+default = "scaleway"
[profiles.all_xai]
description = "Use xAI backend for all its supported models"
default = "xai"
+[profiles.all_internal]
+description = "Use internal backend for all its supported models"
+default = "internal"
+
# =========================================================================================
# Custom Profiles
# =========================================================================================
diff --git a/pipelex/kit/configs/pipelex.toml b/pipelex/kit/configs/pipelex.toml
index 9e4f9cbb6..955152085 100644
--- a/pipelex/kit/configs/pipelex.toml
+++ b/pipelex/kit/configs/pipelex.toml
@@ -67,6 +67,13 @@ pipelex = "INFO"
# Uncomment to change the reaction to missing presets: "raise" (default), "log" or "none"
# missing_presets_reaction = "raise"
+[cogt.tenacity_config]
+# Uncomment to change those values as needed
+# max_retries = 50 # Maximum number of retry attempts before giving up
+# wait_multiplier = 0.2 # Multiplier applied to the wait time between retries (in seconds)
+# wait_max = 20 # Maximum wait time between retries (in seconds)
+# wait_exp_base = 1.3 # Base for exponential backoff calculation
+
[cogt.llm_config]
# Uncomment any of these to enable dumping the inputs or outputs of text-genration with an LLM
# is_dump_text_prompts_enabled = true
diff --git a/pipelex/kit/configs/pipelex_service.toml b/pipelex/kit/configs/pipelex_service.toml
new file mode 100644
index 000000000..de17e2380
--- /dev/null
+++ b/pipelex/kit/configs/pipelex_service.toml
@@ -0,0 +1,19 @@
+####################################################################################################
+# Pipelex Service Configuration
+####################################################################################################
+#
+# This file stores settings related to Pipelex managed services.
+# Currently used for Pipelex Gateway terms acceptance.
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+####################################################################################################
+
+[agreement]
+# Set to true after accepting Pipelex terms of service.
+terms_accepted = false
+
+# Note: when using pipelex_gateway, telemetry is enabled to monitor service usage.
+# We collect technical data (model, pipe type...) and quantitative data (token counts...)
+# but NOT your content, pipe codes, or output class names.
diff --git a/pipelex/kit/configs/telemetry.toml b/pipelex/kit/configs/telemetry.toml
index af98b57e8..75207a7c8 100644
--- a/pipelex/kit/configs/telemetry.toml
+++ b/pipelex/kit/configs/telemetry.toml
@@ -1,21 +1,84 @@
####################################################################################################
-# Pipelex Telemetry Configuration
+# Custom Telemetry Configuration
####################################################################################################
#
-# This file controls telemetry settings for Pipelex usage analytics.
-# Telemetry helps us improve Pipelex by understanding how it's used.
+# This file controls YOUR custom telemetry settings for observability and analytics.
+# Configure your own PostHog, Langfuse, or OTLP-compatible backends here.
+#
+# NOTE: When using Pipelex Gateway, identified telemetry is automatically enabled
+# (tied to your Gateway API key, hashed for security). This allows us to monitor
+# service quality, enforce fair usage, and provide you with better support.
+# Gateway telemetry operates independently from your settings below - you can have both!
+#
+# To disable all telemetry, set the DO_NOT_TRACK=1 environment variable.
#
# Documentation: https://docs.pipelex.com
# Support: https://go.pipelex.com/discord
#
####################################################################################################
-telemetry_mode = "anonymous" # Values: "off" | "anonymous" | "identified"
-host = "https://eu.i.posthog.com"
-project_api_key = "phc_HPJnNKpIXh0SxNDYyTAyUtnq9KxNNZJWQszynsWVx4Y"
-respect_dnt = true
-redact = ["prompt", "system_prompt", "response", "file_path", "url"]
-geoip_enabled = true
-dry_mode_enabled = false
-verbose_enabled = false
-user_id = ""
+# ──────────────────────────────────────────────────────────────────────────────
+# PostHog Configuration (Event tracking + AI span tracing)
+# ──────────────────────────────────────────────────────────────────────────────
+
+[posthog]
+mode = "off" # Values: "off" | "anonymous" | "identified"
+# user_id = "your_user_id" # Required when mode = "identified"
+endpoint = "${POSTHOG_ENDPOINT}" # Default: https://us.i.posthog.com (or https://eu.i.posthog.com for EU)
+api_key = "${POSTHOG_API_KEY}" # Get from PostHog Project Settings
+geoip = true # Enable GeoIP lookup
+debug = false # Enable PostHog debug mode
+redact_properties = [
+ "prompt",
+ "system_prompt",
+ "response",
+ "file_path",
+ "url",
+] # Event properties to redact
+
+# AI span tracing to YOUR PostHog (does NOT affect Langfuse/OTLP - they receive full data)
+[posthog.tracing]
+enabled = false # Send AI spans to your PostHog
+
+# Privacy controls for data sent to YOUR PostHog only
+[posthog.tracing.capture]
+content = false # Capture prompt/completion content
+# content_max_length = 1000 # Max length for captured content (omit for unlimited)
+pipe_codes = false # Include pipe codes in span names/attributes
+output_class_names = false # Include output class names in span names/attributes
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Langfuse Integration
+# Note: Langfuse receives FULL span data (no redaction)
+# ──────────────────────────────────────────────────────────────────────────────
+
+[langfuse]
+enabled = false
+# endpoint = "https://cloud.langfuse.com" # Override for self-hosted Langfuse
+# public_key = "${LANGFUSE_PUBLIC_KEY}" # Langfuse public key
+# secret_key = "${LANGFUSE_SECRET_KEY}" # Langfuse secret key
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Additional OTLP Exporters (array for multiple)
+# Note: OTLP exporters receive FULL span data (no redaction)
+# ──────────────────────────────────────────────────────────────────────────────
+
+# [[otlp]]
+# name = "my-collector" # Identifier for logging
+# endpoint = "https://..." # OTLP endpoint URL
+# headers = { Authorization = "Bearer ${OTLP_AUTH_TOKEN}" } # Headers for OTLP export
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Custom Telemetry Allowed Modes
+# Controls which integration modes can use custom telemetry settings above.
+# ──────────────────────────────────────────────────────────────────────────────
+
+[custom_telemetry_allowed_modes]
+ci = false # CI environments don't use custom telemetry
+cli = true # CLI usage allows custom telemetry
+docker = true # Docker deployments allow custom telemetry
+fastapi = true # FastAPI integrations allow custom telemetry
+mcp = true # MCP integrations allow custom telemetry
+n8n = true # n8n integrations allow custom telemetry
+pytest = false # Tests don't use custom telemetry
+python = false # Direct Python SDK usage doesn't use custom telemetry by default
diff --git a/pipelex/pipe_operators/llm/pipe_llm.py b/pipelex/pipe_operators/llm/pipe_llm.py
index 316c46169..5c9ae5f54 100644
--- a/pipelex/pipe_operators/llm/pipe_llm.py
+++ b/pipelex/pipe_operators/llm/pipe_llm.py
@@ -227,7 +227,7 @@ class PipeLLM(PipeOperator[PipeLLMOutput]):
)
except LLMCompletionError as exc:
location = self._format_error_location(pipe_run_params=pipe_run_params)
- error_details = self._format_llm_error(exc)
+ error_details = self._format_llm_error(exc=exc, settings=[llm_setting_main])
msg = f"Error generating text with LLM {location}: {error_details}"
raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode) from exc
@@ -353,7 +353,7 @@ class PipeLLM(PipeOperator[PipeLLMOutput]):
)
except LLMCompletionError as exc:
location = self._format_error_location(pipe_run_params=pipe_run_params)
- error_details = self._format_llm_error(exc)
+ error_details = self._format_llm_error(exc=exc, settings=[llm_setting_main, llm_setting_for_object])
msg = f"Error generating list of objects with text then object {location}: {error_details}"
raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode) from exc
else:
@@ -370,7 +370,7 @@ class PipeLLM(PipeOperator[PipeLLMOutput]):
)
except LLMCompletionError as exc:
location = self._format_error_location(pipe_run_params=pipe_run_params)
- error_details = self._format_llm_error(exc)
+ error_details = self._format_llm_error(exc=exc, settings=[llm_setting_for_object])
msg = f"Error generating list of objects with direct method {location}: {error_details}"
raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode) from exc
@@ -395,7 +395,7 @@ class PipeLLM(PipeOperator[PipeLLMOutput]):
)
except LLMCompletionError as exc:
location = self._format_error_location(pipe_run_params=pipe_run_params)
- error_details = self._format_llm_error(exc)
+ error_details = self._format_llm_error(exc=exc, settings=[llm_setting_main, llm_setting_for_object])
msg = f"Error generating single object with text then object {location}: {error_details}"
raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode) from exc
else:
@@ -411,7 +411,7 @@ class PipeLLM(PipeOperator[PipeLLMOutput]):
)
except LLMCompletionError as exc:
location = self._format_error_location(pipe_run_params=pipe_run_params)
- error_details = self._format_llm_error(exc)
+ error_details = self._format_llm_error(exc=exc, settings=[llm_setting_for_object])
msg = f"Error generating single object with direct method {location}: {error_details}"
raise PipeRunError(message=msg, run_mode=pipe_run_params.run_mode) from exc
the_content = generated_object
@@ -421,16 +421,16 @@ class PipeLLM(PipeOperator[PipeLLMOutput]):
def _format_error_location(self, pipe_run_params: PipeRunParams) -> str:
return f"in pipe '{pipe_run_params.pipe_stack_str}'"
- def _format_llm_error(self, exc: LLMCompletionError) -> str:
+ def _format_llm_error(self, exc: LLMCompletionError, settings: list[LLMSetting]) -> str:
"""Format an LLMCompletionError, extracting and formatting any ValidationError in the chain."""
error_details = str(exc)
current_exc: BaseException | None = exc
while current_exc is not None:
if isinstance(current_exc, ValidationError):
- error_details = format_pydantic_validation_error(current_exc)
+ error_details += f"\n{format_pydantic_validation_error(current_exc)}"
break
current_exc = current_exc.__cause__
- return error_details
+ return f"{error_details}\nLLM settings: {settings}"
@override
async def _dry_run_operator_pipe(
diff --git a/pipelex/pipe_run/dry_run.py b/pipelex/pipe_run/dry_run.py
index 2b3bb1ec2..125c9eddd 100644
--- a/pipelex/pipe_run/dry_run.py
+++ b/pipelex/pipe_run/dry_run.py
@@ -47,7 +47,7 @@ async def dry_run_pipe(pipe: PipeAbstract, raise_on_failure: bool = False) -> Dr
working_memory = WorkingMemoryFactory.make_for_dry_run(needed_inputs=needed_inputs_for_factory)
pipe.validate_with_libraries()
await pipe.run_pipe(
- job_metadata=JobMetadata(job_name=f"dry_run_{pipe.code}"),
+ job_metadata=JobMetadata(),
working_memory=working_memory,
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=PipeRunMode.DRY),
)
diff --git a/pipelex/pipe_run/pipe_run_mode.py b/pipelex/pipe_run/pipe_run_mode.py
index 5df56666a..9a701b17c 100644
--- a/pipelex/pipe_run/pipe_run_mode.py
+++ b/pipelex/pipe_run/pipe_run_mode.py
@@ -14,3 +14,11 @@ class PipeRunMode(StrEnum):
return True
case PipeRunMode.LIVE:
return False
+
+ @property
+ def is_live(self) -> bool:
+ match self:
+ case PipeRunMode.LIVE:
+ return True
+ case PipeRunMode.DRY:
+ return False
diff --git a/pipelex/pipelex.py b/pipelex/pipelex.py
index 0f736eddb..75cf4c7fb 100644
--- a/pipelex/pipelex.py
+++ b/pipelex/pipelex.py
@@ -1,10 +1,9 @@
-import os
-from typing import Any, cast
+import types
+from typing import TYPE_CHECKING, Any, cast
from kajson.class_registry import ClassRegistry
from kajson.class_registry_abstract import ClassRegistryAbstract
from kajson.kajson_manager import KajsonManager
-from kajson.singleton import MetaSingleton
from pydantic import ValidationError
from pipelex import log
@@ -23,6 +22,9 @@ from pipelex.cogt.exceptions import (
RoutingProfileLibraryNotFoundError,
)
from pipelex.cogt.inference.inference_manager import InferenceManager
+from pipelex.cogt.model_backends.backend_credentials import (
+ BackendCredentialsErrorMsgFactory,
+)
from pipelex.cogt.models.model_manager import ModelManager
from pipelex.cogt.models.model_manager_abstract import ModelManagerAbstract
from pipelex.config import get_config
@@ -48,32 +50,38 @@ from pipelex.reporting.reporting_protocol import ReportingNoOp, ReportingProtoco
from pipelex.system.configuration.config_loader import config_manager
from pipelex.system.configuration.config_root import ConfigRoot
from pipelex.system.configuration.configs import ConfigPaths, PipelexConfig
-from pipelex.system.environment import is_env_var_truthy
+from pipelex.system.pipelex_service.exceptions import (
+ GatewayTermsNotAcceptedError,
+)
+from pipelex.system.pipelex_service.pipelex_service_config import (
+ is_pipelex_gateway_enabled,
+ load_pipelex_service_config_if_exists,
+)
+from pipelex.system.pipelex_service.remote_config import (
+ fetch_remote_config,
+)
from pipelex.system.registries.func_registry import func_registry
+from pipelex.system.registries.singleton import MetaSingleton
from pipelex.system.runtime import IntegrationMode, runtime_manager
from pipelex.system.telemetry.observer_telemetry import ObserverTelemetry
from pipelex.system.telemetry.telemetry_config import (
- TELEMETRY_CONFIG_FILE_NAME,
TelemetryConfig,
- TelemetryMode,
-)
-from pipelex.system.telemetry.telemetry_manager import (
- DO_NOT_TRACK_ENV_VAR_KEY,
- TelemetryManager,
)
+from pipelex.system.telemetry.telemetry_factory import make_telemetry_manager
from pipelex.system.telemetry.telemetry_manager_abstract import (
TelemetryManagerAbstract,
- TelemetryManagerNoOp,
)
from pipelex.test_extras.registry_test_models import TestRegistryModels
from pipelex.tools.misc.package_utils import get_package_info
-from pipelex.tools.misc.toml_utils import load_toml_from_path
from pipelex.tools.secrets.env_secrets_provider import EnvSecretsProvider
from pipelex.tools.secrets.secrets_provider_abstract import SecretsProviderAbstract
from pipelex.tools.storage.storage_provider_abstract import StorageProviderAbstract
from pipelex.types import Self
from pipelex.urls import URLs
+if TYPE_CHECKING:
+ from pipelex.cogt.model_backends.model_spec_factory import BackendModelSpecs
+
PACKAGE_NAME, PACKAGE_VERSION = get_package_info()
@@ -83,6 +91,7 @@ class Pipelex(metaclass=MetaSingleton):
config_dir_path: str | None = None,
config_cls: type[ConfigRoot] | None = None,
) -> None:
+ self.is_pipelex_service_enabled = False # Will be set during setup
self.config_dir_path = config_dir_path or ConfigPaths.DEFAULT_CONFIG_DIR_PATH
self.pipelex_hub = PipelexHub()
set_pipelex_hub(self.pipelex_hub)
@@ -154,7 +163,6 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.
pipeline_tracker: PipelineTracker | None = None,
pipe_router: PipeRouterProtocol | None = None,
reporting_delegate: ReportingProtocol | None = None,
- force_enable_telemetry: bool = False,
telemetry_config: TelemetryConfig | None = None,
telemetry_manager: TelemetryManagerAbstract | None = None,
observers: dict[str, ObserverProtocol] | None = None,
@@ -164,25 +172,62 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.
if kwargs:
msg = f"The base setup method does not support any additional arguments: {kwargs}"
raise PipelexSetupError(msg)
- # tools
+
+ # Initialize secrets provider early - needed for gateway check
+ secrets_provider = secrets_provider or EnvSecretsProvider()
+
+ # --- Pipelex Service and Telemetry --------------------------------------------------
+
+ # Check if Pipelex Gateway is enabled
+ # for now the only servic is the Pipelex Gateway
+ is_pipelex_service_enabled = is_pipelex_gateway_enabled()
+
+ gateway_model_specs: BackendModelSpecs | None = None
+ if is_pipelex_service_enabled:
+ # Skip terms check for CI mode - automated CI/CD pipelines don't require human consent
+ if integration_mode.requires_terms_acceptance:
+ # Check if terms are accepted
+ pipelex_service_config = load_pipelex_service_config_if_exists(config_dir=config_manager.pipelex_config_dir)
+ if pipelex_service_config is None or not pipelex_service_config.agreement.terms_accepted:
+ raise GatewayTermsNotAcceptedError
+ # Fetch remote configuration
+ remote_config = fetch_remote_config()
+ log.verbose("Successfully fetched Pipelex Gateway remote configuration")
+ gateway_model_specs = remote_config.backend_model_specs
+
+ self.telemetry_manager = make_telemetry_manager(
+ secrets_provider=secrets_provider,
+ integration_mode=integration_mode,
+ is_pipelex_telemetry_enabled=is_pipelex_service_enabled,
+ telemetry_config=telemetry_config,
+ injected_telemetry_manager=telemetry_manager,
+ )
+ self.telemetry_manager.setup(integration_mode=integration_mode)
+ self.pipelex_hub.set_telemetry_manager(telemetry_manager=self.telemetry_manager)
+
+ # --- Tools ----------------------------------------------------------------------------
+
self.class_registry = class_registry or ClassRegistry()
self.pipelex_hub.set_class_registry(self.class_registry)
self.kajson_manager = KajsonManager(class_registry=self.class_registry)
- secrets_provider = secrets_provider or EnvSecretsProvider()
self.pipelex_hub.set_secrets_provider(secrets_provider=secrets_provider)
self.pipelex_hub.set_storage_provider(storage_provider)
self.library_manager = library_manager or LibraryManager()
self.pipelex_hub.set_library_manager(library_manager=self.library_manager)
- # cogt
+ # --- AI Models and Inference Management ------------------------------------------------
+
self.plugin_manager.setup()
self.models_manager: ModelManagerAbstract = models_manager or ModelManager()
self.pipelex_hub.set_models_manager(models_manager=self.models_manager)
try:
- self.models_manager.setup(secrets_provider=secrets_provider)
+ self.models_manager.setup(
+ secrets_provider=secrets_provider,
+ gateway_model_specs=gateway_model_specs,
+ )
except RoutingProfileLibraryNotFoundError as routing_not_found_exc:
msg = self._get_config_file_not_found_error_msg("routing profile library")
raise PipelexSetupError(msg) from routing_not_found_exc
@@ -207,42 +252,19 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.
except InferenceBackendCredentialsError as credentials_exc:
backend_name = credentials_exc.backend_name
var_name = credentials_exc.key_name
- error_msg: str
- if isinstance(secrets_provider, EnvSecretsProvider):
- error_msg = (
- f"Could not get credentials for inference backend '{backend_name}':\n{credentials_exc},\n"
- f"you need to add '{var_name}' to your environment variables or to your .env file."
- )
- else:
- error_msg = (
- f"Could not get credentials for inference backend '{backend_name}':\n{credentials_exc},\n"
- f"check that secret '{var_name}' is available from your secrets provider."
- )
- if credentials_exc.backend_name == "pipelex_inference":
- error_msg += (
- "\nYou can check the project's README about getting a Pipelex Inference API key,\n\n"
- "or you can bring your own 'OPENAI_API_KEY', "
- "'AZURE_OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'MISTRAL_API_KEY' etc.\n"
- "--> choose which inference backends to enable in '.pipelex/inference/backends.toml'\n"
- )
+ error_msg = BackendCredentialsErrorMsgFactory.make_one_variable_missing_error_msg(
+ secrets_provider=secrets_provider,
+ backend_name=backend_name,
+ var_name=var_name,
+ )
raise PipelexSetupError(error_msg) from credentials_exc
self.pipelex_hub.set_content_generator(content_generator or ContentGenerator())
self.inference_manager = inference_manager or InferenceManager()
self.pipelex_hub.set_inference_manager(self.inference_manager)
- self.library_manager = library_manager or LibraryManager()
- self.pipelex_hub.set_library_manager(library_manager=self.library_manager)
-
- # reporting
- if get_config().pipelex.feature_config.is_reporting_enabled:
- self.reporting_delegate = reporting_delegate or ReportingManager()
- else:
- self.reporting_delegate = ReportingNoOp()
- self.pipelex_hub.set_report_delegate(self.reporting_delegate)
- self.reporting_delegate.setup()
+ # --- Pipeline Tracking (deprecated) ----------------------------------------------------
- # pipeline
if pipeline_tracker:
self.pipeline_tracker = pipeline_tracker
elif get_config().pipelex.feature_config.is_pipeline_tracking_enabled:
@@ -250,47 +272,41 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.
else:
self.pipeline_tracker = PipelineTrackerNoOp()
self.pipelex_hub.set_pipeline_tracker(pipeline_tracker=self.pipeline_tracker)
+ self.pipeline_tracker.setup()
+
+ # --- Libraries & Registries -------------------------------------------------------------
+
+ if get_config().pipelex.feature_config.is_reporting_enabled:
+ self.reporting_delegate = reporting_delegate or ReportingManager()
+ else:
+ self.reporting_delegate = ReportingNoOp()
+ self.pipelex_hub.set_report_delegate(self.reporting_delegate)
+ self.reporting_delegate.setup()
+
+ self.library_manager = library_manager or LibraryManager()
+ self.pipelex_hub.set_library_manager(library_manager=self.library_manager)
+
self.pipeline_manager = pipeline_manager or PipelineManager()
self.pipelex_hub.set_pipeline_manager(pipeline_manager=self.pipeline_manager)
+ self.pipeline_manager.setup()
self.class_registry.register_classes(CoreRegistryModels.get_all_models())
if runtime_manager.is_unit_testing:
log.verbose("Registering test models for unit testing")
self.class_registry.register_classes(TestRegistryModels.get_all_models())
- if integration_mode.allows_telemetry() or force_enable_telemetry:
- if not telemetry_config:
- config_path = os.path.join(config_manager.pipelex_config_dir, TELEMETRY_CONFIG_FILE_NAME)
- telemetry_config_toml = load_toml_from_path(path=config_path)
- telemetry_config = TelemetryConfig.model_validate(telemetry_config_toml)
-
- match telemetry_config.telemetry_mode:
- case TelemetryMode.OFF:
- self.telemetry_manager = TelemetryManagerNoOp()
- log.debug("Telemetry is disabled because telemetry_mode is set to 'off'")
- case TelemetryMode.ANONYMOUS | TelemetryMode.IDENTIFIED:
- if telemetry_config.respect_dnt and is_env_var_truthy(DO_NOT_TRACK_ENV_VAR_KEY):
- self.telemetry_manager = TelemetryManagerNoOp()
- log.debug(f"Telemetry is disabled by env var '{DO_NOT_TRACK_ENV_VAR_KEY}'")
- else:
- self.telemetry_manager = telemetry_manager or TelemetryManager(telemetry_config=telemetry_config)
- else:
- self.telemetry_manager = TelemetryManagerNoOp()
- log.verbose(f"Telemetry is disabled because the integration mode '{integration_mode}' does not allow it")
-
- self.telemetry_manager.setup(integration_mode=integration_mode)
+ # --- Observers -------------------------------------------------------------------------
- self.pipelex_hub.set_telemetry_manager(telemetry_manager=self.telemetry_manager)
if not observers:
local_observer = LocalObserver()
observer_telemetry = ObserverTelemetry(telemetry_manager=self.telemetry_manager)
observers = {"local": local_observer, "telemetry": observer_telemetry}
multi_observer = MultiObserver(observers=observers)
self.pipelex_hub.set_observer(observer=multi_observer)
- self.pipelex_hub.set_pipe_router(pipe_router or PipeRouter(observer=multi_observer))
- self.pipeline_tracker.setup()
- self.pipeline_manager.setup()
+ # --- Pipe Router -----------------------------------------------------------------------
+
+ self.pipelex_hub.set_pipe_router(pipe_router or PipeRouter(observer=multi_observer))
log.verbose(f"{PACKAGE_NAME} version {PACKAGE_VERSION} setup done")
@@ -320,6 +336,12 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.
if self.__class__ in MetaSingleton.instances:
del MetaSingleton.instances[self.__class__]
+ def __enter__(self) -> Self:
+ return self
+
+ def __exit__(self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None) -> None:
+ self.teardown()
+
@classmethod
def make(
cls,
@@ -334,7 +356,6 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.
pipeline_tracker: PipelineTracker | None = None,
pipe_router: PipeRouterProtocol | None = None,
reporting_delegate: ReportingProtocol | None = None,
- force_enable_telemetry: bool = False,
telemetry_config: TelemetryConfig | None = None,
telemetry_manager: TelemetryManagerAbstract | None = None,
observers: dict[str, ObserverProtocol] | None = None,
@@ -358,7 +379,6 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.
pipeline_tracker: Custom pipeline tracking/logging
pipe_router: Custom pipe routing logic
reporting_delegate: Custom reporting handler
- force_enable_telemetry: Force enable telemetry even if the integration mode does not allow it
telemetry_config: Custom telemetry configuration
telemetry_manager: Custom telemetry manager
observers: Custom observers for pipeline events
@@ -376,25 +396,30 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.
raise PipelexSetupError(msg)
pipelex_instance = cls()
- pipelex_instance.setup(
- integration_mode=integration_mode,
- class_registry=class_registry,
- secrets_provider=secrets_provider,
- storage_provider=storage_provider,
- models_manager=models_manager,
- inference_manager=inference_manager,
- content_generator=content_generator,
- pipeline_manager=pipeline_manager,
- pipeline_tracker=pipeline_tracker,
- pipe_router=pipe_router,
- reporting_delegate=reporting_delegate,
- force_enable_telemetry=force_enable_telemetry,
- telemetry_config=telemetry_config,
- telemetry_manager=telemetry_manager,
- observers=observers,
- **kwargs,
- )
- pipelex_instance.models_manager.validate_model_deck()
+ try:
+ pipelex_instance.setup(
+ integration_mode=integration_mode,
+ class_registry=class_registry,
+ secrets_provider=secrets_provider,
+ storage_provider=storage_provider,
+ models_manager=models_manager,
+ inference_manager=inference_manager,
+ content_generator=content_generator,
+ pipeline_manager=pipeline_manager,
+ pipeline_tracker=pipeline_tracker,
+ pipe_router=pipe_router,
+ reporting_delegate=reporting_delegate,
+ telemetry_config=telemetry_config,
+ telemetry_manager=telemetry_manager,
+ observers=observers,
+ **kwargs,
+ )
+ pipelex_instance.models_manager.validate_model_deck()
+ except BaseException:
+ # Cleanup the singleton instance if setup fails to avoid "already initialized" errors
+ if cls in MetaSingleton.instances:
+ del MetaSingleton.instances[cls]
+ raise
log.verbose(f"{PACKAGE_NAME} version {PACKAGE_VERSION} ready")
return pipelex_instance
@@ -410,3 +435,14 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.
msg = "Pipelex is not initialized"
raise RuntimeError(msg)
return cast("Self", instance)
+
+ @classmethod
+ def teardown_if_needed(cls) -> None:
+ """Teardown the Pipelex singleton instance if it exists.
+
+ This is useful for cleanup in finally blocks where the instance
+ may or may not have been successfully created.
+ """
+ instance = cls.get_optional_instance()
+ if instance is not None:
+ instance.teardown()
diff --git a/pipelex/pipelex.toml b/pipelex/pipelex.toml
index b33d21d07..0ace7f4ad 100644
--- a/pipelex/pipelex.toml
+++ b/pipelex/pipelex.toml
@@ -104,6 +104,12 @@ api_key_method = "env"
is_model_fallback_enabled = true
missing_presets_reaction = "log"
+[cogt.tenacity_config]
+max_retries = 50 # Maximum number of retry attempts before giving up
+wait_multiplier = 0.2 # Multiplier applied to the wait time between retries (in seconds)
+wait_max = 20 # Maximum wait time between retries (in seconds)
+wait_exp_base = 1.3 # Base for exponential backoff calculation
+
[cogt.llm_config]
default_max_images = 100
is_structure_prompt_enabled = true
@@ -117,7 +123,6 @@ is_dump_error_enabled = false
[cogt.llm_config.llm_job_config]
max_retries = 3
-is_streaming_enabled = false
[cogt.llm_config.generic_templates]
structure_from_preliminary_text_system = """
diff --git a/pipelex/pipeline/exceptions.py b/pipelex/pipeline/exceptions.py
index 4c300783b..176de1c86 100644
--- a/pipelex/pipeline/exceptions.py
+++ b/pipelex/pipeline/exceptions.py
@@ -1,4 +1,4 @@
-from pipelex.base_exceptions import PipelexError
+from pipelex.base_exceptions import PipelexError, PipelexUnexpectedError
from pipelex.pipe_run.pipe_run_mode import PipeRunMode
@@ -27,3 +27,7 @@ class PipeStackOverflowError(PipelexError):
self.limit = limit
self.pipe_stack = pipe_stack
super().__init__(message)
+
+
+class JobMetadataError(PipelexUnexpectedError):
+ pass
diff --git a/pipelex/pipeline/execute.py b/pipelex/pipeline/execute.py
index 0769dc675..cf39dfa7e 100644
--- a/pipelex/pipeline/execute.py
+++ b/pipelex/pipeline/execute.py
@@ -1,3 +1,6 @@
+from typing import Any
+
+from pipelex.base_exceptions import PipelexError
from pipelex.client.protocol import PipelineInputs
from pipelex.core.memory.working_memory import WorkingMemory
from pipelex.core.pipes.pipe_output import PipeOutput
@@ -88,9 +91,32 @@ async def execute_pipeline(
search_domains=search_domains,
)
+ properties: dict[EventProperty, Any]
try:
pipe_output = await get_pipe_router().run(pipe_job)
except PipeRouterError as exc:
+ properties = {
+ EventProperty.PIPELINE_RUN_ID: pipeline_run_id,
+ EventProperty.PIPE_TYPE: pipe_job.pipe.pipe_type,
+ EventProperty.PIPELINE_OUTCOME: Outcome.FAILURE,
+ }
+ get_telemetry_manager().track_event(event_name=EventName.PIPELINE_COMPLETE, properties=properties)
+ raise PipelineExecutionError(
+ message=exc.message,
+ run_mode=pipe_job.pipe_run_params.run_mode,
+ pipe_code=pipe_job.pipe.code,
+ output_name=pipe_job.output_name,
+ pipe_stack=pipe_job.pipe_run_params.pipe_stack,
+ ) from exc
+ except PipelexError as exc:
+ # Catch other Pipelex errors that bypass the router's PipeRunError handling
+ # (e.g., PipeRunInputsError raised directly from pipe_abstract.py)
+ properties = {
+ EventProperty.PIPELINE_RUN_ID: pipeline_run_id,
+ EventProperty.PIPE_TYPE: pipe_job.pipe.pipe_type,
+ EventProperty.PIPELINE_OUTCOME: Outcome.FAILURE,
+ }
+ get_telemetry_manager().track_event(event_name=EventName.PIPELINE_COMPLETE, properties=properties)
raise PipelineExecutionError(
message=exc.message,
run_mode=pipe_job.pipe_run_params.run_mode,
@@ -105,7 +131,7 @@ async def execute_pipeline(
properties = {
EventProperty.PIPELINE_RUN_ID: pipeline_run_id,
EventProperty.PIPE_TYPE: pipe_job.pipe.pipe_type,
- EventProperty.PIPELINE_EXECUTE_OUTCOME: Outcome.SUCCESS,
+ EventProperty.PIPELINE_OUTCOME: Outcome.SUCCESS,
}
get_telemetry_manager().track_event(event_name=EventName.PIPELINE_COMPLETE, properties=properties)
return pipe_output
diff --git a/pipelex/pipeline/job_metadata.py b/pipelex/pipeline/job_metadata.py
index 8bd1ae443..9279c6889 100644
--- a/pipelex/pipeline/job_metadata.py
+++ b/pipelex/pipeline/job_metadata.py
@@ -3,6 +3,7 @@ from datetime import datetime
from pydantic import BaseModel, Field
from pipelex.pipeline.pipeline_models import SpecialPipelineId
+from pipelex.system.telemetry.otel_context import OtelContext
from pipelex.types import StrEnum
@@ -20,14 +21,32 @@ class UnitJobId(StrEnum):
IMG_GEN_TEXT_TO_IMAGE = "img_gen_text_to_image"
EXTRACT_PAGES = "extract_pages"
+ @property
+ def model_kind(self) -> str:
+ match self:
+ case UnitJobId.LLM_GEN_TEXT:
+ return "LLM"
+ case UnitJobId.LLM_GEN_OBJECT:
+ return "LLM"
+ case UnitJobId.IMG_GEN_TEXT_TO_IMAGE:
+ return "ImgGen"
+ case UnitJobId.EXTRACT_PAGES:
+ return "Extract"
+
class JobMetadata(BaseModel):
- job_name: str | None = None
pipeline_run_id: str = Field(default=SpecialPipelineId.UNTITLED)
- pipe_job_ids: list[str] | None = None
+ pipe_code: str | None = None
+
+ # Business ID for the current pipe execution (16-char hex string).
+ # Always set during pipe runs for tracking purposes.
+ pipe_run_id: str | None = None
+
+ # OTel context with precomputed trace/span IDs. None when telemetry is disabled.
+ otel_context: OtelContext | None = None
content_generation_job_id: str | None = None
- unit_job_id: str | None = None
+ unit_job_id: UnitJobId | None = None
job_category: JobCategory | None = None
started_at: datetime | None = Field(default_factory=datetime.now)
@@ -42,9 +61,12 @@ class JobMetadata(BaseModel):
def update(self, updated_metadata: "JobMetadata"):
if updated_metadata.job_category:
self.job_category = updated_metadata.job_category
- if updated_metadata.pipe_job_ids:
- self.pipe_job_ids = self.pipe_job_ids or []
- self.pipe_job_ids.extend(updated_metadata.pipe_job_ids)
+ if updated_metadata.pipe_code:
+ self.pipe_code = updated_metadata.pipe_code
+ if updated_metadata.pipe_run_id:
+ self.pipe_run_id = updated_metadata.pipe_run_id
+ if updated_metadata.otel_context:
+ self.otel_context = updated_metadata.otel_context
if updated_metadata.content_generation_job_id:
self.content_generation_job_id = updated_metadata.content_generation_job_id
if updated_metadata.unit_job_id:
@@ -54,7 +76,16 @@ class JobMetadata(BaseModel):
if updated_metadata.completed_at:
self.completed_at = updated_metadata.completed_at
- def copy_with_update(self, updated_metadata: "JobMetadata") -> "JobMetadata":
- new_metadata = self.model_copy()
+ def copy_with_update(self, updated_metadata: "JobMetadata", otel_context: OtelContext | None) -> "JobMetadata":
+ """Create a copy of this metadata with updates applied.
+
+ Args:
+ updated_metadata: Metadata with fields to update (sparse update - only truthy fields are applied)
+ otel_context: OTel context to set on the copy. Unlike other fields, this is always set explicitly
+ because it's computed fresh per pipe run and should replace the parent's context
+ (even when None, e.g. in dry mode or when tracing is disabled).
+ """
+ new_metadata = self.model_copy(deep=True)
new_metadata.update(updated_metadata=updated_metadata)
+ new_metadata.otel_context = otel_context
return new_metadata
diff --git a/pipelex/pipeline/pipeline_factory.py b/pipelex/pipeline/pipeline_factory.py
index e56931907..1f918b8d4 100644
--- a/pipelex/pipeline/pipeline_factory.py
+++ b/pipelex/pipeline/pipeline_factory.py
@@ -1,11 +1,22 @@
-import shortuuid
+from uuid import uuid4
+from pipelex import log
from pipelex.pipeline.pipeline import Pipeline
class PipelineFactory:
@classmethod
def make_pipeline(cls) -> Pipeline:
+ pipeline_run_id = cls.make_pipeline_run_id()
+ log.dev(f"Making new pipeline with run id: {pipeline_run_id}")
return Pipeline(
- pipeline_run_id=shortuuid.uuid(),
+ pipeline_run_id=pipeline_run_id,
)
+
+ @classmethod
+ def make_pipeline_run_id(cls) -> str:
+ return str(uuid4())
+
+ @classmethod
+ def make_pipe_run_id(cls) -> str:
+ return str(uuid4())
diff --git a/pipelex/pipeline/pipeline_manager.py b/pipelex/pipeline/pipeline_manager.py
index 791e99925..40a0b500e 100644
--- a/pipelex/pipeline/pipeline_manager.py
+++ b/pipelex/pipeline/pipeline_manager.py
@@ -41,7 +41,7 @@ class PipelineManager(PipelineManagerAbstract, RootModel[PipelineManagerRoot]):
return pipeline
@override
- def add_new_pipeline(self) -> Pipeline:
+ def add_new_pipeline(self, pipe_code: str | None) -> Pipeline:
pipeline = PipelineFactory.make_pipeline()
self._set_pipeline(pipeline_run_id=pipeline.pipeline_run_id, pipeline=pipeline)
return pipeline
diff --git a/pipelex/pipeline/pipeline_manager_abstract.py b/pipelex/pipeline/pipeline_manager_abstract.py
index 9e3e7a972..3b1916234 100644
--- a/pipelex/pipeline/pipeline_manager_abstract.py
+++ b/pipelex/pipeline/pipeline_manager_abstract.py
@@ -21,5 +21,5 @@ class PipelineManagerAbstract(ABC):
pass
@abstractmethod
- def add_new_pipeline(self) -> Pipeline:
+ def add_new_pipeline(self, pipe_code: str | None) -> Pipeline:
pass
diff --git a/pipelex/pipeline/pipeline_run_setup.py b/pipelex/pipeline/pipeline_run_setup.py
index 94b19cee5..988726a30 100644
--- a/pipelex/pipeline/pipeline_run_setup.py
+++ b/pipelex/pipeline/pipeline_run_setup.py
@@ -6,6 +6,7 @@ from pipelex.core.memory.working_memory import WorkingMemory
from pipelex.core.memory.working_memory_factory import WorkingMemoryFactory
from pipelex.hub import (
get_library_manager,
+ get_otel_tracer,
get_pipeline_manager,
get_report_delegate,
get_required_pipe,
@@ -21,10 +22,12 @@ from pipelex.pipe_run.pipe_run_params import (
)
from pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactory
from pipelex.pipeline.exceptions import PipeExecutionError
-from pipelex.pipeline.job_metadata import JobMetadata
+from pipelex.pipeline.job_metadata import JobMetadata, OtelContext
from pipelex.pipeline.validate_bundle import validate_bundle
from pipelex.system.environment import get_optional_env
from pipelex.system.telemetry.events import EventName, EventProperty
+from pipelex.system.telemetry.otel_constants import OTelConstants
+from pipelex.system.telemetry.otel_factory import OtelFactory
if TYPE_CHECKING:
from pipelex.core.bundles.pipelex_bundle_blueprint import PipelexBundleBlueprint
@@ -97,7 +100,7 @@ async def pipeline_run_setup(
msg = "Either pipe_code or plx_content must be provided to the pipeline API."
raise ValueError(msg)
- pipeline = get_pipeline_manager().add_new_pipeline()
+ pipeline = get_pipeline_manager().add_new_pipeline(pipe_code=pipe_code)
pipeline_run_id = pipeline.pipeline_run_id
if not library_id:
@@ -124,7 +127,10 @@ async def pipeline_run_setup(
raise PipeExecutionError(message=msg)
elif pipe_code:
if library_dirs:
- library_manager.load_libraries(library_id=library_id, library_dirs=[Path(library_dir) for library_dir in library_dirs])
+ library_manager.load_libraries(
+ library_id=library_id,
+ library_dirs=[Path(library_dir) for library_dir in library_dirs],
+ )
else:
library_manager.load_libraries(library_id=library_id, library_dirs=[Path.cwd()])
pipe = get_required_pipe(pipe_code=pipe_code)
@@ -132,6 +138,8 @@ async def pipeline_run_setup(
msg = "Either provide pipe_code or plx_content to the pipeline API. 'pipe_code' must be provided when 'plx_content' is None"
raise PipeExecutionError(message=msg)
+ pipe_code = pipe.code
+
search_domains = search_domains or []
if pipe.domain not in search_domains:
search_domains.insert(0, pipe.domain)
@@ -155,8 +163,25 @@ async def pipeline_run_setup(
get_report_delegate().open_registry(pipeline_run_id=pipeline_run_id)
+ # Initialize OtelContext if telemetry is enabled (not dry mode and tracer available)
+ # The trace_id is computed once here; span_id uses OTEL_VIRTUAL_ROOT_PARENT_SPAN_ID for root
+ otel_context: OtelContext | None = None
+ if pipe_run_mode.is_live and get_otel_tracer() is not None:
+ trace_id = OtelFactory.make_trace_id(pipeline_run_id=pipeline_run_id)
+ trace_name, trace_name_redacted = OtelFactory.make_trace_names(pipeline_run_id=pipeline_run_id, pipe_code=pipe_code)
+ otel_context = OtelContext(
+ trace_id=trace_id,
+ trace_name=trace_name,
+ trace_name_redacted=trace_name_redacted,
+ span_id=OTelConstants.OTEL_VIRTUAL_ROOT_PARENT_SPAN_ID,
+ )
+ # Emit trace start event immediately to establish trace name in PostHog
+ # This must happen before any pipe spans are created/exported
+ get_telemetry_manager().handle_trace_start(trace_name=trace_name, trace_name_redacted=trace_name_redacted, trace_id=trace_id)
+
job_metadata = JobMetadata(
pipeline_run_id=pipeline.pipeline_run_id,
+ otel_context=otel_context,
)
pipe_run_params = PipeRunParamsFactory.make_run_params(
diff --git a/pipelex/plugins/anthropic/anthropic_factory.py b/pipelex/plugins/anthropic/anthropic_factory.py
index 3c3470518..9011628bf 100644
--- a/pipelex/plugins/anthropic/anthropic_factory.py
+++ b/pipelex/plugins/anthropic/anthropic_factory.py
@@ -1,4 +1,3 @@
-import asyncio
from typing import TYPE_CHECKING
from anthropic import AsyncAnthropic, AsyncAnthropicBedrock
@@ -11,21 +10,15 @@ from openai.types.chat import (
from pipelex.cogt.exceptions import CogtError
from pipelex.cogt.image.prompt_image import (
- PromptImage,
- PromptImageBase64,
- PromptImagePath,
PromptImageTypedBase64,
PromptImageTypedUrlOrBase64,
- PromptImageUrl,
)
-from pipelex.cogt.image.prompt_image_factory import PromptImageFactory
+from pipelex.cogt.image.prompt_image_utils import prep_prompt_images
from pipelex.cogt.llm.llm_job import LLMJob
from pipelex.cogt.model_backends.backend import InferenceBackend
from pipelex.cogt.usage.token_category import NbTokensByCategoryDict, TokenCategory
from pipelex.config import get_config
from pipelex.plugins.plugin_sdk_registry import Plugin
-from pipelex.tools.misc.base_64_utils import load_binary_as_base64_async
-from pipelex.tools.misc.filetype_utils import detect_file_type_from_base64
from pipelex.types import StrEnum
if TYPE_CHECKING:
@@ -76,17 +69,16 @@ class AnthropicFactory:
) -> MessageParam:
message: MessageParam
content: list[TextBlockParam | ImageBlockParam] = []
+ llm_prompt = llm_job.llm_prompt
- if llm_job.llm_prompt.user_text:
+ if user_text := llm_prompt.user_text:
text_block_param: TextBlockParam = {
"type": "text",
- "text": llm_job.llm_prompt.user_text,
+ "text": user_text,
}
content.append(text_block_param)
- if llm_job.llm_prompt.user_images:
- tasks_to_prep_images = [cls._prep_image_for_anthropic(prompt_image) for prompt_image in llm_job.llm_prompt.user_images]
- prepped_user_images = await asyncio.gather(*tasks_to_prep_images)
- # images_block_params: List[ImageBlockParam] = []
+ if llm_prompt.user_images:
+ prepped_user_images = await prep_prompt_images(prompt_images=llm_prompt.user_images, is_http_url_enabled=False)
for prepped_image in prepped_user_images:
image_block_param: ImageBlockParam
if isinstance(prepped_image, PromptImageTypedBase64):
@@ -170,26 +162,6 @@ class AnthropicFactory:
return message # type: ignore[return-value, valid-type] # pyright: ignore[reportReturnType]
- @classmethod
- async def _prep_image_for_anthropic(
- cls,
- prompt_image: PromptImage,
- ) -> PromptImageTypedUrlOrBase64:
- typed_bytes_or_url: PromptImageTypedUrlOrBase64
- if isinstance(prompt_image, PromptImageBase64):
- typed_bytes_or_url = prompt_image.make_prompt_image_typed_base64()
- elif isinstance(prompt_image, PromptImageUrl):
- image_bytes = await PromptImageFactory.make_promptimagebase64_from_url_async(prompt_image)
- file_type = detect_file_type_from_base64(image_bytes.base_64)
- typed_bytes_or_url = PromptImageTypedBase64(base_64=image_bytes.base_64, file_type=file_type)
- elif isinstance(prompt_image, PromptImagePath):
- b64 = await load_binary_as_base64_async(prompt_image.file_path)
- typed_bytes_or_url = PromptImageTypedBase64(base_64=b64, file_type=prompt_image.get_file_type())
- else:
- msg = f"Unsupported PromptImage type: '{type(prompt_image).__name__}'"
- raise AnthropicFactoryError(msg)
- return typed_bytes_or_url
-
@classmethod
async def make_simple_messages(
cls,
@@ -198,14 +170,12 @@ class AnthropicFactory:
"""Makes a list of messages with a system message (if provided) and followed by a user message."""
llm_prompt = llm_job.llm_prompt
messages: list[ChatCompletionMessageParam] = []
- # System message ####
if system_content := llm_prompt.system_text:
messages.append(ChatCompletionSystemMessageParam(role="system", content=system_content))
prepped_user_images: list[PromptImageTypedUrlOrBase64] | None
if llm_prompt.user_images:
- tasks_to_prep_images = [cls._prep_image_for_anthropic(prompt_image) for prompt_image in llm_prompt.user_images]
- prepped_user_images = await asyncio.gather(*tasks_to_prep_images)
+ prepped_user_images = await prep_prompt_images(prompt_images=llm_prompt.user_images, is_http_url_enabled=False)
else:
prepped_user_images = None
diff --git a/pipelex/plugins/anthropic/anthropic_list.py b/pipelex/plugins/anthropic/anthropic_list.py
new file mode 100644
index 000000000..4400b9740
--- /dev/null
+++ b/pipelex/plugins/anthropic/anthropic_list.py
@@ -0,0 +1,110 @@
+from __future__ import annotations
+
+import importlib.util
+from typing import TYPE_CHECKING
+
+from rich import box
+from rich.table import Table
+
+from pipelex.cli.exceptions import PipelexCLIError
+from pipelex.cogt.exceptions import MissingDependencyError
+from pipelex.hub import get_console
+from pipelex.plugins.plugin_sdk_registry import Plugin
+
+if TYPE_CHECKING:
+ from anthropic.types import ModelInfo
+
+ from pipelex.cogt.model_backends.backend import InferenceBackend
+
+
+async def list_anthropic_models(
+ sdk: str,
+ backend_name: str,
+ backend: InferenceBackend,
+ flat: bool,
+ any_listed: bool,
+) -> None:
+ """List Anthropic models."""
+ if importlib.util.find_spec("anthropic") is None:
+ lib_name = "anthropic"
+ lib_extra_name = "anthropic"
+ msg = (
+ "The anthropic SDK is required in order to use Anthropic models via the anthropic client. "
+ "However, you can use Anthropic models through bedrock directly "
+ "by using the 'bedrock-anthropic-claude' llm family. (eg: bedrock-anthropic-claude)"
+ )
+ raise MissingDependencyError(
+ lib_name,
+ lib_extra_name,
+ msg,
+ )
+
+ from anthropic import AuthenticationError # noqa: PLC0415
+
+ from pipelex.plugins.anthropic.anthropic_llms import anthropic_list_available_models # noqa: PLC0415
+
+ plugin = Plugin(sdk=sdk, backend=backend_name)
+ try:
+ anthropic_models = await anthropic_list_available_models(
+ plugin=plugin,
+ backend=backend,
+ )
+
+ if flat:
+ _display_anthropic_models_flat(
+ models=anthropic_models,
+ sdk=sdk,
+ backend_name=backend_name,
+ any_listed=any_listed,
+ )
+ else:
+ _display_anthropic_models_table(
+ models=anthropic_models,
+ sdk=sdk,
+ backend_name=backend_name,
+ )
+ except AuthenticationError as auth_exc:
+ msg = f"Authentication error for SDK '{sdk}' in backend '{backend_name}': {auth_exc}"
+ raise PipelexCLIError(msg) from auth_exc
+
+
+def _display_anthropic_models_flat(
+ models: list[ModelInfo],
+ sdk: str,
+ backend_name: str,
+ any_listed: bool,
+) -> None:
+ """Display Anthropic models in CSV format."""
+ console = get_console()
+ if not any_listed:
+ console.print("model_id,display_name,created_at,sdk,backend")
+ for anthropic_model in models:
+ created_date = anthropic_model.created_at.strftime("%Y-%m-%d") if anthropic_model.created_at else "N/A"
+ display_name = anthropic_model.display_name.replace(",", ";") if anthropic_model.display_name else "N/A"
+ console.print(f"{anthropic_model.id},{display_name},{created_date},{sdk},{backend_name}")
+
+
+def _display_anthropic_models_table(
+ models: list[ModelInfo],
+ sdk: str,
+ backend_name: str,
+) -> None:
+ """Display Anthropic models in table format."""
+ table = Table(
+ title=f"Available Models for Backend '{backend_name}' (SDK: {sdk})",
+ show_header=True,
+ header_style="bold cyan",
+ box=box.SQUARE_DOUBLE_HEAD,
+ )
+ table.add_column("Model ID", style="green")
+ table.add_column("Display Name", style="blue")
+ table.add_column("Created At", style="yellow")
+
+ for anthropic_model in models:
+ created_date = anthropic_model.created_at.strftime("%Y-%m-%d") if anthropic_model.created_at else "N/A"
+ table.add_row(anthropic_model.id, anthropic_model.display_name, created_date)
+
+ console = get_console()
+ console.print("\n")
+ console.print(table)
+ console.print("\n")
diff --git a/pipelex/plugins/anthropic/anthropic_llm_worker.py b/pipelex/plugins/anthropic/anthropic_llm_worker.py
index 3414b6b6d..bbadd629c 100644
--- a/pipelex/plugins/anthropic/anthropic_llm_worker.py
+++ b/pipelex/plugins/anthropic/anthropic_llm_worker.py
@@ -4,7 +4,6 @@ import instructor
from anthropic import AsyncAnthropic, AsyncAnthropicBedrock, omit
from typing_extensions import override
-from pipelex import log
from pipelex.base_exceptions import PipelexError
from pipelex.cogt.exceptions import LLMCompletionError, SdkTypeError
from pipelex.cogt.llm.llm_job import LLMJob
@@ -25,11 +24,6 @@ from pipelex.plugins.anthropic.anthropic_factory import (
)
from pipelex.reporting.reporting_protocol import ReportingProtocol
from pipelex.tools.typing.pydantic_utils import BaseModelTypeVar
-from pipelex.types import StrEnum
-
-
-class AnthropicExtraField(StrEnum):
- CLAUDE_4_TOKENS_LIMIT = "claude_4_tokens_limit"
class AnthropicLLMWorkerError(PipelexError):
@@ -97,31 +91,19 @@ class AnthropicLLMWorker(LLMWorkerInternalAbstract):
# Instance methods
#########################################################
- # TODO: implement streaming behind the scenes to avoid timeout/streaming errors with Claude 4 and high tokens
- def _adapt_max_tokens(self, max_tokens: int | None) -> int:
- max_tokens = max_tokens or self.default_max_tokens
-
- if (claude_4_tokens_limit := self.extra_config.get(AnthropicExtraField.CLAUDE_4_TOKENS_LIMIT)) and max_tokens > claude_4_tokens_limit:
- max_tokens = claude_4_tokens_limit
- log.warning(f"Max tokens is greater than the claude 4 reduced tokens limit, reducing to {max_tokens}")
- if not max_tokens:
- msg = f"Max tokens is None for model {self.inference_model.desc}"
- raise AnthropicWorkerConfigurationError(msg)
- return max_tokens
-
@override
async def _gen_text(
self,
llm_job: LLMJob,
) -> str:
+ job_params = llm_job.applied_job_params or llm_job.job_params
message = await AnthropicFactory.make_user_message(llm_job=llm_job)
- max_tokens = self._adapt_max_tokens(max_tokens=llm_job.job_params.max_tokens)
response = await self.anthropic_async_client.messages.create(
messages=[message],
system=llm_job.llm_prompt.system_text or omit,
model=self.inference_model.model_id,
- temperature=llm_job.job_params.temperature,
- max_tokens=max_tokens,
+ temperature=job_params.temperature,
+ max_tokens=job_params.max_tokens or self.default_max_tokens,
)
single_content_block = response.content[0]
@@ -130,12 +112,6 @@ class AnthropicLLMWorker(LLMWorkerInternalAbstract):
raise LLMCompletionError(msg)
full_reply_content = single_content_block.text
- single_content_block = response.content[0]
- if single_content_block.type != "text":
- msg = f"Unexpected content block type: {single_content_block.type}\nmodel: {self.inference_model.desc}"
- raise LLMCompletionError(msg)
- full_reply_content = single_content_block.text
-
if (llm_tokens_usage := llm_job.job_report.llm_tokens_usage) and (usage := response.usage):
llm_tokens_usage.nb_tokens_by_category = AnthropicFactory.make_nb_tokens_by_category(usage=usage)
@@ -147,8 +123,8 @@ class AnthropicLLMWorker(LLMWorkerInternalAbstract):
llm_job: LLMJob,
schema: type[BaseModelTypeVar],
) -> BaseModelTypeVar:
+ job_params = llm_job.applied_job_params or llm_job.job_params
messages = await AnthropicFactory.make_simple_messages(llm_job=llm_job)
- max_tokens = self._adapt_max_tokens(max_tokens=llm_job.job_params.max_tokens)
(
result_object,
completion,
@@ -157,8 +133,8 @@ class AnthropicLLMWorker(LLMWorkerInternalAbstract):
response_model=schema,
max_retries=llm_job.job_config.max_retries,
model=self.inference_model.model_id,
- temperature=llm_job.job_params.temperature,
- max_tokens=max_tokens,
+ temperature=job_params.temperature,
+ max_tokens=job_params.max_tokens or self.default_max_tokens,
)
if (llm_tokens_usage := llm_job.job_report.llm_tokens_usage) and (usage := completion.usage):
llm_tokens_usage.nb_tokens_by_category = AnthropicFactory.make_nb_tokens_by_category(usage=usage)
diff --git a/pipelex/plugins/azure_rest/azure_img_gen_worker.py b/pipelex/plugins/azure_rest/azure_img_gen_worker.py
index c032c12a9..b34d6baa7 100644
--- a/pipelex/plugins/azure_rest/azure_img_gen_worker.py
+++ b/pipelex/plugins/azure_rest/azure_img_gen_worker.py
@@ -30,7 +30,7 @@ class AzureImgGenWorker(ImgGenWorkerAbstract):
):
super().__init__(inference_model=inference_model, reporting_delegate=reporting_delegate)
- if plugin.sdk != "azure_rest":
+ if plugin.sdk != "azure_rest_img_gen":
msg = f"Plugin '{plugin}' is not supported for image generation"
raise NotImplementedError(msg)
self.plugin = plugin
diff --git a/pipelex/plugins/bedrock/bedrock_list.py b/pipelex/plugins/bedrock/bedrock_list.py
new file mode 100644
index 000000000..73c411f52
--- /dev/null
+++ b/pipelex/plugins/bedrock/bedrock_list.py
@@ -0,0 +1,120 @@
+from __future__ import annotations
+
+import importlib.util
+from typing import TYPE_CHECKING, Any
+
+from rich import box
+from rich.table import Table
+
+from pipelex.cli.exceptions import PipelexCLIError
+from pipelex.cogt.exceptions import MissingDependencyError
+from pipelex.config import get_config
+from pipelex.hub import get_console
+from pipelex.plugins.plugin_sdk_registry import Plugin
+from pipelex.tools.aws.aws_config import AwsCredentialsError
+
+if TYPE_CHECKING:
+ from pipelex.cogt.model_backends.backend import InferenceBackend
+
+
+def list_bedrock_models(
+ sdk: str,
+ backend_name: str,
+ backend: InferenceBackend,
+ flat: bool,
+ any_listed: bool,
+) -> None:
+ """List Bedrock models."""
+ if importlib.util.find_spec("boto3") is None or importlib.util.find_spec("aioboto3") is None:
+ lib_name = "boto3,aioboto3"
+ lib_extra_name = "bedrock"
+ msg = "The boto3 and aioboto3 SDKs are required to use Bedrock models."
+ raise MissingDependencyError(
+ lib_name,
+ lib_extra_name,
+ msg,
+ )
+
+ from pipelex.plugins.bedrock.bedrock_llms import bedrock_list_available_models # noqa: PLC0415
+
+ plugin = Plugin(sdk=sdk, backend=backend_name)
+
+ try:
+ # Get AWS region for display
+ aws_config = get_config().pipelex.aws_config
+ _, _, aws_region = aws_config.get_aws_access_keys()
+ except AwsCredentialsError as exc:
+ msg = f"Error getting AWS credentials for Bedrock: {exc}"
+ raise PipelexCLIError(msg) from exc
+
+ try:
+ # List available models using the plugin-specific function
+ bedrock_models_list = bedrock_list_available_models(
+ plugin=plugin,
+ backend=backend,
+ )
+
+ if flat:
+ _display_bedrock_models_flat(
+ models=bedrock_models_list,
+ sdk=sdk,
+ backend_name=backend_name,
+ aws_region=aws_region,
+ any_listed=any_listed,
+ )
+ else:
+ _display_bedrock_models_table(
+ models=bedrock_models_list,
+ sdk=sdk,
+ aws_region=aws_region,
+ )
+
+ except Exception as exc:
+ msg = f"Error listing Bedrock models: {exc}"
+ raise PipelexCLIError(msg) from exc
+
+
+def _display_bedrock_models_flat(
+ models: list[dict[str, Any]],
+ sdk: str,
+ backend_name: str,
+ aws_region: str,
+ any_listed: bool,
+) -> None:
+ """Display Bedrock models in CSV format."""
+ console = get_console()
+ if not any_listed:
+ console.print("model_id,provider,model_arn,sdk,backend,region")
+ for bedrock_model in models: # pyright: ignore[reportUnknownVariableType]
+ model_id = bedrock_model.get("modelId", "N/A") # pyright: ignore[reportUnknownMemberType,reportUnknownVariableType]
+ provider = bedrock_model.get("providerName", "N/A") # pyright: ignore[reportUnknownMemberType,reportUnknownVariableType]
+ model_arn = bedrock_model.get("modelArn", "N/A") # pyright: ignore[reportUnknownMemberType,reportUnknownVariableType]
+ console.print(f"{model_id},{provider},{model_arn},{sdk},{backend_name},{aws_region}") # pyright: ignore[reportUnknownArgumentType]
+
+
+def _display_bedrock_models_table(
+ models: list[dict[str, Any]],
+ sdk: str,
+ aws_region: str,
+) -> None:
+ """Display Bedrock models in table format."""
+ table = Table(
+ title=f"Available Bedrock Models in {aws_region} (SDK: {sdk})",
+ show_header=True,
+ header_style="bold cyan",
+ box=box.SQUARE_DOUBLE_HEAD,
+ )
+ table.add_column("Model ID", style="green")
+ table.add_column("Provider", style="blue")
+ table.add_column("Model ARN", style="yellow")
+
+ for bedrock_model in models: # pyright: ignore[reportUnknownVariableType]
+ model_id = bedrock_model.get("modelId", "N/A") # pyright: ignore[reportUnknownMemberType,reportUnknownVariableType]
+ provider = bedrock_model.get("providerName", "N/A") # pyright: ignore[reportUnknownMemberType,reportUnknownVariableType]
+ model_arn = bedrock_model.get("modelArn", "N/A") # pyright: ignore[reportUnknownMemberType,reportUnknownVariableType]
+ table.add_row(model_id, provider, model_arn) # pyright: ignore[reportUnknownArgumentType]
+
+ console = get_console()
+ console.print("\n")
+ console.print(table)
+ console.print("\n")
diff --git a/pipelex/plugins/bedrock/bedrock_llm_worker.py b/pipelex/plugins/bedrock/bedrock_llm_worker.py
index 2c8acda96..728a5acda 100644
--- a/pipelex/plugins/bedrock/bedrock_llm_worker.py
+++ b/pipelex/plugins/bedrock/bedrock_llm_worker.py
@@ -46,6 +46,7 @@ class BedrockLLMWorker(LLMWorkerInternalAbstract):
self,
llm_job: LLMJob,
) -> str:
+ job_params = llm_job.applied_job_params or llm_job.job_params
message = BedrockFactory.make_simple_message(llm_job=llm_job)
log.verbose(self.inference_model.model_id)
@@ -54,8 +55,8 @@ class BedrockLLMWorker(LLMWorkerInternalAbstract):
messages=message.to_dict_list(),
system_text=llm_job.llm_prompt.system_text,
model=self.inference_model.model_id,
- temperature=llm_job.job_params.temperature,
- max_tokens=llm_job.job_params.max_tokens or self.default_max_tokens,
+ temperature=job_params.temperature,
+ max_tokens=job_params.max_tokens or self.default_max_tokens,
)
if (llm_tokens_usage := llm_job.job_report.llm_tokens_usage) and nb_tokens_by_category:
llm_tokens_usage.nb_tokens_by_category = nb_tokens_by_category
diff --git a/pipelex/plugins/fal/fal_factory.py b/pipelex/plugins/fal/fal_factory.py
index 577a44c83..5f728ef02 100644
--- a/pipelex/plugins/fal/fal_factory.py
+++ b/pipelex/plugins/fal/fal_factory.py
@@ -1,7 +1,9 @@
-from typing import Any
+from typing import Any, cast
+
+from pydantic import ValidationError
from pipelex import log
-from pipelex.cogt.exceptions import ImgGenGeneratedTypeError, ImgGenParameterError
+from pipelex.cogt.exceptions import ImgGenGenerationError, ImgGenParameterError
from pipelex.cogt.image.generated_image import GeneratedImage
from pipelex.cogt.img_gen.img_gen_job import ImgGenJob
from pipelex.cogt.img_gen.img_gen_job_components import AspectRatio, OutputFormat, Quality
@@ -138,56 +140,36 @@ class FalFactory:
return args_dict
- @staticmethod
- def make_generated_image(fal_result: dict[str, Any]) -> GeneratedImage:
- images = fal_result["images"]
- fal_image_dict = images[0]
- image_url = fal_image_dict["url"]
- if not isinstance(image_url, str):
- msg = "Image url is not a string"
- raise ImgGenGeneratedTypeError(msg)
- # TODO: if the url is actual image data, send it to cloud storage?
-
- width = fal_image_dict["width"]
- if not isinstance(width, int):
- msg = "Image width is not an integer"
- raise ImgGenGeneratedTypeError(msg)
- height = fal_image_dict["height"]
- if not isinstance(height, int):
- msg = "Image height is not an integer"
- raise ImgGenGeneratedTypeError(msg)
-
- return GeneratedImage(
- url=image_url,
- width=width,
- height=height,
- )
+ @classmethod
+ def make_generated_image(cls, fal_result: dict[str, Any]) -> GeneratedImage:
+ generated_image_list = cls.make_generated_image_list(fal_result=fal_result)
+ if len(generated_image_list) != 1:
+ msg = f"Expected 1 image, got {len(generated_image_list)}"
+ raise ImgGenGenerationError(msg)
+ return generated_image_list[0]
- @staticmethod
- def make_generated_image_list(fal_result: dict[str, Any]) -> list[GeneratedImage]:
- fal_image_dicts = fal_result["images"]
+ @classmethod
+ def make_generated_image_list(cls, fal_result: dict[str, Any]) -> list[GeneratedImage]:
+ return cls._unpack_fal_result(fal_result=fal_result)
+ @classmethod
+ def _unpack_fal_result(cls, fal_result: dict[str, Any]) -> list[GeneratedImage]:
generated_image_list: list[GeneratedImage] = []
- for fal_image_dict in fal_image_dicts:
- image_url = fal_image_dict["url"]
- if not isinstance(image_url, str):
- msg = "Image url is not a string"
- raise ImgGenGeneratedTypeError(msg)
-
- width = fal_image_dict["width"]
- if not isinstance(width, int):
- msg = "Image width is not an integer"
- raise ImgGenGeneratedTypeError(msg)
- height = fal_image_dict["height"]
- if not isinstance(height, int):
- msg = "Image height is not an integer"
- raise ImgGenGeneratedTypeError(msg)
-
- generated_image = GeneratedImage(
- url=image_url,
- width=width,
- height=height,
- )
- generated_image_list.append(generated_image)
+ try:
+ image_dicts = fal_result["images"]
+ if not isinstance(image_dicts, list):
+ msg = f"Expected 'images' to be a list, got {type(image_dicts).__name__}"
+ raise ImgGenGenerationError(msg)
+ image_dicts = cast("list[dict[str, Any]]", image_dicts)
+ for image_dict in image_dicts:
+ generated_image = GeneratedImage(
+ url=image_dict["url"],
+ width=image_dict["width"],
+ height=image_dict["height"],
+ )
+ generated_image_list.append(generated_image)
+ except (KeyError, TypeError, ValidationError) as exc:
+ msg = f"Failed to parse image data from fal response: {exc}"
+ raise ImgGenGenerationError(msg) from exc
return generated_image_list
diff --git a/pipelex/system/registries/__init__py b/pipelex/plugins/gateway/__init__.py
similarity index 100%
rename from pipelex/system/registries/__init__py
rename to pipelex/plugins/gateway/__init__.py
diff --git a/pipelex/plugins/gateway/gateway_completions_factory.py b/pipelex/plugins/gateway/gateway_completions_factory.py
new file mode 100644
index 000000000..83085600f
--- /dev/null
+++ b/pipelex/plugins/gateway/gateway_completions_factory.py
@@ -0,0 +1,96 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, cast
+
+import openai
+from portkey_ai import (
+ createHeaders, # type: ignore[reportUnknownVariableType]
+)
+from typing_extensions import override
+
+from pipelex.cogt.extract.extract_output import ExtractedImageFromPage, ExtractOutput, Page
+from pipelex.plugins.gateway.gateway_constants import GatewayOpenAISdkVariant
+from pipelex.plugins.gateway.gateway_exceptions import GatewayFactoryError
+from pipelex.plugins.gateway.gateway_factory import GatewayFactory
+from pipelex.plugins.openai.openai_completions_factory import OpenAICompletionsFactory
+
+if TYPE_CHECKING:
+ from portkey_ai.api_resources.utils import GenericResponse
+
+ from pipelex.cogt.llm.llm_job import LLMJob
+ from pipelex.cogt.model_backends.backend import InferenceBackend
+ from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
+ from pipelex.plugins.plugin_sdk_registry import Plugin
+
+
+class GatewayCompletionsFactory(OpenAICompletionsFactory):
+ @classmethod
+ def make_portkey_openai_client_for_completions(
+ cls,
+ plugin: Plugin,
+ backend: InferenceBackend,
+ ) -> openai.AsyncOpenAI:
+ is_debug_enabled = GatewayFactory.is_debug_enabled(backend=backend)
+ endpoint = GatewayFactory.get_endpoint(backend=backend)
+ api_key = GatewayFactory.get_api_key(backend=backend)
+
+ if not GatewayOpenAISdkVariant.is_completions(plugin.sdk):
+ msg = f"Plugin '{plugin}' is not supported by '{cls.__name__}'"
+ raise GatewayFactoryError(msg)
+
+ return openai.AsyncOpenAI(
+ base_url=endpoint,
+ api_key="",
+ default_headers=createHeaders(
+ api_key=api_key,
+ strict_open_ai_compliance=False,
+ debug=is_debug_enabled,
+ ), # type: ignore[call-overload]
+ )
+
+ @classmethod
+ def make_extract_output_from_portkey_response(
+ cls,
+ response: GenericResponse,
+ ) -> ExtractOutput:
+ if not hasattr(response, "pages"):
+ msg = "Portkey extract response does not have pages"
+ raise GatewayFactoryError(msg)
+ pages: dict[int, Page] = {}
+ for extracted_page in response.pages: # pyright: ignore[reportUnknownMemberType, reportAttributeAccessIssue, reportUnknownVariableType]
+ if not isinstance(extracted_page, dict):
+ msg = "Extracted page is not a dictionary"
+ raise GatewayFactoryError(msg)
+ extracted_page_dict = cast("dict[str, Any]", extracted_page)
+ page_index = extracted_page_dict.get("index")
+ if page_index is None:
+ msg = "Page index is not set"
+ raise GatewayFactoryError(msg)
+ extracted_page_text = extracted_page_dict.get("markdown")
+ if extracted_page_text is None:
+ msg = "Page text is not set"
+ raise GatewayFactoryError(msg)
+ extracted_page_images = extracted_page_dict.get("images")
+ if extracted_page_images is None:
+ msg = "Page images are not set"
+ raise GatewayFactoryError(msg)
+ page_images: list[ExtractedImageFromPage] = []
+ for extracted_page_image in extracted_page_images:
+ extracted_image = ExtractedImageFromPage(
+ image_id=extracted_page_image["id"],
+ base_64=extracted_page_image["image_base64"],
+ caption=extracted_page_image["image_annotation"],
+ )
+ page_images.append(extracted_image)
+ pages[page_index] = Page(
+ text=extracted_page_text,
+ extracted_images=page_images,
+ page_view=None,
+ )
+ return ExtractOutput(
+ pages=pages,
+ )
+
+ @override
+ def make_extras(self, inference_model: InferenceModelSpec, llm_job: LLMJob, output_desc: str) -> tuple[dict[str, str], dict[str, Any]]:
+ return GatewayFactory.make_extras(inference_model=inference_model, llm_job=llm_job, output_desc=output_desc)
diff --git a/pipelex/plugins/gateway/gateway_constants.py b/pipelex/plugins/gateway/gateway_constants.py
new file mode 100644
index 000000000..33b88c113
--- /dev/null
+++ b/pipelex/plugins/gateway/gateway_constants.py
@@ -0,0 +1,30 @@
+from pipelex.types import StrEnum
+
+
+class GatewayOpenAISdkVariant(StrEnum):
+ GATEWAY_COMPLETIONS = "gateway_completions"
+ GATEWAY_RESPONSES = "gateway_responses"
+
+ @classmethod
+ def is_completions(cls, sdk: str) -> bool:
+ try:
+ variant = cls(sdk)
+ except ValueError:
+ return False
+ match variant:
+ case cls.GATEWAY_COMPLETIONS:
+ return True
+ case cls.GATEWAY_RESPONSES:
+ return False
+
+ @classmethod
+ def is_responses(cls, sdk: str) -> bool:
+ try:
+ variant = cls(sdk)
+ except ValueError:
+ return False
+ match variant:
+ case cls.GATEWAY_COMPLETIONS:
+ return False
+ case cls.GATEWAY_RESPONSES:
+ return True
diff --git a/pipelex/plugins/gateway/gateway_exceptions.py b/pipelex/plugins/gateway/gateway_exceptions.py
new file mode 100644
index 000000000..402ae8c62
--- /dev/null
+++ b/pipelex/plugins/gateway/gateway_exceptions.py
@@ -0,0 +1,13 @@
+from pipelex.cogt.exceptions import CogtError
+
+
+class PortkeyError(CogtError):
+ pass
+
+
+class GatewayFactoryError(PortkeyError):
+ pass
+
+
+class GatewayCredentialsError(PortkeyError):
+ pass
diff --git a/pipelex/plugins/gateway/gateway_extract_worker.py b/pipelex/plugins/gateway/gateway_extract_worker.py
new file mode 100644
index 000000000..6142f822e
--- /dev/null
+++ b/pipelex/plugins/gateway/gateway_extract_worker.py
@@ -0,0 +1,171 @@
+from typing import Any
+
+from portkey_ai import AsyncPortkey
+from portkey_ai.api_resources import exceptions as portkey_exceptions
+from portkey_ai.api_resources.utils import GenericResponse
+from tenacity import AsyncRetrying, RetryCallState, retry_if_exception, stop_after_attempt, wait_random_exponential
+from typing_extensions import override
+
+from pipelex import log
+from pipelex.cogt.exceptions import ExtractCapabilityError, ExtractJobFailureError, SdkTypeError
+from pipelex.cogt.extract.extract_input import ExtractInputError
+from pipelex.cogt.extract.extract_job import ExtractJob
+from pipelex.cogt.extract.extract_output import ExtractOutput
+from pipelex.cogt.extract.extract_worker_abstract import ExtractWorkerAbstract
+from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
+from pipelex.config import get_config
+from pipelex.plugins.gateway.gateway_completions_factory import GatewayCompletionsFactory
+from pipelex.plugins.portkey.portkey_constants import PortkeyHeaderKey
+from pipelex.reporting.reporting_protocol import ReportingProtocol
+from pipelex.tools.misc.base_64_utils import make_base_64_url_from_location_async
+from pipelex.types import StrEnum
+
+
+class DocumentKind(StrEnum):
+ IMAGE = "image"
+ PDF = "pdf"
+
+ @property
+ def document_tag(self) -> str:
+ match self:
+ case DocumentKind.IMAGE:
+ return "image_url"
+ case DocumentKind.PDF:
+ return "document_url"
+
+
+class PortkeyExtractWorker(ExtractWorkerAbstract):
+ def __init__(
+ self,
+ sdk_instance: Any,
+ extra_config: dict[str, Any],
+ inference_model: InferenceModelSpec,
+ reporting_delegate: ReportingProtocol | None = None,
+ ):
+ super().__init__(
+ extra_config=extra_config,
+ inference_model=inference_model,
+ reporting_delegate=reporting_delegate,
+ )
+
+ if not isinstance(sdk_instance, AsyncPortkey):
+ msg = f"Provided extraction sdk_instance for {self.__class__.__name__} is not of type Portkey: it's a '{type(sdk_instance)}'"
+ raise SdkTypeError(msg)
+
+ self.portkey_client: AsyncPortkey = sdk_instance
+ self._tenacity_config = get_config().cogt.tenacity_config
+
+ def _make_retryer(self) -> AsyncRetrying:
+ """Create a fresh AsyncRetrying instance for each extraction call.
+
+ This is necessary because AsyncRetrying is stateful and cannot be shared
+ across parallel async calls without causing race conditions.
+ """
+ return AsyncRetrying(
+ retry=retry_if_exception(self._is_retryable_portkey_error),
+ before_sleep=self._log_retry,
+ wait=wait_random_exponential(
+ multiplier=self._tenacity_config.wait_multiplier,
+ max=self._tenacity_config.wait_max,
+ exp_base=self._tenacity_config.wait_exp_base,
+ ),
+ reraise=True,
+ stop=stop_after_attempt(self._tenacity_config.max_retries),
+ )
+
+ @override
+ async def _extract_pages(
+ self,
+ extract_job: ExtractJob,
+ ) -> ExtractOutput:
+ if image_uri := extract_job.extract_input.image_uri:
+ if extract_job.job_params.should_caption_images:
+ msg = f"Captioning is not implemented by '{self.inference_model.tag}'."
+ raise NotImplementedError(msg)
+ base64_url = await make_base_64_url_from_location_async(location=image_uri)
+ extract_output = await self.extract_base64_url(
+ base64_url=base64_url,
+ document_type=DocumentKind.IMAGE,
+ should_include_images=False,
+ )
+
+ elif pdf_uri := extract_job.extract_input.pdf_uri:
+ if extract_job.job_params.should_caption_images:
+ msg = f"Captioning is not implemented by '{self.inference_model.tag}'."
+ raise ExtractCapabilityError(msg)
+ if extract_job.job_params.should_include_page_views:
+ log.verbose(f"Page views are not implemented by '{self.inference_model.tag}'.")
+ # TODO: use a model capability flag to check possibility before asking for it
+ # it it's asked and not available, raise
+ # the caller will be responsible to get the page views using other solution if needed
+ base64_url = await make_base_64_url_from_location_async(location=pdf_uri)
+ extract_output = await self.extract_base64_url(
+ base64_url=base64_url,
+ document_type=DocumentKind.PDF,
+ should_include_images=extract_job.job_params.should_include_images,
+ )
+ else:
+ msg = "No image nor PDF URI provided in ExtractJob"
+ raise ExtractInputError(msg)
+ return extract_output
+
+ async def extract_base64_url(
+ self,
+ base64_url: str,
+ document_type: DocumentKind,
+ should_include_images: bool = False,
+ ) -> ExtractOutput:
+ config_id = self._get_portkey_config_id()
+ log.dev(f"Extracting using config '{config_id}' with should_include_images: {should_include_images}")
+ doc_tag = document_type.document_tag
+
+ attempt_number = 0
+ response: GenericResponse | None = None
+ retryer = self._make_retryer()
+ async for attempt in retryer:
+ with attempt:
+ attempt_number += 1
+ response = await self.portkey_client.with_options(config=config_id).post( # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType]
+ "/",
+ model=self.inference_model.model_id,
+ document={"type": doc_tag, doc_tag: base64_url},
+ include_image_base64=True,
+ )
+
+ if response is None:
+ msg = f"Could not get a response for model '{self.inference_model.model_id}' via Portkey after {attempt_number} attempts"
+ raise ExtractJobFailureError(msg)
+
+ if not isinstance(response, GenericResponse):
+ msg = "Response is not of type GenericResponse"
+ raise TypeError(msg)
+ return GatewayCompletionsFactory.make_extract_output_from_portkey_response(
+ response=response,
+ )
+
+ def _get_portkey_config_id(self) -> str:
+ if not self.inference_model.extra_headers:
+ msg = f"{PortkeyHeaderKey.CONFIG} header is required"
+ raise ExtractInputError(msg)
+ config_id = self.inference_model.extra_headers.get(PortkeyHeaderKey.CONFIG)
+ if not config_id:
+ msg = f"{PortkeyHeaderKey.CONFIG} header is required"
+ raise ExtractInputError(msg)
+ return config_id
+
+ def _is_retryable_portkey_error(self, exc: BaseException) -> bool:
+ if isinstance(exc, portkey_exceptions.NotFoundError):
+ msg = str(exc).lower()
+ return "specified deployment could not be found" in msg
+ return False
+
+ def _log_retry(self, retry_state: RetryCallState) -> None:
+ """Called before sleeping between retries."""
+ if not retry_state.outcome:
+ log.error("Tenacity retry state outcome is None")
+ return
+ exc = retry_state.outcome.exception()
+ attempt = retry_state.attempt_number
+ wait_duration = retry_state.next_action.sleep if retry_state.next_action else 0.0
+ log.dev(f"{self.__class__.__name__} retry #{attempt} for '{self.inference_model.model_id}' due to '{type(exc).__name__}' (service is flaky).")
+ log.verbose(f"Wait duration before next attempt: {wait_duration:.4f}s")
diff --git a/pipelex/plugins/gateway/gateway_factory.py b/pipelex/plugins/gateway/gateway_factory.py
new file mode 100644
index 000000000..797d87c97
--- /dev/null
+++ b/pipelex/plugins/gateway/gateway_factory.py
@@ -0,0 +1,76 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+from portkey_ai import (
+ PORTKEY_GATEWAY_URL,
+ AsyncPortkey, # type: ignore[reportUnknownVariableType]
+)
+
+from pipelex import log
+from pipelex.cogt.llm.llm_constants import LLMOutputType
+from pipelex.hub import get_telemetry_manager
+from pipelex.plugins.gateway.gateway_exceptions import GatewayCredentialsError
+from pipelex.plugins.portkey.portkey_constants import PortkeyHeaderKey
+from pipelex.system.telemetry.otel_constants import OTelConstants
+
+if TYPE_CHECKING:
+ from pipelex.cogt.llm.llm_job import LLMJob
+ from pipelex.cogt.model_backends.backend import InferenceBackend
+ from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
+
+
+class GatewayFactory:
+ @classmethod
+ def is_debug_enabled(cls, backend: InferenceBackend) -> bool:
+ is_debug_configured = backend.extra_config.get("debug", False)
+ return get_telemetry_manager().is_portkey_logging_enabled(is_debug_configured=is_debug_configured)
+
+ @classmethod
+ def get_endpoint(cls, backend: InferenceBackend) -> str:
+ return backend.endpoint or PORTKEY_GATEWAY_URL
+
+ @classmethod
+ def get_api_key(cls, backend: InferenceBackend) -> str:
+ if not backend.api_key:
+ msg = "Portkey API key is not set"
+ raise GatewayCredentialsError(msg)
+ return backend.api_key
+
+ @classmethod
+ def make_portkey_client(
+ cls,
+ backend: InferenceBackend,
+ ) -> AsyncPortkey:
+ is_debug_enabled = cls.is_debug_enabled(backend=backend)
+ endpoint = cls.get_endpoint(backend=backend)
+ api_key = cls.get_api_key(backend=backend)
+ log.verbose(f"Making Portkey client with endpoint: {endpoint}, debug: {is_debug_enabled}")
+
+ return AsyncPortkey(
+ base_url=endpoint,
+ api_key=api_key,
+ debug=is_debug_enabled,
+ )
+
+ @classmethod
+ def make_extras(cls, inference_model: InferenceModelSpec, llm_job: LLMJob, output_desc: str) -> tuple[dict[str, str], dict[str, Any]]:
+ extra_headers: dict[str, str] = {}
+ if inference_model.extra_headers:
+ extra_headers.update(inference_model.extra_headers)
+ if not extra_headers.get(PortkeyHeaderKey.CONFIG) and not extra_headers.get(PortkeyHeaderKey.PROVIDER):
+ extra_headers[PortkeyHeaderKey.PROVIDER] = inference_model.backend_name
+
+ # OTel-correlated Portkey tracing (only when enabled and OTel context available)
+ if get_telemetry_manager().is_portkey_tracing_enabled() and (otel_context := llm_job.job_metadata.otel_context):
+ # Use OTel trace_id and span_id for correlation
+ extra_headers[PortkeyHeaderKey.TRACE_ID] = f"{otel_context.trace_id:032x}"
+ extra_headers[PortkeyHeaderKey.SPAN_ID] = f"{otel_context.span_id:016x}"
+
+ # Build span name with redacted output class name (consistent with Pipelex telemetry policy)
+ # Pipelex services always redact sensitive data to protect user privacy
+ unit_job_id = llm_job.job_metadata.unit_job_id or "unknown"
+ display_output = output_desc if output_desc == LLMOutputType.TEXT else OTelConstants.OUTPUT_CLASS_REDACTED
+ extra_headers[PortkeyHeaderKey.SPAN_NAME] = f"{unit_job_id} -> {display_output}"
+
+ return extra_headers, {}
diff --git a/pipelex/plugins/gateway/gateway_responses_factory.py b/pipelex/plugins/gateway/gateway_responses_factory.py
new file mode 100644
index 000000000..a5f37c5c0
--- /dev/null
+++ b/pipelex/plugins/gateway/gateway_responses_factory.py
@@ -0,0 +1,48 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+import openai
+from portkey_ai import (
+ createHeaders, # type: ignore[reportUnknownVariableType]
+)
+from typing_extensions import override
+
+from pipelex.plugins.gateway.gateway_constants import GatewayOpenAISdkVariant
+from pipelex.plugins.gateway.gateway_exceptions import GatewayFactoryError
+from pipelex.plugins.gateway.gateway_factory import GatewayFactory
+from pipelex.plugins.openai.openai_responses_factory import OpenAIResponsesFactory
+
+if TYPE_CHECKING:
+ from pipelex.cogt.llm.llm_job import LLMJob
+ from pipelex.cogt.model_backends.backend import InferenceBackend
+ from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
+ from pipelex.plugins.plugin_sdk_registry import Plugin
+
+
+class GatewayResponsesFactory(OpenAIResponsesFactory):
+ @classmethod
+ def make_portkey_openai_client_for_responses(
+ cls,
+ plugin: Plugin,
+ backend: InferenceBackend,
+ ) -> openai.AsyncOpenAI:
+ is_debug_enabled = GatewayFactory.is_debug_enabled(backend=backend)
+ endpoint = GatewayFactory.get_endpoint(backend=backend)
+ api_key = GatewayFactory.get_api_key(backend=backend)
+ if not GatewayOpenAISdkVariant.is_responses(plugin.sdk):
+ msg = f"Plugin '{plugin}' is not supported by '{cls.__name__}'"
+ raise GatewayFactoryError(msg)
+
+ return openai.AsyncOpenAI(
+ base_url=endpoint,
+ api_key="",
+ default_headers=createHeaders(
+ api_key=api_key,
+ debug=is_debug_enabled,
+ ), # type: ignore[call-overload]
+ )
+
+ @override
+ def make_extras(self, inference_model: InferenceModelSpec, llm_job: LLMJob, output_desc: str) -> tuple[dict[str, str], dict[str, Any]]:
+ return GatewayFactory.make_extras(inference_model=inference_model, llm_job=llm_job, output_desc=output_desc)
diff --git a/pipelex/plugins/google/google_list.py b/pipelex/plugins/google/google_list.py
new file mode 100644
index 000000000..2e83d576b
--- /dev/null
+++ b/pipelex/plugins/google/google_list.py
@@ -0,0 +1,102 @@
+from __future__ import annotations
+
+import importlib.util
+from typing import TYPE_CHECKING, Any
+
+from rich import box
+from rich.table import Table
+
+from pipelex.cogt.exceptions import MissingDependencyError
+from pipelex.hub import get_console
+
+if TYPE_CHECKING:
+ from pipelex.cogt.model_backends.backend import InferenceBackend
+
+
+async def list_google_models(
+ sdk: str,
+ backend_name: str,
+ backend: InferenceBackend,
+ flat: bool,
+ any_listed: bool,
+) -> None:
+ """List Google GenAI models."""
+ if importlib.util.find_spec("google.genai") is None:
+ lib_name = "google-genai"
+ lib_extra_name = "google"
+ msg = "The google-genai SDK is required to use Google GenAI models."
+ raise MissingDependencyError(
+ lib_name,
+ lib_extra_name,
+ msg,
+ )
+
+ from pipelex.plugins.google.google_factory import GoogleFactory # noqa: PLC0415
+
+ client = GoogleFactory.make_google_client(backend)
+ google_models: list[Any] = []
+ async for model in await client.aio.models.list():
+ google_models.append(model)
+
+ if flat:
+ _display_google_models_flat(
+ models=google_models,
+ sdk=sdk,
+ backend_name=backend_name,
+ any_listed=any_listed,
+ )
+ else:
+ _display_google_models_table(
+ models=google_models,
+ sdk=sdk,
+ backend_name=backend_name,
+ )
+
+
+def _display_google_models_flat(
+ models: list[Any],
+ sdk: str,
+ backend_name: str,
+ any_listed: bool,
+) -> None:
+ """Display Google GenAI models in CSV format."""
+ console = get_console()
+ if not any_listed:
+ console.print("model_name,display_name,description,sdk,backend")
+ for google_model in models:
+ model_name = google_model.name or "N/A"
+ display_name = google_model.display_name.replace(",", ";") if google_model.display_name else "N/A"
+ description = google_model.description.replace(",", ";").replace("\n", " ")[:100] if google_model.description else "N/A"
+ console.print(f"{model_name},{display_name},{description},{sdk},{backend_name}")
+
+
+def _display_google_models_table(
+ models: list[Any],
+ sdk: str,
+ backend_name: str,
+) -> None:
+ """Display Google GenAI models in table format."""
+ table = Table(
+ title=f"Available Models for Backend '{backend_name}' (SDK: {sdk})",
+ show_header=True,
+ header_style="bold cyan",
+ box=box.SQUARE_DOUBLE_HEAD,
+ )
+ table.add_column("Model Name", style="green")
+ table.add_column("Display Name", style="blue")
+ table.add_column("Description", style="yellow", max_width=60)
+
+ for google_model in models:
+ model_name = google_model.name or "N/A"
+ display_name = google_model.display_name or "N/A"
+ description = (
+ google_model.description[:100] + "..."
+ if google_model.description and len(google_model.description) > 100
+ else (google_model.description or "N/A")
+ )
+ table.add_row(model_name, display_name, description)
+
+ console = get_console()
+ console.print("\n")
+ console.print(table)
+ console.print("\n")
diff --git a/pipelex/plugins/google/google_llm_worker.py b/pipelex/plugins/google/google_llm_worker.py
index 3198e1cd9..010a6b328 100644
--- a/pipelex/plugins/google/google_llm_worker.py
+++ b/pipelex/plugins/google/google_llm_worker.py
@@ -101,13 +101,14 @@ class GoogleLLMWorker(LLMWorkerInternalAbstract):
llm_job: LLMJob,
) -> str:
"""Generate text using Google Gemini API."""
- # Prepare contents (text and images)
+ job_params = llm_job.applied_job_params or llm_job.job_params
+
contents = await GoogleFactory.prepare_user_contents(llm_job.llm_prompt)
# Build generation config
generation_config = types.GenerateContentConfig(
- temperature=llm_job.job_params.temperature,
- max_output_tokens=llm_job.job_params.max_tokens,
+ temperature=job_params.temperature,
+ max_output_tokens=job_params.max_tokens,
candidate_count=1, # Generate one candidate
)
@@ -151,14 +152,14 @@ class GoogleLLMWorker(LLMWorkerInternalAbstract):
schema: type[BaseModelTypeVar],
) -> BaseModelTypeVar:
"""Generate structured output using Google Gemini API with instructor."""
- # Prepare contents (text and images)
+ job_params = llm_job.applied_job_params or llm_job.job_params
contents = await GoogleFactory.prepare_user_contents(llm_job.llm_prompt)
# Build generation config
generation_config = types.GenerateContentConfig(
system_instruction=llm_job.llm_prompt.system_text,
- temperature=llm_job.job_params.temperature,
- max_output_tokens=llm_job.job_params.max_tokens,
+ temperature=job_params.temperature,
+ max_output_tokens=job_params.max_tokens,
candidate_count=1,
)
diff --git a/pipelex/plugins/mistral/mistral_factory.py b/pipelex/plugins/mistral/mistral_factory.py
index ea65210fa..01d595ef9 100644
--- a/pipelex/plugins/mistral/mistral_factory.py
+++ b/pipelex/plugins/mistral/mistral_factory.py
@@ -27,7 +27,7 @@ from pipelex.cogt.image.prompt_image import PromptImage, PromptImageBase64, Prom
from pipelex.cogt.llm.llm_job import LLMJob
from pipelex.cogt.model_backends.backend import InferenceBackend
from pipelex.cogt.usage.token_category import NbTokensByCategoryDict, TokenCategory
-from pipelex.plugins.openai.openai_factory import OpenAIFactory
+from pipelex.plugins.openai.openai_utils import make_image_url_obj
from pipelex.tools.misc.base_64_utils import load_binary_as_base64
from pipelex.tools.misc.filetype_utils import detect_file_type_from_base64, detect_file_type_from_path
@@ -48,15 +48,14 @@ class MistralFactory:
# Message
#########################################################
- @classmethod
- def make_simple_messages(cls, llm_job: LLMJob) -> list[Messages]:
+ def make_simple_messages(self, llm_job: LLMJob) -> list[Messages]:
"""Makes a list of messages with a system message (if provided) and followed by a user message."""
messages: list[Messages] = []
user_content: list[ContentChunk] = []
if user_text := llm_job.llm_prompt.user_text:
user_content.append(TextChunk(text=user_text))
if user_images := llm_job.llm_prompt.user_images:
- user_content.extend(cls.make_mistral_image_url(user_image) for user_image in user_images)
+ user_content.extend(self.make_mistral_image_url(user_image) for user_image in user_images)
if user_content:
messages.append(UserMessage(content=user_content))
@@ -65,8 +64,7 @@ class MistralFactory:
return messages
- @classmethod
- def make_mistral_image_url(cls, prompt_image: PromptImage) -> ImageURLChunk:
+ def make_mistral_image_url(self, prompt_image: PromptImage) -> ImageURLChunk:
if isinstance(prompt_image, PromptImageUrl):
return ImageURLChunk(image_url=prompt_image.url)
if isinstance(prompt_image, PromptImagePath):
@@ -80,9 +78,8 @@ class MistralFactory:
msg = f"prompt_image of type {type(prompt_image)} is not supported"
raise PromptImageFormatError(msg)
- @classmethod
- def make_simple_messages_openai_typed(
- cls,
+ async def make_simple_messages_openai_typed(
+ self,
llm_job: LLMJob,
) -> list[ChatCompletionMessageParam]:
"""Makes a list of messages with a system message (if provided) and followed by a user message."""
@@ -99,15 +96,14 @@ class MistralFactory:
if user_images := llm_prompt.user_images:
for prompt_image in user_images:
- openai_image_url = OpenAIFactory.make_openai_image_url(prompt_image=prompt_image)
- image_param = ChatCompletionContentPartImageParam(image_url=openai_image_url, type="image_url")
+ image_url_obj = await make_image_url_obj(prompt_image=prompt_image, detail=llm_job.job_params.image_detail)
+ image_param = ChatCompletionContentPartImageParam(image_url=image_url_obj, type="image_url")
user_contents.append(image_param)
messages.append(ChatCompletionUserMessageParam(role="user", content=user_contents))
return messages
- @staticmethod
- def make_nb_tokens_by_category(usage: UsageInfo) -> NbTokensByCategoryDict:
+ def make_nb_tokens_by_category(self, usage: UsageInfo) -> NbTokensByCategoryDict:
nb_tokens_by_category: NbTokensByCategoryDict = {
TokenCategory.INPUT: usage.prompt_tokens,
TokenCategory.OUTPUT: usage.completion_tokens,
diff --git a/pipelex/plugins/mistral/mistral_list.py b/pipelex/plugins/mistral/mistral_list.py
new file mode 100644
index 000000000..c5b5ab0a3
--- /dev/null
+++ b/pipelex/plugins/mistral/mistral_list.py
@@ -0,0 +1,90 @@
+from __future__ import annotations
+
+import importlib.util
+from typing import Any
+
+from rich import box
+from rich.table import Table
+
+from pipelex.cogt.exceptions import MissingDependencyError
+from pipelex.hub import get_console
+
+
+def list_mistral_models(
+ sdk: str,
+ backend_name: str,
+ flat: bool,
+ any_listed: bool,
+) -> None:
+ """List Mistral models."""
+ if importlib.util.find_spec("mistralai") is None:
+ lib_name = "mistralai"
+ lib_extra_name = "mistral"
+ msg = (
+ "The mistralai SDK is required in order to use Mistral models through the mistralai client. "
+ "However, you can use Mistral models through bedrock directly "
+ "by using the 'bedrock-mistral' llm family. (eg: bedrock-mistral-large)"
+ )
+ raise MissingDependencyError(
+ lib_name,
+ lib_extra_name,
+ msg,
+ )
+
+ from pipelex.plugins.mistral.mistral_llms import mistral_list_available_models # noqa: PLC0415
+
+ mistral_models = mistral_list_available_models()
+
+ if flat:
+ _display_mistral_models_flat(
+ models=mistral_models,
+ sdk=sdk,
+ backend_name=backend_name,
+ any_listed=any_listed,
+ )
+ else:
+ _display_mistral_models_table(
+ models=mistral_models,
+ sdk=sdk,
+ backend_name=backend_name,
+ )
+
+
+def _display_mistral_models_flat(
+ models: list[Any],
+ sdk: str,
+ backend_name: str,
+ any_listed: bool,
+) -> None:
+ """Display Mistral models in CSV format."""
+ console = get_console()
+ if not any_listed:
+ console.print("model_id,max_context_length,sdk,backend")
+ for mistral_model in models:
+ max_ctx = str(mistral_model.max_context_length) if mistral_model.max_context_length else "N/A"
+ console.print(f"{mistral_model.id},{max_ctx},{sdk},{backend_name}")
+
+
+def _display_mistral_models_table(
+ models: list[Any],
+ sdk: str,
+ backend_name: str,
+) -> None:
+ """Display Mistral models in table format."""
+ table = Table(
+ title=f"Available Models for Backend '{backend_name}' (SDK: {sdk})",
+ show_header=True,
+ header_style="bold cyan",
+ box=box.SQUARE_DOUBLE_HEAD,
+ )
+ table.add_column("Model ID", style="green")
+ table.add_column("Max Context Length", style="yellow")
+
+ for mistral_model in models:
+ max_ctx = str(mistral_model.max_context_length) if mistral_model.max_context_length else "N/A"
+ table.add_row(mistral_model.id, max_ctx)
+
+ console = get_console()
+ console.print("\n")
+ console.print(table)
+ console.print("\n")
diff --git a/pipelex/plugins/mistral/mistral_llm_worker.py b/pipelex/plugins/mistral/mistral_llm_worker.py
index 5ee5238b6..cd519cb8b 100644
--- a/pipelex/plugins/mistral/mistral_llm_worker.py
+++ b/pipelex/plugins/mistral/mistral_llm_worker.py
@@ -20,6 +20,7 @@ from pipelex.tools.typing.pydantic_utils import BaseModelTypeVar
class MistralLLMWorker(LLMWorkerInternalAbstract):
def __init__(
self,
+ mistral_factory: MistralFactory,
sdk_instance: Any,
inference_model: InferenceModelSpec,
reporting_delegate: ReportingProtocol | None = None,
@@ -40,6 +41,7 @@ class MistralLLMWorker(LLMWorkerInternalAbstract):
msg = f"No max_tokens provided for llm model '{self.inference_model.desc}', but it is required for Mistral"
raise MistralWorkerConfigurationError(msg)
self.mistral_client_for_text: Mistral = sdk_instance
+ self.mistral_factory = mistral_factory
if instructor_mode := self.inference_model.get_instructor_mode():
self.instructor_for_objects = instructor.from_mistral(client=sdk_instance, mode=instructor_mode, use_async=True)
@@ -51,12 +53,13 @@ class MistralLLMWorker(LLMWorkerInternalAbstract):
self,
llm_job: LLMJob,
) -> str:
- messages = MistralFactory.make_simple_messages(llm_job=llm_job)
+ job_params = llm_job.applied_job_params or llm_job.job_params
+ messages = self.mistral_factory.make_simple_messages(llm_job=llm_job)
response: ChatCompletionResponse | None = await self.mistral_client_for_text.chat.complete_async(
messages=messages,
model=self.inference_model.model_id,
- temperature=llm_job.job_params.temperature,
- max_tokens=llm_job.job_params.max_tokens or self.default_max_tokens,
+ temperature=job_params.temperature,
+ max_tokens=job_params.max_tokens or self.default_max_tokens,
)
if not response:
msg = "Mistral response is None"
@@ -70,7 +73,7 @@ class MistralLLMWorker(LLMWorkerInternalAbstract):
raise LLMCompletionError(msg)
if (llm_tokens_usage := llm_job.job_report.llm_tokens_usage) and (usage := response.usage):
- llm_tokens_usage.nb_tokens_by_category = MistralFactory.make_nb_tokens_by_category(usage=usage)
+ llm_tokens_usage.nb_tokens_by_category = self.mistral_factory.make_nb_tokens_by_category(usage=usage)
return mistral_response_content
@@ -80,14 +83,16 @@ class MistralLLMWorker(LLMWorkerInternalAbstract):
llm_job: LLMJob,
schema: type[BaseModelTypeVar],
) -> BaseModelTypeVar:
+ job_params = llm_job.applied_job_params or llm_job.job_params
+ messages = await self.mistral_factory.make_simple_messages_openai_typed(llm_job=llm_job)
result_object, completion = await self.instructor_for_objects.chat.completions.create_with_completion(
response_model=schema,
- messages=MistralFactory.make_simple_messages_openai_typed(llm_job=llm_job),
+ messages=messages,
model=self.inference_model.model_id,
- temperature=llm_job.job_params.temperature,
- max_tokens=llm_job.job_params.max_tokens or self.default_max_tokens,
+ temperature=job_params.temperature,
+ max_tokens=job_params.max_tokens or self.default_max_tokens,
)
if (llm_tokens_usage := llm_job.job_report.llm_tokens_usage) and (usage := completion.usage):
- llm_tokens_usage.nb_tokens_by_category = MistralFactory.make_nb_tokens_by_category(usage=usage)
+ llm_tokens_usage.nb_tokens_by_category = self.mistral_factory.make_nb_tokens_by_category(usage=usage)
return result_object
diff --git a/pipelex/plugins/openai/openai_client_factory.py b/pipelex/plugins/openai/openai_client_factory.py
new file mode 100644
index 000000000..5377fd23e
--- /dev/null
+++ b/pipelex/plugins/openai/openai_client_factory.py
@@ -0,0 +1,65 @@
+import openai
+
+from pipelex import log
+from pipelex.cogt.exceptions import CogtError
+from pipelex.cogt.model_backends.backend import InferenceBackend
+from pipelex.plugins.plugin_sdk_registry import Plugin
+from pipelex.types import StrEnum
+
+
+class OpenAIClientFactoryError(CogtError):
+ pass
+
+
+class OpenAISdkVariant(StrEnum):
+ AZURE_OPENAI = "azure_openai"
+ AZURE_OPENAI_RESPONSES = "azure_openai_responses"
+ OPENAI = "openai"
+ OPENAI_RESPONSES = "openai_responses"
+ OPENAI_IMG_GEN = "openai_img_gen"
+ OPENAI_ALT_IMG_GEN = "openai_alt_img_gen"
+
+
+class AzureExtraField(StrEnum):
+ API_VERSION = "api_version"
+
+
+class OpenAIClientFactory:
+ @classmethod
+ def make_openai_client(
+ cls,
+ plugin: Plugin,
+ backend: InferenceBackend,
+ ) -> openai.AsyncClient:
+ try:
+ sdk_variant = OpenAISdkVariant(plugin.sdk)
+ except ValueError as exc:
+ msg = f"Plugin '{plugin}' is not supported by '{cls.__name__}'"
+ raise OpenAIClientFactoryError(msg) from exc
+
+ # We have a workaround here:
+ # OpenAI can be used without any API key (for instance when pointing to local Ollama) but the SDK,
+ # as it is, raises if there is not API key (api_key is None and there is not env var).
+ # But it works fine with an empty string.
+ api_key = backend.api_key or ""
+
+ the_client: openai.AsyncOpenAI
+ match sdk_variant:
+ case OpenAISdkVariant.AZURE_OPENAI | OpenAISdkVariant.AZURE_OPENAI_RESPONSES:
+ log.verbose(f"Making AsyncOpenAI client with endpoint: {backend.endpoint}")
+ if backend.endpoint is None:
+ msg = "Azure OpenAI endpoint is not set"
+ raise OpenAIClientFactoryError(msg)
+ the_client = openai.AsyncAzureOpenAI(
+ azure_endpoint=backend.endpoint,
+ api_key=api_key,
+ api_version=backend.get_extra_config(AzureExtraField.API_VERSION),
+ )
+ case OpenAISdkVariant.OPENAI | OpenAISdkVariant.OPENAI_RESPONSES | OpenAISdkVariant.OPENAI_IMG_GEN | OpenAISdkVariant.OPENAI_ALT_IMG_GEN:
+ log.verbose(f"Making AsyncOpenAI client with endpoint: {backend.endpoint}")
+ the_client = openai.AsyncOpenAI(
+ api_key=api_key,
+ base_url=backend.endpoint,
+ )
+
+ return the_client
diff --git a/pipelex/plugins/openai/openai_completions_factory.py b/pipelex/plugins/openai/openai_completions_factory.py
new file mode 100644
index 000000000..b4ae2c1b9
--- /dev/null
+++ b/pipelex/plugins/openai/openai_completions_factory.py
@@ -0,0 +1,78 @@
+from typing import Any
+
+from openai.types.chat import (
+ ChatCompletionContentPartImageParam,
+ ChatCompletionContentPartParam,
+ ChatCompletionContentPartTextParam,
+ ChatCompletionMessageParam,
+ ChatCompletionSystemMessageParam,
+ ChatCompletionUserMessageParam,
+)
+from openai.types.chat.chat_completion_content_part_image_param import ImageURL
+from openai.types.completion_usage import CompletionUsage
+from typing_extensions import override
+
+from pipelex.cogt.image.prompt_image import PromptImageDetail, PromptImageTypedBase64
+from pipelex.cogt.image.prompt_image_factory import PromptImageFactory
+from pipelex.cogt.image.prompt_image_utils import prep_prompt_images
+from pipelex.cogt.llm.llm_job import LLMJob
+from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
+from pipelex.cogt.usage.token_category import NbTokensByCategoryDict, TokenCategory
+from pipelex.plugins.plugin_factory_abstract import PluginFactoryAbstract
+
+
+class OpenAICompletionsFactory(PluginFactoryAbstract):
+ def __init__(self, is_http_url_enabled: bool):
+ super().__init__()
+ self.is_http_url_enabled = is_http_url_enabled
+
+ async def make_simple_messages(
+ self,
+ llm_job: LLMJob,
+ ) -> list[ChatCompletionMessageParam]:
+ """Makes a list of messages with a system message (if provided) and followed by a user message."""
+ llm_prompt = llm_job.llm_prompt
+ messages: list[ChatCompletionMessageParam] = []
+ user_contents: list[ChatCompletionContentPartParam] = []
+ if system_content := llm_prompt.system_text:
+ messages.append(ChatCompletionSystemMessageParam(role="system", content=system_content))
+ # TODO: confirm that we can prompt without user_contents, for instance if we have only images,
+ # otherwise consider using a default user_content
+ if user_prompt_text := llm_prompt.user_text:
+ user_part_text = ChatCompletionContentPartTextParam(text=user_prompt_text, type="text")
+ user_contents.append(user_part_text)
+ if llm_prompt.user_images:
+ detail = llm_job.job_params.image_detail or PromptImageDetail.AUTO
+ prepped_images = await prep_prompt_images(prompt_images=llm_prompt.user_images, is_http_url_enabled=self.is_http_url_enabled)
+ for prepped_image in prepped_images:
+ if isinstance(prepped_image, str):
+ url = prepped_image
+ else:
+ assert isinstance(prepped_image, PromptImageTypedBase64)
+ url = PromptImageFactory.make_base_64_url_from_prompt_image_typed_base64(prompt_image=prepped_image)
+
+ image_url_obj = ImageURL(url=url, detail=detail.as_openai_detail)
+ image_param = ChatCompletionContentPartImageParam(image_url=image_url_obj, type="image_url")
+ user_contents.append(image_param)
+
+ messages.append(ChatCompletionUserMessageParam(role="user", content=user_contents))
+ return messages
+
+ def make_nb_tokens_by_category(self, usage: CompletionUsage) -> NbTokensByCategoryDict:
+ nb_tokens_by_category: NbTokensByCategoryDict = {
+ TokenCategory.INPUT: usage.prompt_tokens,
+ TokenCategory.OUTPUT: usage.completion_tokens,
+ }
+ if prompt_tokens_details := usage.prompt_tokens_details:
+ nb_tokens_by_category[TokenCategory.INPUT_AUDIO] = prompt_tokens_details.audio_tokens or 0
+ nb_tokens_by_category[TokenCategory.INPUT_CACHED] = prompt_tokens_details.cached_tokens or 0
+ if completion_tokens_details := usage.completion_tokens_details:
+ nb_tokens_by_category[TokenCategory.OUTPUT_AUDIO] = completion_tokens_details.audio_tokens or 0
+ nb_tokens_by_category[TokenCategory.OUTPUT_REASONING] = completion_tokens_details.reasoning_tokens or 0
+ nb_tokens_by_category[TokenCategory.OUTPUT_ACCEPTED_PREDICTION] = completion_tokens_details.accepted_prediction_tokens or 0
+ nb_tokens_by_category[TokenCategory.OUTPUT_REJECTED_PREDICTION] = completion_tokens_details.rejected_prediction_tokens or 0
+ return nb_tokens_by_category
+
+ @override
+ def make_extras(self, inference_model: InferenceModelSpec, llm_job: LLMJob, output_desc: str) -> tuple[dict[str, str], dict[str, Any]]:
+ return inference_model.extra_headers or {}, {}
diff --git a/pipelex/plugins/openai/openai_llm_worker.py b/pipelex/plugins/openai/openai_completions_llm_worker.py
similarity index 56%
rename from pipelex/plugins/openai/openai_llm_worker.py
rename to pipelex/plugins/openai/openai_completions_llm_worker.py
index 27ed0279c..9bc06f4f2 100644
--- a/pipelex/plugins/openai/openai_llm_worker.py
+++ b/pipelex/plugins/openai/openai_completions_llm_worker.py
@@ -3,28 +3,28 @@ from typing import TYPE_CHECKING, Any
import instructor
import openai
from instructor.exceptions import InstructorRetryException
-from openai import NOT_GIVEN, APIConnectionError, BadRequestError, NotFoundError, omit
+from openai import NOT_GIVEN, APIConnectionError, AuthenticationError, BadRequestError, NotFoundError, omit
if TYPE_CHECKING:
from openai.types.chat import ChatCompletionMessage
from typing_extensions import override
-from pipelex import log
-from pipelex.cogt.exceptions import LLMCompletionError, LLMModelNotFoundError, SdkTypeError
+from pipelex.cogt.exceptions import LLMCompletionError, SdkTypeError
from pipelex.cogt.llm.llm_job import LLMJob
from pipelex.cogt.llm.llm_utils import dump_error, dump_kwargs, dump_response_from_structured_gen
from pipelex.cogt.llm.llm_worker_internal_abstract import LLMWorkerInternalAbstract
-from pipelex.cogt.model_backends.model_constraints import ModelConstraints
from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
from pipelex.config import get_config
-from pipelex.plugins.openai.openai_factory import OpenAIFactory
+from pipelex.plugins.openai.openai_completions_factory import OpenAICompletionsFactory
from pipelex.reporting.reporting_protocol import ReportingProtocol
+from pipelex.system.telemetry.otel_constants import LLMOutputType
from pipelex.tools.typing.pydantic_utils import BaseModelTypeVar
-class OpenAILLMWorker(LLMWorkerInternalAbstract):
+class OpenAICompletionsLLMWorker(LLMWorkerInternalAbstract):
def __init__(
self,
+ openai_completions_factory: OpenAICompletionsFactory,
sdk_instance: Any,
inference_model: InferenceModelSpec,
reporting_delegate: ReportingProtocol | None = None,
@@ -40,6 +40,7 @@ class OpenAILLMWorker(LLMWorkerInternalAbstract):
raise SdkTypeError(msg)
self.openai_client_for_text: openai.AsyncOpenAI = sdk_instance
+ self.openai_completions_factory = openai_completions_factory
if instructor_mode := self.inference_model.get_instructor_mode():
self.instructor_for_objects = instructor.from_openai(client=sdk_instance, mode=instructor_mode)
else:
@@ -67,34 +68,34 @@ class OpenAILLMWorker(LLMWorkerInternalAbstract):
self,
llm_job: LLMJob,
) -> str:
- messages = OpenAIFactory.make_simple_messages(llm_job=llm_job)
+ job_params = llm_job.applied_job_params or llm_job.job_params
+ messages = await self.openai_completions_factory.make_simple_messages(llm_job=llm_job)
try:
- temperature = llm_job.job_params.temperature
- if ModelConstraints.TEMPERATURE_MUST_BE_MULTIPLIED_BY_2 in self.inference_model.constraints:
- temperature *= 2
- if ModelConstraints.TEMPERATURE_MUST_BE_1 in self.inference_model.constraints and temperature != 1:
- log.warning(
- f"Model {self.inference_model.desc} used with temperature {temperature}, but it must be 1 for this model so we forced it to 1"
- )
- temperature = 1
+ extra_headers, extra_body = self.openai_completions_factory.make_extras(
+ inference_model=self.inference_model, llm_job=llm_job, output_desc=LLMOutputType.TEXT
+ )
response = await self.openai_client_for_text.chat.completions.create(
model=self.inference_model.model_id,
- temperature=temperature,
- max_tokens=llm_job.job_params.max_tokens or omit,
- seed=llm_job.job_params.seed,
+ temperature=job_params.temperature,
+ max_tokens=job_params.max_tokens or omit,
+ seed=job_params.seed,
messages=messages,
+ extra_headers=extra_headers,
+ extra_body=extra_body,
)
- except NotFoundError as not_found_error:
- # TODO: record llm config so it can be displayed here
- msg = f"OpenAI model or deployment not found:\n{self.inference_model.desc}\nmodel: {self.inference_model.desc}\n{not_found_error}"
- raise LLMModelNotFoundError(msg) from not_found_error
+ except NotFoundError as exc:
+ msg = f"LLM model or deployment '{self.inference_model.model_id}' not found: {exc}"
+ raise LLMCompletionError(msg) from exc
except APIConnectionError as api_connection_error:
- msg = f"OpenAI API connection error: {api_connection_error}"
+ msg = f"LLM API connection error: {api_connection_error}"
raise LLMCompletionError(msg) from api_connection_error
except BadRequestError as bad_request_error:
- msg = f"OpenAI bad request error with model: {self.inference_model.desc}:\n{bad_request_error}"
+ msg = f"LLM bad request error with model: {self.inference_model.desc}:\n{bad_request_error}"
raise LLMCompletionError(msg) from bad_request_error
+ except AuthenticationError as authentication_error:
+ msg = f"LLM authentication error: {authentication_error}"
+ raise LLMCompletionError(msg) from authentication_error
openai_message: ChatCompletionMessage = response.choices[0].message
response_text = openai_message.content
@@ -103,7 +104,7 @@ class OpenAILLMWorker(LLMWorkerInternalAbstract):
raise LLMCompletionError(msg)
if (llm_tokens_usage := llm_job.job_report.llm_tokens_usage) and (usage := response.usage):
- llm_tokens_usage.nb_tokens_by_category = OpenAIFactory.make_nb_tokens_by_category(usage=usage)
+ llm_tokens_usage.nb_tokens_by_category = self.openai_completions_factory.make_nb_tokens_by_category(usage=usage)
return response_text
@override
@@ -112,37 +113,44 @@ class OpenAILLMWorker(LLMWorkerInternalAbstract):
llm_job: LLMJob,
schema: type[BaseModelTypeVar],
) -> BaseModelTypeVar:
- messages = OpenAIFactory.make_simple_messages(llm_job=llm_job)
+ job_params = llm_job.applied_job_params or llm_job.job_params
+ messages = await self.openai_completions_factory.make_simple_messages(llm_job=llm_job)
try:
- temperature = llm_job.job_params.temperature
- if ModelConstraints.TEMPERATURE_MUST_BE_MULTIPLIED_BY_2 in self.inference_model.constraints:
- temperature *= 2
- if ModelConstraints.TEMPERATURE_MUST_BE_1 in self.inference_model.constraints and temperature != 1:
- log.warning(
- f"Model {self.inference_model.desc} used with temperature {temperature}, but it must be 1 for this model so we forced it to 1"
- )
- temperature = 1
try:
+ extra_headers, extra_body = self.openai_completions_factory.make_extras(
+ inference_model=self.inference_model, llm_job=llm_job, output_desc=schema.__name__
+ )
result_object, completion = await self.instructor_for_objects.chat.completions.create_with_completion(
model=self.inference_model.model_id,
- temperature=temperature,
- max_tokens=llm_job.job_params.max_tokens or NOT_GIVEN,
- seed=llm_job.job_params.seed,
+ temperature=job_params.temperature,
+ max_tokens=job_params.max_tokens or NOT_GIVEN,
+ seed=job_params.seed,
messages=messages,
response_model=schema,
max_retries=llm_job.job_config.max_retries,
+ extra_headers=extra_headers,
+ extra_body=extra_body,
)
except InstructorRetryException as exc:
- msg = f"OpenAI instructor failed with model: {self.inference_model.desc} trying to generate schema: {schema} with error: {exc}"
+ msg = (
+ f"LLM structured generation via 'instructor' failed with model: {self.inference_model.desc} "
+ f"trying to generate schema: {schema} with error: {exc}"
+ )
raise LLMCompletionError(msg) from exc
except NotFoundError as exc:
- msg = f"OpenAI model or deployment '{self.inference_model.model_id}' not found: {exc}"
+ msg = f"LLM model or deployment '{self.inference_model.model_id}' not found: {exc}"
raise LLMCompletionError(msg) from exc
+ except APIConnectionError as api_connection_error:
+ msg = f"LLM API connection error: {api_connection_error}"
+ raise LLMCompletionError(msg) from api_connection_error
except BadRequestError as bad_request_error:
- msg = f"OpenAI bad request error with model: {self.inference_model.desc}:\n{bad_request_error}"
+ msg = f"LLM bad request error with model: {self.inference_model.desc}:\n{bad_request_error}"
raise LLMCompletionError(msg) from bad_request_error
+ except AuthenticationError as authentication_error:
+ msg = f"LLM authentication error: {authentication_error}"
+ raise LLMCompletionError(msg) from authentication_error
if (llm_tokens_usage := llm_job.job_report.llm_tokens_usage) and (usage := completion.usage):
- llm_tokens_usage.nb_tokens_by_category = OpenAIFactory.make_nb_tokens_by_category(usage=usage)
+ llm_tokens_usage.nb_tokens_by_category = self.openai_completions_factory.make_nb_tokens_by_category(usage=usage)
return result_object
diff --git a/pipelex/plugins/openai/openai_constants.py b/pipelex/plugins/openai/openai_constants.py
new file mode 100644
index 000000000..e0f28324d
--- /dev/null
+++ b/pipelex/plugins/openai/openai_constants.py
@@ -0,0 +1,5 @@
+from pipelex.types import StrEnum
+
+
+class OpenAIBodyKey(StrEnum):
+ MAX_TOKENS = "max_tokens"
diff --git a/pipelex/plugins/openai/openai_factory.py b/pipelex/plugins/openai/openai_factory.py
deleted file mode 100644
index 6543ae78e..000000000
--- a/pipelex/plugins/openai/openai_factory.py
+++ /dev/null
@@ -1,164 +0,0 @@
-import openai
-from openai.types.chat import (
- ChatCompletionContentPartImageParam,
- ChatCompletionContentPartParam,
- ChatCompletionContentPartTextParam,
- ChatCompletionMessageParam,
- ChatCompletionSystemMessageParam,
- ChatCompletionUserMessageParam,
-)
-from openai.types.chat.chat_completion_content_part_image_param import ImageURL
-from openai.types.completion_usage import CompletionUsage
-
-from pipelex import log
-from pipelex.cogt.exceptions import CogtError, LLMPromptParameterError
-from pipelex.cogt.image.prompt_image import PromptImage, PromptImageBase64, PromptImagePath, PromptImageUrl
-from pipelex.cogt.llm.llm_job import LLMJob
-from pipelex.cogt.model_backends.backend import InferenceBackend
-from pipelex.cogt.usage.token_category import NbTokensByCategoryDict, TokenCategory
-from pipelex.plugins.plugin_sdk_registry import Plugin
-from pipelex.tools.misc.base_64_utils import load_binary_as_base64
-from pipelex.types import StrEnum
-
-
-class OpenAIFactoryError(CogtError):
- pass
-
-
-class OpenAISdkVariant(StrEnum):
- AZURE_OPENAI = "azure_openai"
- OPENAI = "openai"
- OPENAI_ALT_IMG_GEN = "openai_alt_img_gen"
-
-
-class AzureExtraField(StrEnum):
- API_VERSION = "api_version"
-
-
-class OpenAIFactory:
- @classmethod
- def make_openai_client(
- cls,
- plugin: Plugin,
- backend: InferenceBackend,
- ) -> openai.AsyncClient:
- try:
- sdk_variant = OpenAISdkVariant(plugin.sdk)
- except ValueError as exc:
- msg = f"Plugin '{plugin}' is not supported by OpenAIFactory"
- raise OpenAIFactoryError(msg) from exc
-
- # We have a workaround here:
- # OpenAI can be used without any API key (for instance when pointing to local Ollama) but the SDK,
- # as it is, raises if there is not API key (api_key is None and there is not env var).
- # But it works fine with an empty string.
- api_key = backend.api_key or ""
-
- the_client: openai.AsyncOpenAI
- match sdk_variant:
- case OpenAISdkVariant.AZURE_OPENAI:
- log.verbose(f"Making AsyncOpenAI client with endpoint: {backend.endpoint}")
- if backend.endpoint is None:
- msg = "Azure OpenAI endpoint is not set"
- raise OpenAIFactoryError(msg)
- the_client = openai.AsyncAzureOpenAI(
- azure_endpoint=backend.endpoint,
- api_key=api_key,
- api_version=backend.get_extra_config(AzureExtraField.API_VERSION),
- )
- case OpenAISdkVariant.OPENAI:
- log.verbose(f"Making AsyncOpenAI client with endpoint: {backend.endpoint}")
- the_client = openai.AsyncOpenAI(
- api_key=api_key,
- base_url=backend.endpoint,
- )
- case OpenAISdkVariant.OPENAI_ALT_IMG_GEN:
- log.verbose(f"Making AsyncOpenAI client with endpoint: {backend.endpoint}")
- the_client = openai.AsyncOpenAI(
- api_key=api_key,
- base_url=backend.endpoint,
- )
-
- return the_client
-
- @classmethod
- def make_simple_messages(
- cls,
- llm_job: LLMJob,
- ) -> list[ChatCompletionMessageParam]:
- """Makes a list of messages with a system message (if provided) and followed by a user message."""
- llm_prompt = llm_job.llm_prompt
- messages: list[ChatCompletionMessageParam] = []
- user_contents: list[ChatCompletionContentPartParam] = []
- if system_content := llm_prompt.system_text:
- messages.append(ChatCompletionSystemMessageParam(role="system", content=system_content))
- # TODO: confirm that we can prompt without user_contents, for instance if we have only images,
- # otherwise consider using a default user_content
- if user_prompt_text := llm_prompt.user_text:
- user_part_text = ChatCompletionContentPartTextParam(text=user_prompt_text, type="text")
- user_contents.append(user_part_text)
- if llm_prompt.user_images:
- for prompt_image in llm_prompt.user_images:
- openai_image_url = cls.make_openai_image_url(prompt_image=prompt_image)
- image_param = ChatCompletionContentPartImageParam(image_url=openai_image_url, type="image_url")
- user_contents.append(image_param)
-
- messages.append(ChatCompletionUserMessageParam(role="user", content=user_contents))
- return messages
-
- @classmethod
- def make_openai_image_url(cls, prompt_image: PromptImage) -> ImageURL:
- if isinstance(prompt_image, PromptImageUrl):
- url = prompt_image.url
- openai_image_url = ImageURL(url=url, detail="high")
- elif isinstance(prompt_image, PromptImageBase64):
- # TODO: manage image type
- url_with_bytes: str = f"data:image/jpeg;base64,{prompt_image.base_64.decode('utf-8')}"
- openai_image_url = ImageURL(url=url_with_bytes, detail="high")
- elif isinstance(prompt_image, PromptImagePath):
- image_bytes = load_binary_as_base64(path=prompt_image.file_path)
- return cls.make_openai_image_url(PromptImageBase64(base_64=image_bytes))
- else:
- msg = f"prompt_image of type {type(prompt_image)} is not supported"
- raise LLMPromptParameterError(msg)
- return openai_image_url
-
- @staticmethod
- def make_openai_error_info(exception: Exception) -> str:
- error_mapping: dict[type, str] = {
- openai.BadRequestError: "OpenAI API request was invalid.",
- openai.InternalServerError: "OpenAI is having trouble. Please try again later.",
- openai.RateLimitError: "OpenAI API request exceeded rate limit.",
- openai.AuthenticationError: "OpenAI API request was not authorized.",
- openai.PermissionDeniedError: "OpenAI API request was not permitted.",
- openai.NotFoundError: "Requested resource not found.",
- openai.APITimeoutError: "OpenAI API request timed out.",
- openai.APIConnectionError: "OpenAI API request failed to connect.",
- openai.APIError: "OpenAI API returned an API Error.",
- }
- return error_mapping.get(type(exception), "An unexpected error occurred with the OpenAI API.")
-
- # reference:
- # https://help.openai.com/en/articles/5247780-using-logit-bias-to-define-token-probability
- # https://platform.openai.com/tokenizer
- @staticmethod
- def make_logit_bias(nb_items: int, weight: int = 100) -> dict[str, int]:
- logit_bias = {str(item): weight for item in range(15, 15 + nb_items + 1)}
- log.verbose(f"logit_bias: {logit_bias}")
- return logit_bias
-
- @staticmethod
- def make_nb_tokens_by_category(usage: CompletionUsage) -> NbTokensByCategoryDict:
- nb_tokens_by_category: NbTokensByCategoryDict = {
- TokenCategory.INPUT: usage.prompt_tokens,
- TokenCategory.OUTPUT: usage.completion_tokens,
- }
- if prompt_tokens_details := usage.prompt_tokens_details:
- nb_tokens_by_category[TokenCategory.INPUT_AUDIO] = prompt_tokens_details.audio_tokens or 0
- nb_tokens_by_category[TokenCategory.INPUT_CACHED] = prompt_tokens_details.cached_tokens or 0
- if completion_tokens_details := usage.completion_tokens_details:
- nb_tokens_by_category[TokenCategory.OUTPUT_AUDIO] = completion_tokens_details.audio_tokens or 0
- nb_tokens_by_category[TokenCategory.OUTPUT_REASONING] = completion_tokens_details.reasoning_tokens or 0
- nb_tokens_by_category[TokenCategory.OUTPUT_ACCEPTED_PREDICTION] = completion_tokens_details.accepted_prediction_tokens or 0
- nb_tokens_by_category[TokenCategory.OUTPUT_REJECTED_PREDICTION] = completion_tokens_details.rejected_prediction_tokens or 0
- return nb_tokens_by_category
diff --git a/pipelex/plugins/openai/openai_list.py b/pipelex/plugins/openai/openai_list.py
new file mode 100644
index 000000000..2ee470d03
--- /dev/null
+++ b/pipelex/plugins/openai/openai_list.py
@@ -0,0 +1,95 @@
+from __future__ import annotations
+
+from datetime import datetime
+from typing import TYPE_CHECKING
+
+from rich import box
+from rich.table import Table
+
+from pipelex.hub import get_console
+from pipelex.plugins.openai.openai_llms import openai_list_available_models
+from pipelex.plugins.plugin_sdk_registry import Plugin
+
+if TYPE_CHECKING:
+ from openai.types import Model
+
+ from pipelex.cogt.model_backends.backend import InferenceBackend
+
+
+async def list_openai_models(
+ sdk: str,
+ backend_name: str,
+ backend: InferenceBackend,
+ flat: bool,
+ any_listed: bool,
+) -> None:
+ """List OpenAI models."""
+ plugin = Plugin(sdk=sdk, backend=backend_name)
+ openai_models = await openai_list_available_models(
+ plugin=plugin,
+ backend=backend,
+ )
+
+ if flat:
+ _display_openai_models_flat(
+ models=openai_models,
+ sdk=sdk,
+ backend_name=backend_name,
+ any_listed=any_listed,
+ )
+ else:
+ _display_openai_models_table(
+ models=openai_models,
+ sdk=sdk,
+ backend_name=backend_name,
+ )
+
+
+def _display_openai_models_flat(
+ models: list[Model],
+ sdk: str,
+ backend_name: str,
+ any_listed: bool,
+) -> None:
+ """Display OpenAI models in CSV format."""
+ console = get_console()
+ if not any_listed:
+ console.print("model_id,created,owned_by,sdk,backend")
+ for model in models:
+ # Convert Unix timestamp to formatted date
+ if hasattr(model, "created") and model.created:
+ created = datetime.fromtimestamp(model.created).strftime("%Y-%m-%d") # noqa: DTZ006
+ else:
+ created = "N/A"
+ owned_by = model.owned_by if hasattr(model, "owned_by") else "N/A"
+ console.print(f"{model.id},{created},{owned_by},{sdk},{backend_name}")
+
+
+def _display_openai_models_table(
+ models: list[Model],
+ sdk: str,
+ backend_name: str,
+) -> None:
+ """Display OpenAI models in table format."""
+ table = Table(
+ title=f"Available Models for Backend '{backend_name}' (SDK: {sdk})",
+ show_header=True,
+ header_style="bold cyan",
+ box=box.SQUARE_DOUBLE_HEAD,
+ )
+ table.add_column("Model ID", style="green")
+ table.add_column("Created", style="yellow")
+ table.add_column("Owned By", style="blue")
+
+ for model in models:
+ # Convert Unix timestamp to formatted date
+ if hasattr(model, "created") and model.created:
+ created = datetime.fromtimestamp(model.created).strftime("%Y-%m-%d") # noqa: DTZ006
+ else:
+ created = "N/A"
+ owned_by = model.owned_by if hasattr(model, "owned_by") else "N/A"
+ table.add_row(model.id, created, owned_by)
+ console = get_console()
+ console.print("\n")
+ console.print(table)
+ console.print("\n")
diff --git a/pipelex/plugins/openai/openai_llms.py b/pipelex/plugins/openai/openai_llms.py
index d790e3fe3..e7974d6bf 100644
--- a/pipelex/plugins/openai/openai_llms.py
+++ b/pipelex/plugins/openai/openai_llms.py
@@ -1,7 +1,7 @@
from openai.types import Model
from pipelex.cogt.model_backends.backend import InferenceBackend
-from pipelex.plugins.openai.openai_factory import OpenAIFactory
+from pipelex.plugins.openai.openai_client_factory import OpenAIClientFactory
from pipelex.plugins.plugin_sdk_registry import Plugin
@@ -9,7 +9,7 @@ async def openai_list_available_models(
plugin: Plugin,
backend: InferenceBackend,
) -> list[Model]:
- openai_client_async = OpenAIFactory.make_openai_client(
+ openai_client_async = OpenAIClientFactory.make_openai_client(
plugin=plugin,
backend=backend,
)
diff --git a/pipelex/plugins/openai/openai_responses_factory.py b/pipelex/plugins/openai/openai_responses_factory.py
new file mode 100644
index 000000000..ae62eb5e0
--- /dev/null
+++ b/pipelex/plugins/openai/openai_responses_factory.py
@@ -0,0 +1,80 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+from openai.types.responses import ResponseInputImageParam
+from typing_extensions import override
+
+from pipelex.cogt.exceptions import LLMPromptParameterError
+from pipelex.cogt.image.prompt_image import PromptImageDetail, PromptImageTypedBase64
+from pipelex.cogt.image.prompt_image_factory import PromptImageFactory
+from pipelex.cogt.image.prompt_image_utils import prep_prompt_images
+from pipelex.cogt.llm.llm_job import LLMJob
+from pipelex.cogt.usage.token_category import NbTokensByCategoryDict, TokenCategory
+from pipelex.plugins.plugin_factory_abstract import PluginFactoryAbstract
+
+if TYPE_CHECKING:
+ from openai.types.responses import (
+ ResponseInputItemParam,
+ ResponseInputMessageContentListParam,
+ ResponseInputTextParam,
+ ResponseUsage,
+ )
+
+ from pipelex.cogt.llm.llm_job import LLMJob
+ from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
+
+
+class OpenAIResponsesFactory(PluginFactoryAbstract):
+ def __init__(self, is_http_url_enabled: bool):
+ super().__init__()
+ self.is_http_url_enabled = is_http_url_enabled
+
+ async def make_input_items(self, llm_job: LLMJob) -> list[ResponseInputItemParam]:
+ """Build Response API input items from a standard LLM job prompt."""
+ llm_prompt = llm_job.llm_prompt
+ input_items: list[ResponseInputItemParam] = []
+
+ user_contents: ResponseInputMessageContentListParam = []
+ if llm_prompt.user_text:
+ text_content: ResponseInputTextParam = {"type": "input_text", "text": llm_prompt.user_text}
+ user_contents.append(text_content)
+
+ detail = llm_job.job_params.image_detail or PromptImageDetail.AUTO
+ prepped_images = await prep_prompt_images(prompt_images=llm_prompt.user_images, is_http_url_enabled=self.is_http_url_enabled)
+ for prepped_image in prepped_images:
+ if isinstance(prepped_image, str):
+ url = prepped_image
+ else:
+ assert isinstance(prepped_image, PromptImageTypedBase64)
+ url = PromptImageFactory.make_base_64_url_from_prompt_image_typed_base64(prompt_image=prepped_image)
+
+ image_param = ResponseInputImageParam(type="input_image", image_url=url, detail=detail.as_openai_detail)
+ user_contents.append(image_param)
+
+ if not user_contents:
+ msg = "LLM prompt must include text or images for the user input when using the OpenAI Responses API"
+ raise LLMPromptParameterError(msg)
+
+ input_items.append(
+ {
+ "role": "user",
+ "content": user_contents,
+ }
+ )
+ return input_items
+
+ def make_nb_tokens_by_category(self, usage: ResponseUsage) -> NbTokensByCategoryDict:
+ nb_tokens_by_category: NbTokensByCategoryDict = {
+ TokenCategory.INPUT: usage.input_tokens,
+ TokenCategory.OUTPUT: usage.output_tokens,
+ }
+ if usage.input_tokens_details:
+ nb_tokens_by_category[TokenCategory.INPUT_CACHED] = usage.input_tokens_details.cached_tokens
+ if usage.output_tokens_details:
+ nb_tokens_by_category[TokenCategory.OUTPUT_REASONING] = usage.output_tokens_details.reasoning_tokens
+ return nb_tokens_by_category
+
+ @override
+ def make_extras(self, inference_model: InferenceModelSpec, llm_job: LLMJob, output_desc: str) -> tuple[dict[str, str], dict[str, Any]]:
+ return inference_model.extra_headers or {}, {}
diff --git a/pipelex/plugins/openai/openai_responses_llm_worker.py b/pipelex/plugins/openai/openai_responses_llm_worker.py
new file mode 100644
index 000000000..e56e0fa02
--- /dev/null
+++ b/pipelex/plugins/openai/openai_responses_llm_worker.py
@@ -0,0 +1,155 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, cast
+
+import instructor
+import openai
+from instructor.exceptions import InstructorRetryException
+from openai import NOT_GIVEN, APIConnectionError, AuthenticationError, BadRequestError, NotFoundError, omit
+from typing_extensions import override
+
+from pipelex.cogt.exceptions import LLMCompletionError, LLMModelNotFoundError, SdkTypeError
+from pipelex.cogt.llm.llm_utils import dump_error, dump_kwargs, dump_response_from_structured_gen
+from pipelex.cogt.llm.llm_worker_internal_abstract import LLMWorkerInternalAbstract
+from pipelex.config import get_config
+from pipelex.system.telemetry.otel_constants import LLMOutputType
+
+if TYPE_CHECKING:
+ from openai.types.chat import ChatCompletionMessageParam
+
+ from pipelex.cogt.llm.llm_job import LLMJob
+ from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
+ from pipelex.plugins.openai.openai_responses_factory import OpenAIResponsesFactory
+ from pipelex.reporting.reporting_protocol import ReportingProtocol
+ from pipelex.tools.typing.pydantic_utils import BaseModelTypeVar
+
+
+class OpenAIResponsesLLMWorker(LLMWorkerInternalAbstract):
+ def __init__(
+ self,
+ openai_responses_factory: OpenAIResponsesFactory,
+ sdk_instance: Any,
+ inference_model: InferenceModelSpec,
+ reporting_delegate: ReportingProtocol | None = None,
+ ):
+ super().__init__(inference_model=inference_model, reporting_delegate=reporting_delegate)
+
+ if not isinstance(sdk_instance, openai.AsyncOpenAI):
+ msg = f"Provided LLM sdk_instance for {self.__class__.__name__} is not of type openai.AsyncOpenAI: it's a '{type(sdk_instance)}'"
+ raise SdkTypeError(msg)
+
+ self.openai_client_for_responses: openai.AsyncOpenAI = sdk_instance
+ self.openai_responses_factory = openai_responses_factory
+
+ if instructor_mode := self.inference_model.get_instructor_mode():
+ self.instructor_for_objects = instructor.from_openai(client=sdk_instance, mode=instructor_mode)
+ else:
+ self.instructor_for_objects = instructor.from_openai(client=sdk_instance)
+
+ instructor_config = get_config().cogt.llm_config.instructor_config
+ if instructor_config.is_dump_kwargs_enabled:
+ self.instructor_for_objects.on(hook_name="completion:kwargs", handler=dump_kwargs)
+ if instructor_config.is_dump_response_enabled:
+ self.instructor_for_objects.on(hook_name="completion:response", handler=dump_response_from_structured_gen)
+ if instructor_config.is_dump_error_enabled:
+ self.instructor_for_objects.on(hook_name="completion:error", handler=dump_error)
+
+ #########################################################
+ @override
+ def setup(self):
+ pass
+
+ @override
+ def teardown(self):
+ pass
+
+ #########################################################
+ @override
+ async def _gen_text(
+ self,
+ llm_job: LLMJob,
+ ) -> str:
+ job_params = llm_job.applied_job_params or llm_job.job_params
+ input_items = await self.openai_responses_factory.make_input_items(llm_job=llm_job)
+ try:
+ extra_headers, extra_body = self.openai_responses_factory.make_extras(
+ inference_model=self.inference_model, llm_job=llm_job, output_desc=LLMOutputType.TEXT
+ )
+ response = await self.openai_client_for_responses.responses.create(
+ model=self.inference_model.model_id,
+ instructions=llm_job.llm_prompt.system_text,
+ temperature=job_params.temperature,
+ max_output_tokens=job_params.max_tokens or omit,
+ input=input_items,
+ extra_headers=extra_headers,
+ extra_body=extra_body,
+ )
+ except NotFoundError as not_found_error:
+ msg = (
+ f"OpenAI Responses model or deployment not found:\n{self.inference_model.desc}\nmodel: {self.inference_model.desc}\n{not_found_error}"
+ )
+ raise LLMModelNotFoundError(msg) from not_found_error
+ except APIConnectionError as api_connection_error:
+ msg = f"OpenAI API connection error: {api_connection_error}"
+ raise LLMCompletionError(msg) from api_connection_error
+ except BadRequestError as bad_request_error:
+ msg = f"OpenAI bad request error with model: {self.inference_model.desc}:\n{bad_request_error}"
+ raise LLMCompletionError(msg) from bad_request_error
+ except AuthenticationError as authentication_error:
+ msg = f"Authentication error: {authentication_error}"
+ raise LLMCompletionError(msg) from authentication_error
+
+ if not response.output_text:
+ msg = f"OpenAI Responses message content is empty: {response}\nmodel: {self.inference_model.desc}"
+ raise LLMCompletionError(msg)
+
+ if (llm_tokens_usage := llm_job.job_report.llm_tokens_usage) and response.usage:
+ llm_tokens_usage.nb_tokens_by_category = self.openai_responses_factory.make_nb_tokens_by_category(usage=response.usage)
+ return response.output_text
+
+ @override
+ async def _gen_object(
+ self,
+ llm_job: LLMJob,
+ schema: type[BaseModelTypeVar],
+ ) -> BaseModelTypeVar:
+ job_params = llm_job.applied_job_params or llm_job.job_params
+ try:
+ if not hasattr(self.instructor_for_objects, "responses"):
+ msg = "Instructor client is not configured for the Responses API. Set a responses-capable structure_method for this model."
+ raise LLMCompletionError(msg)
+ extra_headers, extra_body = self.openai_responses_factory.make_extras(
+ inference_model=self.inference_model, llm_job=llm_job, output_desc=schema.__name__
+ )
+ input_items = await self.openai_responses_factory.make_input_items(llm_job=llm_job)
+ result_object, completion = await self.instructor_for_objects.responses.create_with_completion( # pyright: ignore[reportUnknownMemberType]
+ input=cast("list[ChatCompletionMessageParam]", input_items),
+ response_model=schema,
+ max_retries=llm_job.job_config.max_retries,
+ model=self.inference_model.model_id,
+ instructions=llm_job.llm_prompt.system_text,
+ temperature=job_params.temperature,
+ max_output_tokens=job_params.max_tokens or NOT_GIVEN,
+ extra_headers=extra_headers,
+ extra_body=extra_body,
+ ) # type: ignore[arg-type,misc]
+ except InstructorRetryException as exc:
+ msg = f"OpenAI instructor failed with model: {self.inference_model.desc} trying to generate schema: {schema} with error: {exc}"
+ raise LLMCompletionError(msg) from exc
+ except NotFoundError as exc:
+ msg = f"OpenAI Responses model or deployment '{self.inference_model.model_id}' not found: {exc}"
+ raise LLMCompletionError(msg) from exc
+ except BadRequestError as bad_request_error:
+ msg = f"OpenAI bad request error with model: {self.inference_model.desc}:\n{bad_request_error}"
+ raise LLMCompletionError(msg) from bad_request_error
+ except AuthenticationError as authentication_error:
+ msg = f"Authentication error: {authentication_error}"
+ raise LLMCompletionError(msg) from authentication_error
+
+ if (llm_tokens_usage := llm_job.job_report.llm_tokens_usage) and hasattr(completion, "usage"):
+ completion_usage = completion.usage
+ if completion_usage:
+ llm_tokens_usage.nb_tokens_by_category = self.openai_responses_factory.make_nb_tokens_by_category(usage=completion_usage)
+
+ typed_result_object: BaseModelTypeVar = result_object
+ return typed_result_object
diff --git a/pipelex/plugins/openai/openai_utils.py b/pipelex/plugins/openai/openai_utils.py
new file mode 100644
index 000000000..c5f07f160
--- /dev/null
+++ b/pipelex/plugins/openai/openai_utils.py
@@ -0,0 +1,24 @@
+from openai.types.chat.chat_completion_content_part_image_param import ImageURL
+
+from pipelex.cogt.exceptions import LLMPromptParameterError
+from pipelex.cogt.image.prompt_image import PromptImage, PromptImageBase64, PromptImageDetail, PromptImagePath, PromptImageUrl
+from pipelex.tools.misc.base_64_utils import load_binary_as_base64
+
+
+async def make_image_url_obj(prompt_image: PromptImage, detail: PromptImageDetail | None) -> ImageURL:
+ if detail is None:
+ detail = PromptImageDetail.AUTO
+ if isinstance(prompt_image, PromptImageUrl):
+ url = prompt_image.url
+ image_url_obj = ImageURL(url=url, detail=detail.as_openai_detail)
+ elif isinstance(prompt_image, PromptImageBase64):
+ # TODO: manage image type
+ url_with_bytes: str = f"data:image/jpeg;base64,{prompt_image.base_64.decode('utf-8')}"
+ image_url_obj = ImageURL(url=url_with_bytes, detail=detail.as_openai_detail)
+ elif isinstance(prompt_image, PromptImagePath):
+ image_bytes = load_binary_as_base64(path=prompt_image.file_path)
+ return await make_image_url_obj(prompt_image=PromptImageBase64(base_64=image_bytes), detail=detail)
+ else:
+ msg = f"prompt_image of type {type(prompt_image)} is not supported"
+ raise LLMPromptParameterError(msg)
+ return image_url_obj
diff --git a/pipelex/plugins/plugin_factory_abstract.py b/pipelex/plugins/plugin_factory_abstract.py
new file mode 100644
index 000000000..860fee423
--- /dev/null
+++ b/pipelex/plugins/plugin_factory_abstract.py
@@ -0,0 +1,11 @@
+from abc import ABC, abstractmethod
+from typing import Any
+
+from pipelex.cogt.llm.llm_job import LLMJob
+from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
+
+
+class PluginFactoryAbstract(ABC):
+ @abstractmethod
+ def make_extras(self, inference_model: InferenceModelSpec, llm_job: LLMJob, output_desc: str) -> tuple[dict[str, str], dict[str, Any]]:
+ pass
diff --git a/pipelex/plugins/portkey/__init__.py b/pipelex/plugins/portkey/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/pipelex/plugins/portkey/portkey_completions_factory.py b/pipelex/plugins/portkey/portkey_completions_factory.py
new file mode 100644
index 000000000..a22cf3c72
--- /dev/null
+++ b/pipelex/plugins/portkey/portkey_completions_factory.py
@@ -0,0 +1,50 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+import openai
+from portkey_ai import (
+ createHeaders, # type: ignore[reportUnknownVariableType]
+)
+from typing_extensions import override
+
+from pipelex.plugins.openai.openai_completions_factory import OpenAICompletionsFactory
+from pipelex.plugins.portkey.portkey_constants import PortkeyOpenAISdkVariant
+from pipelex.plugins.portkey.portkey_exceptions import PortkeyFactoryError
+from pipelex.plugins.portkey.portkey_factory import PortkeyFactory
+
+if TYPE_CHECKING:
+ from pipelex.cogt.llm.llm_job import LLMJob
+ from pipelex.cogt.model_backends.backend import InferenceBackend
+ from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
+ from pipelex.plugins.plugin_sdk_registry import Plugin
+
+
+class PortkeyCompletionsFactory(OpenAICompletionsFactory):
+ @classmethod
+ def make_portkey_openai_client_for_completions(
+ cls,
+ plugin: Plugin,
+ backend: InferenceBackend,
+ ) -> openai.AsyncOpenAI:
+ is_debug_enabled = PortkeyFactory.is_debug_enabled(backend=backend)
+ endpoint = PortkeyFactory.get_endpoint(backend=backend)
+ api_key = PortkeyFactory.get_api_key(backend=backend)
+
+ if not PortkeyOpenAISdkVariant.is_completions(plugin.sdk):
+ msg = f"Plugin '{plugin}' is not supported by '{cls.__name__}'"
+ raise PortkeyFactoryError(msg)
+
+ return openai.AsyncOpenAI(
+ base_url=endpoint,
+ api_key="",
+ default_headers=createHeaders(
+ api_key=api_key,
+ strict_open_ai_compliance=False,
+ debug=is_debug_enabled,
+ ), # type: ignore[call-overload]
+ )
+
+ @override
+ def make_extras(self, inference_model: InferenceModelSpec, llm_job: LLMJob, output_desc: str) -> tuple[dict[str, str], dict[str, Any]]:
+ return PortkeyFactory.make_extras(inference_model=inference_model, llm_job=llm_job, output_desc=output_desc)
diff --git a/pipelex/plugins/portkey/portkey_constants.py b/pipelex/plugins/portkey/portkey_constants.py
new file mode 100644
index 000000000..000bacd00
--- /dev/null
+++ b/pipelex/plugins/portkey/portkey_constants.py
@@ -0,0 +1,43 @@
+from pipelex.types import StrEnum
+
+
+class PortkeyHeaderKey(StrEnum):
+ TRACE_ID = "x-portkey-trace-id"
+ SPAN_ID = "x-portkey-span-id"
+ SPAN_NAME = "x-portkey-span-name"
+ CONFIG = "x-portkey-config"
+ PROVIDER = "x-portkey-provider"
+
+
+class PortkeyEnvVar(StrEnum):
+ FORCE_PORTKEY_DEBUG = "FORCE_PORTKEY_DEBUG"
+ FORCE_PORTKEY_TRACING = "FORCE_PORTKEY_TRACING"
+
+
+class PortkeyOpenAISdkVariant(StrEnum):
+ PORTKEY_COMPLETIONS = "portkey_completions"
+ PORTKEY_RESPONSES = "portkey_responses"
+
+ @classmethod
+ def is_completions(cls, sdk: str) -> bool:
+ try:
+ variant = cls(sdk)
+ except ValueError:
+ return False
+ match variant:
+ case cls.PORTKEY_COMPLETIONS:
+ return True
+ case cls.PORTKEY_RESPONSES:
+ return False
+
+ @classmethod
+ def is_responses(cls, sdk: str) -> bool:
+ try:
+ variant = cls(sdk)
+ except ValueError:
+ return False
+ match variant:
+ case cls.PORTKEY_COMPLETIONS:
+ return False
+ case cls.PORTKEY_RESPONSES:
+ return True
diff --git a/pipelex/plugins/portkey/portkey_exceptions.py b/pipelex/plugins/portkey/portkey_exceptions.py
new file mode 100644
index 000000000..a00816435
--- /dev/null
+++ b/pipelex/plugins/portkey/portkey_exceptions.py
@@ -0,0 +1,13 @@
+from pipelex.cogt.exceptions import CogtError
+
+
+class PortkeyError(CogtError):
+ pass
+
+
+class PortkeyFactoryError(PortkeyError):
+ pass
+
+
+class PortkeyCredentialsError(PortkeyError):
+ pass
diff --git a/pipelex/plugins/portkey/portkey_factory.py b/pipelex/plugins/portkey/portkey_factory.py
new file mode 100644
index 000000000..18e5c332c
--- /dev/null
+++ b/pipelex/plugins/portkey/portkey_factory.py
@@ -0,0 +1,69 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+from portkey_ai import PORTKEY_GATEWAY_URL
+
+from pipelex.cogt.llm.llm_constants import LLMOutputType
+from pipelex.hub import get_telemetry_manager
+from pipelex.plugins.openai.openai_constants import OpenAIBodyKey
+from pipelex.plugins.portkey.portkey_constants import PortkeyHeaderKey
+from pipelex.plugins.portkey.portkey_exceptions import PortkeyCredentialsError
+from pipelex.system.telemetry.otel_constants import OTelConstants
+from pipelex.system.telemetry.telemetry_manager_abstract import TelemetryManagerAbstract
+
+if TYPE_CHECKING:
+ from pipelex.cogt.llm.llm_job import LLMJob
+ from pipelex.cogt.model_backends.backend import InferenceBackend
+ from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
+
+
+class PortkeyFactory:
+ @classmethod
+ def is_debug_enabled(cls, backend: InferenceBackend) -> bool:
+ is_debug_configured = backend.extra_config.get("debug", False)
+ return get_telemetry_manager().is_portkey_logging_enabled(is_debug_configured=is_debug_configured)
+
+ @classmethod
+ def get_endpoint(cls, backend: InferenceBackend) -> str:
+ return backend.endpoint or PORTKEY_GATEWAY_URL
+
+ @classmethod
+ def get_api_key(cls, backend: InferenceBackend) -> str:
+ if not backend.api_key:
+ msg = "Portkey API key is not set"
+ raise PortkeyCredentialsError(msg)
+ return backend.api_key
+
+ @classmethod
+ def make_extras(cls, inference_model: InferenceModelSpec, llm_job: LLMJob, output_desc: str) -> tuple[dict[str, str], dict[str, Any]]:
+ extra_headers: dict[str, str] = {}
+ extra_body: dict[str, Any] = {}
+
+ # Model-level extras (unchanged)
+ if inference_model.extra_headers:
+ extra_headers.update(inference_model.extra_headers)
+ if not llm_job.job_params.max_tokens and inference_model.max_tokens:
+ extra_body[OpenAIBodyKey.MAX_TOKENS] = inference_model.max_tokens
+
+ # OTel-correlated Portkey tracing (only when enabled and OTel context available)
+ if get_telemetry_manager().is_portkey_tracing_enabled() and (otel_context := llm_job.job_metadata.otel_context):
+ # Use OTel trace_id and span_id for correlation
+ extra_headers[PortkeyHeaderKey.TRACE_ID] = f"{otel_context.trace_id:032x}"
+ extra_headers[PortkeyHeaderKey.SPAN_ID] = f"{otel_context.span_id:016x}"
+
+ # Build span name respecting privacy settings
+ pipe_code = llm_job.job_metadata.pipe_code or "main"
+ if not TelemetryManagerAbstract.is_capture_pipe_codes_enabled():
+ pipe_code = OTelConstants.PIPE_CODE_REDACTED
+
+ # Redact output class name if not "text" and capture is disabled
+ if output_desc == LLMOutputType.TEXT or TelemetryManagerAbstract.is_capture_output_class_name_enabled():
+ display_output = output_desc
+ else:
+ display_output = OTelConstants.OUTPUT_CLASS_REDACTED
+
+ unit_job_id = llm_job.job_metadata.unit_job_id or "unknown"
+ extra_headers[PortkeyHeaderKey.SPAN_NAME] = f"{pipe_code}: {unit_job_id} -> {display_output}"
+
+ return extra_headers, extra_body
diff --git a/pipelex/plugins/portkey/portkey_responses_factory.py b/pipelex/plugins/portkey/portkey_responses_factory.py
new file mode 100644
index 000000000..d571729e1
--- /dev/null
+++ b/pipelex/plugins/portkey/portkey_responses_factory.py
@@ -0,0 +1,48 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+import openai
+from portkey_ai import (
+ createHeaders, # type: ignore[reportUnknownVariableType]
+)
+from typing_extensions import override
+
+from pipelex.plugins.openai.openai_responses_factory import OpenAIResponsesFactory
+from pipelex.plugins.portkey.portkey_constants import PortkeyOpenAISdkVariant
+from pipelex.plugins.portkey.portkey_exceptions import PortkeyFactoryError
+from pipelex.plugins.portkey.portkey_factory import PortkeyFactory
+
+if TYPE_CHECKING:
+ from pipelex.cogt.llm.llm_job import LLMJob
+ from pipelex.cogt.model_backends.backend import InferenceBackend
+ from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
+ from pipelex.plugins.plugin_sdk_registry import Plugin
+
+
+class PortkeyResponsesFactory(OpenAIResponsesFactory):
+ @classmethod
+ def make_portkey_openai_client_for_responses(
+ cls,
+ plugin: Plugin,
+ backend: InferenceBackend,
+ ) -> openai.AsyncOpenAI:
+ is_debug_enabled = PortkeyFactory.is_debug_enabled(backend=backend)
+ endpoint = PortkeyFactory.get_endpoint(backend=backend)
+ api_key = PortkeyFactory.get_api_key(backend=backend)
+ if not PortkeyOpenAISdkVariant.is_responses(plugin.sdk):
+ msg = f"Plugin '{plugin}' is not supported by '{cls.__name__}'"
+ raise PortkeyFactoryError(msg)
+
+ return openai.AsyncOpenAI(
+ base_url=endpoint,
+ api_key="",
+ default_headers=createHeaders(
+ api_key=api_key,
+ debug=is_debug_enabled,
+ ), # type: ignore[call-overload]
+ )
+
+ @override
+ def make_extras(self, inference_model: InferenceModelSpec, llm_job: LLMJob, output_desc: str) -> tuple[dict[str, str], dict[str, Any]]:
+ return PortkeyFactory.make_extras(inference_model=inference_model, llm_job=llm_job, output_desc=output_desc)
diff --git a/pipelex/system/configuration/config_model.py b/pipelex/system/configuration/config_model.py
index da0de9a62..f5c05f8e4 100644
--- a/pipelex/system/configuration/config_model.py
+++ b/pipelex/system/configuration/config_model.py
@@ -1,4 +1,4 @@
-from typing import TypeVar
+from typing import Any, TypeVar
from pydantic import BaseModel, ConfigDict
@@ -55,6 +55,23 @@ class ConfigModel(BaseModel):
"""
return {key_enum_cls(key): value for key, value in input_dict.items()}
+ @staticmethod
+ def transform_dict_keys_str_to_enum(
+ input_dict: dict[str, Any],
+ key_enum_cls: type[StrEnumType],
+ ) -> dict[StrEnumType, Any]:
+ """Transforms a dictionary with str keys and Any values into a dictionary with enum keys and Any values.
+
+ Args:
+ input_dict: Dictionary with string keys to be transformed.
+ key_enum_cls: The StrEnum class to convert the keys to
+
+ Returns:
+ A dictionary where the keys are converted to the given StrEnum type.
+
+ """
+ return {key_enum_cls(key): value for key, value in input_dict.items()}
+
@staticmethod
def transform_list_of_str_to_enum(
input_list: list[str],
diff --git a/pipelex/system/pipelex_service/__init__.py b/pipelex/system/pipelex_service/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/pipelex/system/pipelex_service/exceptions.py b/pipelex/system/pipelex_service/exceptions.py
new file mode 100644
index 000000000..adcd9ef6b
--- /dev/null
+++ b/pipelex/system/pipelex_service/exceptions.py
@@ -0,0 +1,125 @@
+"""Exceptions for Pipelex managed services."""
+
+from pipelex.system.exceptions import PipelexError
+
+
+class PipelexServiceConfigValidationError(PipelexError):
+ """Raised when pipelex_service.toml validation fails."""
+
+
+class PipelexServiceError(PipelexError):
+ """Base exception for Pipelex service errors."""
+
+
+class RemoteConfigFetchError(PipelexServiceError):
+ """Raised when fetching remote configuration from PostHog fails.
+
+ This error occurs when:
+ - Network request to PostHog fails
+ - Feature flag is not found or disabled
+ - Payload is missing or malformed
+ """
+
+
+class RemoteConfigValidationError(PipelexServiceError):
+ """Raised when remote configuration payload validation fails.
+
+ This error occurs when:
+ - JSON payload is not valid
+ - Required keys are missing
+ - Payload structure doesn't match expected schema
+ """
+
+
+class GatewayTermsNotAcceptedError(PipelexServiceError):
+ """Raised when Pipelex Gateway is enabled but terms are not accepted.
+
+ Users must accept the Pipelex Gateway terms of service before using
+ the gateway backend. This can be done via `pipelex init config` command.
+ """
+
+ def __init__(self) -> None:
+ msg = (
+ "Pipelex Gateway is enabled but terms have not been accepted.\n"
+ "To use Pipelex Gateway, you must accept our terms of service.\n"
+ "Run `pipelex init config` to configure your backends and accept the terms.\n"
+ "Alternatively, disable pipelex_gateway in .pipelex/inference/backends.toml\n"
+ "and use your own API keys with direct provider backends.\n"
+ "For more information: https://docs.pipelex.com/gateway\n"
+ "Questions? Join our Discord: https://go.pipelex.com/discord"
+ )
+ super().__init__(msg)
+
+
+class GatewayApiKeyMissingError(PipelexServiceError):
+ """Raised when Pipelex Gateway is enabled but the API key is not set.
+
+ Users must set the PIPELEX_GATEWAY_API_KEY environment variable to use
+ the gateway backend.
+ """
+
+ def __init__(self) -> None:
+ msg = (
+ "Pipelex Gateway is enabled but PIPELEX_GATEWAY_API_KEY is not set.\n"
+ "Please set the PIPELEX_GATEWAY_API_KEY environment variable.\n"
+ "You can get a key at: https://pipelex.com/gateway\n"
+ "Alternatively, disable pipelex_gateway in .pipelex/inference/backends.toml\n"
+ "and use your own API keys with direct provider backends.\n"
+ "For more information: https://docs.pipelex.com/gateway\n"
+ "Questions? Join our Discord: https://go.pipelex.com/discord"
+ )
+ super().__init__(msg)
+
+
+class GatewayTelemetryManagerInjectedError(PipelexServiceError):
+ """Raised when a custom TelemetryManager is injected while using Pipelex Gateway.
+
+ Pipelex Gateway requires its own telemetry setup for service monitoring.
+ Dependency-injecting a TelemetryManager is not allowed when gateway is enabled.
+ """
+
+ def __init__(self) -> None:
+ msg = (
+ "Cannot inject a custom TelemetryManager when Pipelex Gateway is enabled.\n"
+ "Gateway requires its own telemetry setup for service monitoring.\n\n"
+ "You can still add your own telemetry via .pipelex/telemetry.toml:\n"
+ " - PostHog: set host and project_api_key\n"
+ " - Langfuse: set langfuse_enabled = true (requires env vars)\n"
+ " - Any OTLP backend: set otlp_endpoint and otlp_headers\n\n"
+ "These will work alongside Gateway telemetry.\n"
+ "Remove the telemetry_manager parameter from Pipelex.make() to proceed."
+ )
+ super().__init__(msg)
+
+
+class GatewayDoNotTrackConflictError(PipelexServiceError):
+ """Raised when DO_NOT_TRACK is set but Pipelex Gateway requires telemetry.
+
+ Pipelex Gateway requires telemetry for service monitoring, but this conflicts
+ with the user's explicit request to not be tracked.
+ """
+
+ def __init__(self, dnt_env_var: str) -> None:
+ msg = (
+ f"Pipelex Gateway requires telemetry, but '{dnt_env_var}' is set.\n"
+ "We respect your Do Not Track preference.\n\n"
+ "To use Pipelex Gateway, unset the DO_NOT_TRACK environment variable.\n"
+ "Alternatively, disable pipelex_gateway in .pipelex/inference/backends.toml\n"
+ "and use your own API keys with direct provider backends.\n\n"
+ "For more information: https://docs.pipelex.com/gateway\n"
+ "Questions? Join our Discord: https://go.pipelex.com/discord"
+ )
+ super().__init__(msg)
+
+
+class GatewayOverrideWarning(UserWarning):
+ """Warning issued when local gateway overrides are applied."""
+
+
+class GatewayConfigMergeError(PipelexServiceError):
+ """Raised when gateway configuration merge encounters invalid data.
+
+ This error occurs when:
+ - Local override for a model is not a dictionary
+ - Remote config for a model is not a dictionary
+ """
diff --git a/pipelex/system/pipelex_service/gateway_config_merger.py b/pipelex/system/pipelex_service/gateway_config_merger.py
new file mode 100644
index 000000000..a8ee43eae
--- /dev/null
+++ b/pipelex/system/pipelex_service/gateway_config_merger.py
@@ -0,0 +1,103 @@
+import copy
+import warnings
+from typing import Any, cast
+
+from pipelex.cogt.model_backends.model_spec_factory import BackendModelSpecs
+from pipelex.system.pipelex_service.exceptions import GatewayConfigMergeError, GatewayOverrideWarning
+from pipelex.tools.log.log import log
+
+# Keys that can be overridden locally
+ALLOWED_OVERRIDE_KEYS = frozenset({"sdk", "structure_method"})
+
+
+class GatewayConfigMerger:
+ """Merges remote gateway configuration with local overrides.
+
+ Only allows overriding specific keys (sdk, structure_method).
+ Logs warnings when overrides are applied or when disallowed keys are found.
+ """
+
+ @classmethod
+ def merge(
+ cls,
+ gateway_model_specs: BackendModelSpecs,
+ local_overrides: BackendModelSpecs,
+ ) -> dict[str, Any]:
+ """Merge remote config with local overrides.
+
+ Args:
+ gateway_model_specs: Model specs from Pipelex Gateway.
+ local_overrides: Local overrides from local pipelex_gateway.toml.
+
+ Returns:
+ Merged configuration with allowed overrides applied.
+ """
+ result: dict[str, Any] = copy.deepcopy(gateway_model_specs)
+
+ # Warn if defaults section is present (not allowed for local overrides)
+ if "defaults" in local_overrides:
+ log.warning("[GatewayConfigMerger] Local 'defaults' section ignored. Overrides are only allowed per-model, not via defaults.")
+
+ # Handle per-model overrides only
+ for model_name, local_model_config in local_overrides.items():
+ if model_name == "defaults":
+ continue # Skip defaults section (already warned above)
+
+ if not isinstance(local_model_config, dict):
+ msg = f"Local override for model '{model_name}' must be a dictionary, got {type(local_model_config).__name__}"
+ raise GatewayConfigMergeError(msg)
+
+ if model_name not in result:
+ log.warning(f"[GatewayConfigMerger] Local override for model '{model_name}' ignored: model not found in remote configuration")
+ continue
+
+ remote_model = result[model_name]
+ if not isinstance(remote_model, dict):
+ msg = f"Remote config for model '{model_name}' must be a dictionary, got {type(remote_model).__name__}"
+ raise GatewayConfigMergeError(msg)
+
+ cls._apply_overrides_to_model(
+ model_name=model_name,
+ gateway_model_specs=cast("dict[str, Any]", remote_model),
+ local_model_config=cast("dict[str, Any]", local_model_config),
+ )
+
+ return result
+
+ @classmethod
+ def _apply_overrides_to_model(
+ cls,
+ model_name: str,
+ gateway_model_specs: BackendModelSpecs,
+ local_model_config: BackendModelSpecs,
+ ) -> None:
+ """Apply local overrides to a single model configuration.
+
+ Args:
+ model_name: Name of the model being configured.
+ gateway_model_specs: Remote model configuration to apply overrides to.
+ local_model_config: Local overrides for the model.
+ """
+ applied_overrides: list[str] = []
+ ignored_keys: list[str] = []
+
+ for key, value in local_model_config.items():
+ if key in ALLOWED_OVERRIDE_KEYS:
+ old_value = gateway_model_specs.get(key)
+ if old_value != value:
+ gateway_model_specs[key] = value
+ applied_overrides.append(f"{key}: {old_value!r} -> {value!r}")
+ else:
+ ignored_keys.append(key)
+
+ if applied_overrides:
+ override_details = ", ".join(applied_overrides)
+ warning_msg = f"[GatewayConfigMerger] Local overrides applied for '{model_name}': {override_details}. This may affect behavior."
+ log.warning(warning_msg)
+ warnings.warn(warning_msg, GatewayOverrideWarning, stacklevel=3)
+
+ if ignored_keys:
+ log.warning(
+ f"[GatewayConfigMerger] Ignored non-overridable keys for '{model_name}': "
+ f"{ignored_keys}. Only {list(ALLOWED_OVERRIDE_KEYS)} can be overridden."
+ )
diff --git a/pipelex/system/pipelex_service/pipelex_details.py b/pipelex/system/pipelex_service/pipelex_details.py
new file mode 100644
index 000000000..f8b59e57a
--- /dev/null
+++ b/pipelex/system/pipelex_service/pipelex_details.py
@@ -0,0 +1,55 @@
+"""Embedded Pipelex credentials for internal services.
+
+These credentials are used for:
+1. Fetching remote configuration
+2. Mandatory telemetry when using Pipelex Gateway
+
+The PostHog project API key is write-only and used for event capture.
+"""
+
+import hashlib
+
+# Environment variable name for Pipelex Gateway API key
+PIPELEX_GATEWAY_API_KEY_VAR = "PIPELEX_GATEWAY_API_KEY"
+
+
+def _hash_gateway_api_key(api_key: str, length: int) -> str:
+ """Hash the gateway API key using truncated SHA256 for use as PostHog distinct_id.
+
+ Uses the first `length` characters of SHA256 hex digest, which provides
+ excellent collision resistance for practical purposes while being compact.
+
+ Args:
+ api_key: The raw Pipelex Gateway API key.
+ length: The length of the hash to return.
+
+ Returns:
+ First `length` characters of SHA256 hex digest.
+ """
+ return hashlib.sha256(api_key.encode("utf-8")).hexdigest()[:length]
+
+
+class PipelexDetails:
+ """Base configuration for Pipelex's services."""
+
+ # PostHog host for Pipelex services
+ POSTHOG_HOST = "https://eu.i.posthog.com"
+
+ # Pipelex PostHog project API key (write-only, safe to embed)
+ # This is used for event capture only
+ POSTHOG_PROJECT_API_KEY = "phc_GXvlRgWMQ9c4xrxAMBsMeyOqHKyfSK0sAc2oEgu4jpT"
+
+ # Public URL for remote gateway configuration (JSON file on S3)
+ REMOTE_CONFIG_URL = "https://pipelex-config.s3.amazonaws.com/pipelex_remote_config.json"
+
+ @classmethod
+ def make_distinct_id(cls, gateway_api_key: str) -> str:
+ """Make a distinct_id for PostHog from the gateway API key.
+
+ Args:
+ gateway_api_key: The raw Pipelex Gateway API key.
+
+ Returns:
+ First 16 characters of SHA256 hex digest.
+ """
+ return _hash_gateway_api_key(gateway_api_key, length=16)
diff --git a/pipelex/system/pipelex_service/pipelex_service_agreement.py b/pipelex/system/pipelex_service/pipelex_service_agreement.py
new file mode 100644
index 000000000..de0ff5689
--- /dev/null
+++ b/pipelex/system/pipelex_service/pipelex_service_agreement.py
@@ -0,0 +1,41 @@
+"""Configuration model for Pipelex managed services."""
+
+import os
+
+from pydantic import Field
+
+from pipelex.kit.paths import get_kit_configs_dir
+from pipelex.system.configuration.config_loader import config_manager
+from pipelex.system.configuration.config_model import ConfigModel
+from pipelex.tools.misc.file_utils import path_exists
+from pipelex.tools.misc.toml_utils import load_toml_with_tomlkit, save_toml_to_path
+
+PIPELEX_SERVICE_CONFIG_FILE_NAME = "pipelex_service.toml"
+
+
+class PipelexServiceAgreement(ConfigModel):
+ terms_accepted: bool = Field(
+ default=False,
+ description="Whether the user has accepted Pipelex terms of service",
+ )
+
+
+def update_service_terms_acceptance(accepted: bool) -> None:
+ """Update the service terms acceptance in pipelex_service.toml.
+
+ Args:
+ accepted: Whether the user accepted the terms.
+ """
+ service_config_path = os.path.join(config_manager.pipelex_config_dir, PIPELEX_SERVICE_CONFIG_FILE_NAME)
+
+ if path_exists(service_config_path):
+ toml_doc = load_toml_with_tomlkit(service_config_path)
+ else:
+ # Load from the kit template
+ template_path = str(get_kit_configs_dir() / PIPELEX_SERVICE_CONFIG_FILE_NAME)
+ toml_doc = load_toml_with_tomlkit(template_path)
+
+ # Update terms_accepted
+ toml_doc["agreement"]["terms_accepted"] = accepted # type: ignore[index]
+
+ save_toml_to_path(toml_doc, service_config_path)
diff --git a/pipelex/system/pipelex_service/pipelex_service_config.py b/pipelex/system/pipelex_service/pipelex_service_config.py
new file mode 100644
index 000000000..a09fbb619
--- /dev/null
+++ b/pipelex/system/pipelex_service/pipelex_service_config.py
@@ -0,0 +1,63 @@
+"""Configuration model for Pipelex managed services."""
+
+import os
+from typing import Any, cast
+
+from pydantic import ValidationError
+
+from pipelex.cogt.model_backends.backend import PipelexBackend
+from pipelex.system.configuration.config_model import ConfigModel
+from pipelex.system.configuration.configs import ConfigPaths
+from pipelex.system.pipelex_service.exceptions import PipelexServiceConfigValidationError
+from pipelex.system.pipelex_service.pipelex_service_agreement import (
+ PIPELEX_SERVICE_CONFIG_FILE_NAME,
+ PipelexServiceAgreement,
+)
+from pipelex.tools.misc.toml_utils import load_toml_from_path, load_toml_from_path_if_exists
+from pipelex.tools.typing.pydantic_utils import format_pydantic_validation_error
+
+
+class PipelexServiceConfig(ConfigModel):
+ agreement: PipelexServiceAgreement
+
+
+def load_pipelex_service_config_if_exists(config_dir: str) -> PipelexServiceConfig | None:
+ """Load Pipelex service configuration if the file exists.
+
+ Args:
+ config_dir: Path to the .pipelex configuration directory.
+
+ Returns:
+ PipelexServiceConfig instance or None if file doesn't exist.
+ """
+ config_path = os.path.join(config_dir, PIPELEX_SERVICE_CONFIG_FILE_NAME)
+ try:
+ config_toml = load_toml_from_path(path=config_path)
+ return PipelexServiceConfig.model_validate(config_toml)
+ except FileNotFoundError:
+ return None
+ except ValidationError as exc:
+ validation_error_msg = format_pydantic_validation_error(exc)
+ msg = f"Invalid Pipelex service configuration: {validation_error_msg}"
+ raise PipelexServiceConfigValidationError(msg) from exc
+
+
+def is_pipelex_gateway_enabled() -> bool:
+ """Check if pipelex_gateway is enabled in the backends configuration.
+
+ This reads the backends.toml file directly without loading the full backend library.
+
+ Returns:
+ True if pipelex_gateway is enabled, False otherwise.
+ """
+ backends_toml = load_toml_from_path_if_exists(ConfigPaths.BACKENDS_FILE_PATH)
+ if backends_toml is None:
+ return False
+
+ gateway_config = backends_toml.get(PipelexBackend.GATEWAY)
+ if gateway_config is None or not isinstance(gateway_config, dict):
+ return False
+
+ gateway_config_dict = cast("dict[str, Any]", gateway_config)
+ enabled_value = gateway_config_dict.get("enabled", True)
+ return enabled_value is True
diff --git a/pipelex/system/pipelex_service/remote_config.py b/pipelex/system/pipelex_service/remote_config.py
new file mode 100644
index 000000000..d48299595
--- /dev/null
+++ b/pipelex/system/pipelex_service/remote_config.py
@@ -0,0 +1,98 @@
+import httpx
+from pydantic import BaseModel, Field, ValidationError
+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential
+
+from pipelex import log
+from pipelex.cogt.model_backends.model_spec_factory import BackendModelSpecs
+from pipelex.system.pipelex_service.exceptions import (
+ RemoteConfigFetchError,
+ RemoteConfigValidationError,
+)
+from pipelex.system.pipelex_service.pipelex_details import PipelexDetails
+from pipelex.tools.typing.pydantic_utils import format_pydantic_validation_error
+
+# Retry configuration for remote config fetch
+# Using hardcoded values since this runs before config is fully loaded
+_FETCH_MAX_RETRIES = 5
+_FETCH_WAIT_MULTIPLIER = 1
+_FETCH_WAIT_MIN = 1
+_FETCH_WAIT_MAX = 10
+_FETCH_TIMEOUT = 10.0
+
+
+class RemoteConfig(BaseModel):
+ backend_model_specs: BackendModelSpecs = Field(description="Model specifications for Pipelex Gateway (model_name -> spec dict)")
+
+
+def _log_retry_attempt(retry_state: RetryCallState) -> None:
+ """Log retry attempts for remote config fetch."""
+ exc = retry_state.outcome.exception() if retry_state.outcome else None
+ log.verbose(f"Remote config fetch attempt {retry_state.attempt_number} failed: {exc}. Retrying...")
+
+
+@retry(
+ retry=retry_if_exception_type((httpx.TimeoutException, httpx.RequestError)),
+ stop=stop_after_attempt(_FETCH_MAX_RETRIES),
+ wait=wait_exponential(multiplier=_FETCH_WAIT_MULTIPLIER, min=_FETCH_WAIT_MIN, max=_FETCH_WAIT_MAX),
+ before_sleep=_log_retry_attempt,
+ reraise=True,
+)
+def _fetch_remote_config_with_retry(url: str) -> httpx.Response:
+ """Fetch remote config with retry logic for transient network errors.
+
+ Args:
+ url: The URL to fetch the configuration from.
+
+ Returns:
+ The HTTP response.
+
+ Raises:
+ httpx.TimeoutException: If the request times out after all retries.
+ httpx.RequestError: If a network error occurs after all retries.
+ httpx.HTTPStatusError: If the server returns an error status (not retried).
+ """
+ response = httpx.get(url, timeout=_FETCH_TIMEOUT, follow_redirects=True)
+ response.raise_for_status()
+ return response
+
+
+def fetch_remote_config() -> RemoteConfig:
+ """Fetch Pipelex Service remote configuration.
+
+ Returns:
+ RemoteConfig.
+
+ Raises:
+ RemoteConfigFetchError: If the HTTP request fails or returns an error.
+ RemoteConfigValidationError: If the JSON doesn't match expected schema.
+ """
+ url = PipelexDetails.REMOTE_CONFIG_URL
+
+ try:
+ response = _fetch_remote_config_with_retry(url)
+ except httpx.TimeoutException as exc:
+ msg = f"Timeout while fetching remote configuration from {url}: {exc}"
+ raise RemoteConfigFetchError(msg) from exc
+ except httpx.HTTPStatusError as exc:
+ msg = f"HTTP error {exc.response.status_code} while fetching remote configuration from {url}"
+ raise RemoteConfigFetchError(msg) from exc
+ except httpx.RequestError as exc:
+ msg = f"Failed to fetch remote configuration from {url} after {_FETCH_MAX_RETRIES} attempts: {exc}"
+ raise RemoteConfigFetchError(msg) from exc
+
+ # Parse JSON content
+ try:
+ config_dict = response.json()
+ except Exception as exc:
+ msg = f"Failed to parse remote configuration JSON: {exc}"
+ raise RemoteConfigValidationError(msg) from exc
+
+ # Validate the structure
+ try:
+ config = RemoteConfig.model_validate(config_dict)
+ except ValidationError as exc:
+ validation_error_msg = format_pydantic_validation_error(exc)
+ msg = f"Remote configuration validation failed: {validation_error_msg}"
+ raise RemoteConfigValidationError(msg) from exc
+
+ return config
diff --git a/pipelex/system/registries/singleton.py b/pipelex/system/registries/singleton.py
new file mode 100644
index 000000000..97f0856e1
--- /dev/null
+++ b/pipelex/system/registries/singleton.py
@@ -0,0 +1,41 @@
+from abc import ABCMeta
+from typing import Any, ClassVar, TypeVar
+
+from typing_extensions import override
+
+T = TypeVar("T")
+
+
+class MetaSingleton(type):
+ """Simple implementation of a singleton using a metaclass."""
+
+ instances: ClassVar[dict[type[Any], Any]] = {}
+
+ @override
+ def __call__(cls, *args: Any, **kwargs: Any) -> Any:
+ if cls not in cls.instances: # pyright: ignore[reportUnnecessaryContains]
+ cls.instances[cls] = super().__call__(*args, **kwargs)
+ return cls.instances[cls]
+
+ @classmethod
+ def clear_subclass_instances(cls, base_cls: type[Any]) -> None:
+ """Clear all instances of subclasses of base_cls from the registry."""
+ for subclass in list(cls.instances.keys()):
+ if issubclass(subclass, base_cls):
+ del cls.instances[subclass]
+
+ @classmethod
+ def get_subclass_instance(cls, base_cls: type[T]) -> T | None:
+ """Get the singleton instance of a subclass of base_cls.
+
+ This is useful when the base class is abstract and only concrete
+ subclasses are instantiated.
+ """
+ for subclass, instance in cls.instances.items():
+ if issubclass(subclass, base_cls) and isinstance(instance, base_cls):
+ return instance
+ return None
+
+
+class ABCSingletonMeta(ABCMeta, MetaSingleton):
+ """Combined metaclass for ABC + Singleton pattern."""
diff --git a/pipelex/system/runtime.py b/pipelex/system/runtime.py
index b6ca033a6..98bb5d28f 100644
--- a/pipelex/system/runtime.py
+++ b/pipelex/system/runtime.py
@@ -8,30 +8,34 @@ CODEX_CLOUD_ENV_VAR_KEY = "CODEX_CLOUD"
class IntegrationMode(StrEnum):
+ CI = "ci"
CLI = "cli"
- FASTAPI = "fastapi"
DOCKER = "docker"
+ FASTAPI = "fastapi"
MCP = "mcp"
N8N = "n8n"
- PYTHON = "python"
PYTEST = "pytest"
+ PYTHON = "python"
- def allows_telemetry(self) -> bool:
+ @property
+ def requires_terms_acceptance(self) -> bool:
match self:
+ case IntegrationMode.CI:
+ return False
case IntegrationMode.CLI:
return True
- case IntegrationMode.FASTAPI:
- return True
case IntegrationMode.DOCKER:
return True
+ case IntegrationMode.FASTAPI:
+ return True
case IntegrationMode.MCP:
return True
case IntegrationMode.N8N:
return True
- case IntegrationMode.PYTHON:
- return False
case IntegrationMode.PYTEST:
- return False
+ return True
+ case IntegrationMode.PYTHON:
+ return True
class RunMode(StrEnum):
diff --git a/pipelex/system/telemetry/events.py b/pipelex/system/telemetry/events.py
index 2f8e7c708..a266094d4 100644
--- a/pipelex/system/telemetry/events.py
+++ b/pipelex/system/telemetry/events.py
@@ -43,7 +43,7 @@ class EventProperty(StrEnum):
# Pipeline
PIPELINE_RUN_ID = "pipeline_run_id"
- PIPELINE_EXECUTE_OUTCOME = "pipeline_execute_outcome"
+ PIPELINE_OUTCOME = "outcome"
# Pipe
PIPE_TYPE = "pipe_type"
diff --git a/pipelex/system/telemetry/exceptions.py b/pipelex/system/telemetry/exceptions.py
new file mode 100644
index 000000000..cf14c1d52
--- /dev/null
+++ b/pipelex/system/telemetry/exceptions.py
@@ -0,0 +1,13 @@
+from pipelex.base_exceptions import PipelexError
+
+
+class TelemetryConfigError(PipelexError):
+ pass
+
+
+class TelemetryConfigValidationError(TelemetryConfigError):
+ pass
+
+
+class LangfuseCredentialsError(PipelexError):
+ pass
diff --git a/pipelex/system/telemetry/otel_constants.py b/pipelex/system/telemetry/otel_constants.py
new file mode 100644
index 000000000..c0df969f2
--- /dev/null
+++ b/pipelex/system/telemetry/otel_constants.py
@@ -0,0 +1,170 @@
+"""OpenTelemetry constants for GenAI-compliant tracing.
+
+This module defines attribute keys used for instrumenting LLM operations
+with OpenTelemetry, following the GenAI semantic conventions.
+"""
+
+from opentelemetry.semconv._incubating.attributes import gen_ai_attributes as otel_gen_ai_attributes # noqa: PLC2701
+
+from pipelex.cogt.llm.llm_constants import LLMOutputType
+from pipelex.types import StrEnum
+
+
+class OTelConstants:
+ """OpenTelemetry constants."""
+
+ DEFAULT_USER_ID = "anonymous"
+ SERVICE_NAME = "pipelex"
+ SERVICE_NAMESPACE_KEY = "service.namespace"
+ SERVICE_NAMESPACE = "ai.orchestration"
+ INSTRUMENTING_MODULE_NAME = "pipelex"
+
+ DO_NOT_TRACK_ENV_VAR_KEY = "DO_NOT_TRACK"
+ PIPE_CODE_REDACTED = "[REDACTED]"
+ OUTPUT_CLASS_REDACTED = "Object"
+ TRUNCATION_SUFFIX = "... [truncated]"
+
+ # Virtual parent span ID for root spans.
+ # INVALID_SPAN_ID (0) makes SpanContext invalid, causing OTel to ignore our trace_id.
+ # Using 1 as virtual parent ensures OTel uses our deterministic trace_id while
+ # still treating the span as a root (we filter this out in the exporter).
+ OTEL_VIRTUAL_ROOT_PARENT_SPAN_ID = 1
+
+ LANGFUSE_CLOUD_URL = "https://cloud.langfuse.com"
+
+
+class GenAISpanAttr(StrEnum):
+ """OpenTelemetry GenAI semantic convention attribute keys."""
+
+ OPERATION_NAME = otel_gen_ai_attributes.GEN_AI_OPERATION_NAME
+ PROVIDER_NAME = otel_gen_ai_attributes.GEN_AI_PROVIDER_NAME
+
+ REQUEST_MODEL = otel_gen_ai_attributes.GEN_AI_REQUEST_MODEL
+ REQUEST_MAX_TOKENS = otel_gen_ai_attributes.GEN_AI_REQUEST_MAX_TOKENS
+ REQUEST_TEMPERATURE = otel_gen_ai_attributes.GEN_AI_REQUEST_TEMPERATURE
+ REQUEST_SEED = otel_gen_ai_attributes.GEN_AI_REQUEST_SEED
+
+ RESPONSE_MODEL = otel_gen_ai_attributes.GEN_AI_RESPONSE_MODEL
+ OUTPUT_TYPE = otel_gen_ai_attributes.GEN_AI_OUTPUT_TYPE
+ USAGE_INPUT_TOKENS = otel_gen_ai_attributes.GEN_AI_USAGE_INPUT_TOKENS
+ USAGE_OUTPUT_TOKENS = otel_gen_ai_attributes.GEN_AI_USAGE_OUTPUT_TOKENS
+
+ # Content attributes for PostHog compatibility (not in standard semconv)
+ # PostHog UI expects these as span attributes, not events
+ PROMPT_CONTENT = "gen_ai.prompt.0.content"
+ COMPLETION_CONTENT = "gen_ai.completion.0.content"
+
+
+class PostHogAttr(StrEnum):
+ """PostHog AI analytics attribute keys."""
+
+ MODEL = "$ai_model"
+ PROVIDER = "$ai_provider"
+ INPUT_TOKENS = "$ai_input_tokens"
+ OUTPUT_TOKENS = "$ai_output_tokens"
+ HTTP_STATUS = "$ai_http_status"
+ LATENCY = "$ai_latency"
+ TRACE_ID = "$ai_trace_id"
+ SPAN_ID = "$ai_span_id"
+ TRACE_NAME = "$ai_trace_name"
+ PARENT_ID = "$ai_parent_id"
+ INPUT = "$ai_input"
+ OUTPUT_CHOICES = "$ai_output_choices"
+ SPAN_NAME = "$ai_span_name"
+
+ # Additional attributes with $ai prefix
+ MODEL_ID = "$ai_model_id"
+ OUTPUT_TYPE = "$ai_output_type"
+ TEMPERATURE = "$ai_temperature"
+ MAX_TOKENS = "$ai_max_tokens"
+ SEED = "$ai_seed"
+
+ # Standard PostHog attribute for anonymous tracking
+ PROCESS_PERSON_PROFILE = "$process_person_profile"
+
+
+class PostHogEvent(StrEnum):
+ """PostHog AI analytics event names."""
+
+ SPAN = "$ai_span"
+ GENERATION = "$ai_generation"
+
+
+def make_otel_gen_ai_output_type(output_type: str) -> otel_gen_ai_attributes.GenAiOutputTypeValues:
+ try:
+ llm_output_type = LLMOutputType(output_type)
+ match llm_output_type:
+ case LLMOutputType.TEXT:
+ return otel_gen_ai_attributes.GenAiOutputTypeValues.TEXT
+ case LLMOutputType.OBJECT:
+ return otel_gen_ai_attributes.GenAiOutputTypeValues.JSON
+ except ValueError as exc:
+ msg = f"Invalid LLM output type: {output_type}, and we only support LLM output types for now in OpenTelemetry"
+ raise ValueError(msg) from exc
+
+
+class PipelexSpanAttr(StrEnum):
+ """Pipelex-specific span attribute keys for workflow tracing."""
+
+ TRACE_NAME = "pipelex.trace.name"
+ TRACE_NAME_REDACTED = "pipelex.trace.name.redacted"
+ SPAN_CATEGORY = "pipelex.span.category" # "pipe" or "inference"
+ PIPE_CATEGORY = "pipelex.pipe.category"
+ PIPE_TYPE = "pipelex.pipe.type"
+ PIPE_CODE = "pipelex.pipe.code"
+ PIPELINE_RUN_ID = "pipelex.pipeline.run_id"
+ OUTCOME = "pipelex.outcome" # "success" or "failure"
+ OUTPUT_CLASS_NAME = "pipelex.output.class_name"
+
+
+class LangfuseSpanAttr(StrEnum):
+ """Langfuse-specific span attribute keys for enhanced observability.
+
+ These are trace-level attributes that Langfuse uses for grouping and filtering.
+ Note: Langfuse auto-detects "generation" type when gen_ai.request.model is present,
+ so we don't need to set langfuse.observation.type explicitly.
+
+ See: https://langfuse.com/integrations/native/opentelemetry
+ """
+
+ # Trace-level attributes (applied to trace record in Langfuse)
+ TRACE_NAME = "langfuse.trace.name"
+ USER_ID = "langfuse.user.id"
+ SESSION_ID = "langfuse.session.id"
+ RELEASE = "langfuse.release"
+ TRACE_INPUT = "langfuse.trace.input"
+ TRACE_OUTPUT = "langfuse.trace.output"
+
+ # Trace-level metadata (filterable in Langfuse UI)
+ TRACE_DESCRIPTION = "langfuse.trace.metadata.description"
+ TRACE_PIPE_CODE = "langfuse.trace.metadata.pipe_code"
+ TRACE_PIPE_TYPE = "langfuse.trace.metadata.pipe_type"
+ TRACE_PIPE_CATEGORY = "langfuse.trace.metadata.pipe_category"
+ TRACE_PIPELINE_RUN_ID = "langfuse.trace.metadata.pipeline_run_id"
+ TRACE_OUTCOME = "langfuse.trace.metadata.outcome"
+
+ # Environment (standard OTel attribute recognized by Langfuse)
+ DEPLOYMENT_ENVIRONMENT = "deployment.environment"
+
+ # Observation-level metadata (filterable in Langfuse UI)
+ OBSERVATION_DESCRIPTION = "langfuse.observation.metadata.description"
+ OBSERVATION_TYPE = "langfuse.observation.metadata.observation_type"
+ OBSERVATION_PIPE_CATEGORY = "langfuse.observation.metadata.pipe_category"
+ OBSERVATION_PIPE_TYPE = "langfuse.observation.metadata.pipe_type"
+ OBSERVATION_PIPE_CODE = "langfuse.observation.metadata.pipe_code"
+ OBSERVATION_PIPELINE_RUN_ID = "langfuse.observation.metadata.pipeline_run_id"
+ OBSERVATION_OUTCOME = "langfuse.observation.metadata.outcome"
+ OBSERVATION_INPUT = "langfuse.observation.input"
+ OBSERVATION_OUTPUT = "langfuse.observation.output"
+
+
+class SpanCategory(StrEnum):
+ PIPE = "pipe"
+ INFERENCE = "inference"
+
+
+class SpanOutcome(StrEnum):
+ """Outcome values for span completion."""
+
+ SUCCESS = "success"
+ FAILURE = "failure"
diff --git a/pipelex/system/telemetry/otel_context.py b/pipelex/system/telemetry/otel_context.py
new file mode 100644
index 000000000..dd8bbfd27
--- /dev/null
+++ b/pipelex/system/telemetry/otel_context.py
@@ -0,0 +1,12 @@
+from pydantic import BaseModel, ConfigDict, Field
+
+
+class OtelContext(BaseModel):
+ """OpenTelemetry context for tracing, derived from business IDs."""
+
+ model_config = ConfigDict(strict=True, extra="forbid")
+
+ trace_id: int = Field(description="128-bit, derived from pipeline_run_id")
+ trace_name: str = Field(description="Trace name with pipe_code (for custom telemetry)")
+ trace_name_redacted: str = Field(description="Trace name without pipe_code (for Pipelex telemetry)")
+ span_id: int = Field(description="64-bit, derived from pipe_run_id")
diff --git a/pipelex/system/telemetry/otel_factory.py b/pipelex/system/telemetry/otel_factory.py
new file mode 100644
index 000000000..f2ce8cc1a
--- /dev/null
+++ b/pipelex/system/telemetry/otel_factory.py
@@ -0,0 +1,286 @@
+"""OpenTelemetry utilities for GenAI-compliant tracing.
+
+This module provides helpers for instrumenting LLM operations with OpenTelemetry.
+"""
+
+import base64
+import hashlib
+from typing import Any
+
+from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
+from opentelemetry.sdk.resources import Resource as OTelResource
+from opentelemetry.sdk.trace import TracerProvider as OTelTracerProvider
+from opentelemetry.sdk.trace.export import BatchSpanProcessor as OTelBatchSpanProcessor
+from opentelemetry.semconv._incubating.attributes import deployment_attributes # noqa: PLC2701
+from opentelemetry.semconv.attributes import service_attributes
+from opentelemetry.trace import Tracer as OTelTracer
+from posthog import Posthog # type: ignore[attr-defined]
+
+from pipelex.core.memory.working_memory import WorkingMemory
+from pipelex.core.pipes.pipe_output import PipeOutput
+from pipelex.system.environment import get_optional_env
+from pipelex.system.runtime import RunEnvironment
+from pipelex.system.telemetry.exceptions import LangfuseCredentialsError
+from pipelex.system.telemetry.otel_constants import OTelConstants
+from pipelex.system.telemetry.posthog_span_exporter import PostHogSpanExporter
+from pipelex.system.telemetry.telemetry_config import LangfuseConfig, OtlpExporterConfig, TelemetryRedactionConfig
+from pipelex.tools.log.log import log
+from pipelex.tools.misc.json_utils import JsonContent, pure_json_str
+from pipelex.tools.misc.package_utils import get_package_version
+
+
+class OtelFactory:
+ @classmethod
+ def make_truncated_content(cls, content: str, max_length: int | None) -> str:
+ """Truncate content for telemetry capture if it exceeds max length.
+
+ Args:
+ content: The content to potentially truncate.
+ max_length: Maximum allowed length, or None for no limit.
+
+ Returns:
+ The original content if within limit, or truncated content with suffix.
+ """
+ if max_length is None or len(content) <= max_length:
+ return content
+ truncate_at = max(0, max_length - len(OTelConstants.TRUNCATION_SUFFIX))
+ return content[:truncate_at] + OTelConstants.TRUNCATION_SUFFIX
+
+ @classmethod
+ def stringify_json(cls, json_conent: JsonContent) -> str:
+ """Serialize a JSON dictionary to a string.
+
+ Args:
+ json_conent: The JSON content to serialize.
+
+ Returns:
+ The serialized JSON string.
+ """
+ # return json.dumps(json_conent, default=str)
+ return pure_json_str(data=json_conent)
+
+ @classmethod
+ def make_inputs_json(
+ cls,
+ working_memory: WorkingMemory,
+ needed_input_names: set[str],
+ max_length: int | None,
+ ) -> str:
+ """Serialize pipe inputs from working memory to JSON for telemetry.
+
+ Args:
+ working_memory: The working memory containing input stuffs.
+ needed_input_names: Set of input variable names to capture.
+ max_length: Maximum allowed length for the JSON string, or None for no limit.
+
+ Returns:
+ JSON string representing the inputs, potentially truncated.
+ """
+ inputs_dict: dict[str, Any] = {}
+ for input_name in needed_input_names:
+ stuff = working_memory.get_stuff(name=input_name)
+ inputs_dict[input_name] = {
+ "concept": stuff.concept.simple_concept_string,
+ "content": stuff.content.smart_dump(),
+ }
+
+ json_str = cls.stringify_json(json_conent=inputs_dict)
+ return cls.make_truncated_content(content=json_str, max_length=max_length)
+
+ @classmethod
+ def make_output_json(
+ cls,
+ pipe_output: PipeOutput,
+ max_length: int | None,
+ ) -> str:
+ """Serialize pipe output to JSON for telemetry.
+
+ Args:
+ pipe_output: The pipe output containing the main stuff.
+ max_length: Maximum allowed length for the JSON string, or None for no limit.
+
+ Returns:
+ JSON string representing the output, potentially truncated.
+ """
+ main_stuff = pipe_output.working_memory.get_optional_main_stuff()
+ if main_stuff is None:
+ return "{}"
+
+ output_dict: dict[str, Any] = {
+ "concept": main_stuff.concept.simple_concept_string,
+ "content": main_stuff.content.smart_dump(),
+ }
+
+ json_str = cls.stringify_json(json_conent=output_dict)
+ return cls.make_truncated_content(content=json_str, max_length=max_length)
+
+ @classmethod
+ def make_trace_id(cls, pipeline_run_id: str) -> int:
+ """Convert pipeline_run_id to a 128-bit OTel trace ID (deterministic).
+
+ Uses MD5 hash to generate a consistent trace ID from the pipeline_run_id.
+ This ensures all spans within the same pipeline run share the same trace ID.
+
+ Args:
+ pipeline_run_id: The pipeline run identifier string.
+
+ Returns:
+ A 128-bit integer suitable for use as an OTel trace ID.
+ """
+ return int(hashlib.md5(pipeline_run_id.encode("utf-8")).hexdigest(), 16) # noqa: S324
+
+ @classmethod
+ def make_trace_names(cls, pipeline_run_id: str, pipe_code: str) -> tuple[str, str]:
+ """Create both full and redacted trace names from pipeline run ID and pipe code.
+
+ Args:
+ pipeline_run_id: The pipeline run identifier string.
+ pipe_code: The pipe code to include in the full trace name.
+
+ Returns:
+ A tuple of (trace_name, trace_name_redacted):
+ - trace_name: Full version with pipe code (e.g., "my_pipe_abc12345")
+ - trace_name_redacted: Just the hash (e.g., "abc12345")
+ """
+ hashed_id = hashlib.md5(pipeline_run_id.encode("utf-8")).hexdigest()[:8] # noqa: S324
+ trace_name = f"{pipe_code}_{hashed_id}"
+ trace_name_redacted = hashed_id
+ return trace_name, trace_name_redacted
+
+ @classmethod
+ def _is_unresolved_placeholder(cls, value: str | None) -> bool:
+ """Check if a value is an unresolved env var placeholder."""
+ return value is not None and value.startswith("${")
+
+ @classmethod
+ def make_langfuse_exporter(cls, langfuse_config: LangfuseConfig) -> OTLPSpanExporter:
+ """Create a Langfuse OTLP exporter using config credentials.
+
+ Credentials can be provided via config (with env var substitution) or
+ fall back to LANGFUSE_PUBLIC_KEY/LANGFUSE_SECRET_KEY environment variables.
+
+ Args:
+ langfuse_config: Langfuse configuration with credentials
+
+ Returns:
+ OTLPSpanExporter configured for Langfuse
+
+ Raises:
+ LangfuseCredentialsError: If credentials are missing or unresolved
+ """
+ # Get credentials from config, falling back to env vars
+ public_key = langfuse_config.public_key or get_optional_env("LANGFUSE_PUBLIC_KEY")
+ secret_key = langfuse_config.secret_key or get_optional_env("LANGFUSE_SECRET_KEY")
+
+ # Check for missing or unresolved credentials
+ if not public_key or cls._is_unresolved_placeholder(public_key):
+ msg = "Langfuse enabled but public_key not found (set LANGFUSE_PUBLIC_KEY or configure in telemetry.toml)"
+ raise LangfuseCredentialsError(msg)
+ if not secret_key or cls._is_unresolved_placeholder(secret_key):
+ msg = "Langfuse enabled but secret_key not found (set LANGFUSE_SECRET_KEY or configure in telemetry.toml)"
+ raise LangfuseCredentialsError(msg)
+
+ # Config takes precedence, then env var, then default
+ endpoint = langfuse_config.endpoint or get_optional_env("LANGFUSE_BASE_URL") or "https://cloud.langfuse.com"
+
+ # Build Basic auth header
+ langfuse_auth = base64.b64encode(f"{public_key}:{secret_key}".encode()).decode()
+
+ return OTLPSpanExporter(
+ endpoint=f"{endpoint}/api/public/otel/v1/traces",
+ headers={"Authorization": f"Basic {langfuse_auth}"},
+ )
+
+ @classmethod
+ def make_ai_tracer(
+ cls,
+ user_id: str | None,
+ custom_posthog_client: Posthog | None,
+ custom_redaction_config: TelemetryRedactionConfig,
+ pipelex_posthog_client: Posthog | None = None,
+ pipelex_distinct_id: str | None = None,
+ otlp_exporters: list[OtlpExporterConfig] | None = None,
+ langfuse_config: LangfuseConfig | None = None,
+ ) -> tuple[OTelTracer, OTelTracerProvider]:
+ """Create an isolated OpenTelemetry Tracer for GenAI instrumentation.
+
+ This creates a dedicated TracerProvider that does NOT register itself as the
+ global tracer to avoid polluting other traces in the host application.
+
+ It can configure multiple types of exporters:
+ 1. Custom PostHog Exporter: User's PostHog for their own analytics
+ 2. Pipelex PostHog Exporter: Pipelex internal telemetry (mandatory for gateway)
+ 3. OTLP Exporters: Sends standard OTLP traces to collectors (supports multiple)
+ 4. Langfuse Exporter: Sends OTLP traces to Langfuse for LLM observability
+
+ Args:
+ user_id: Optional User ID for event attribution (custom telemetry)
+ custom_posthog_client: Optional user's PostHog client for sending events
+ custom_redaction_config: Redaction config for custom PostHog exporter
+ pipelex_posthog_client: Optional Pipelex internal PostHog client (for gateway)
+ pipelex_distinct_id: Distinct ID for Pipelex telemetry
+ otlp_exporters: List of OTLP exporter configurations
+ langfuse_config: Optional Langfuse configuration (enables Langfuse if provided and enabled)
+
+ Returns:
+ A tuple of (Tracer, TracerProvider). The caller should call
+ provider.shutdown() during teardown to flush pending spans.
+ """
+ # Define Resource (Identity)
+ resource = OTelResource.create(
+ attributes={
+ service_attributes.SERVICE_NAME: OTelConstants.SERVICE_NAME,
+ service_attributes.SERVICE_VERSION: get_package_version(),
+ OTelConstants.SERVICE_NAMESPACE_KEY: OTelConstants.SERVICE_NAMESPACE,
+ deployment_attributes.DEPLOYMENT_ENVIRONMENT: RunEnvironment.get_from_env_var().value,
+ }
+ )
+
+ # Create Provider
+ provider = OTelTracerProvider(resource=resource)
+
+ # Add Custom PostHog Exporter if client provided (custom telemetry)
+ # Uses user's redaction config (may capture content/pipe codes based on user settings)
+ if custom_posthog_client:
+ custom_posthog_exporter = PostHogSpanExporter(
+ posthog_client=custom_posthog_client,
+ distinct_id=user_id,
+ redaction_config=custom_redaction_config,
+ )
+ provider.add_span_processor(OTelBatchSpanProcessor(custom_posthog_exporter))
+ log.verbose("Custom PostHog exporter enabled for custom telemetry")
+
+ # Add Pipelex PostHog Exporter if client provided (mandatory for gateway)
+ # Always uses full redaction config (never captures sensitive content/pipe codes)
+ if pipelex_posthog_client:
+ pipelex_redaction_config = TelemetryRedactionConfig.pipelex_config()
+ pipelex_posthog_exporter = PostHogSpanExporter(
+ posthog_client=pipelex_posthog_client,
+ distinct_id=pipelex_distinct_id,
+ redaction_config=pipelex_redaction_config,
+ )
+ provider.add_span_processor(OTelBatchSpanProcessor(pipelex_posthog_exporter))
+ log.verbose("Pipelex PostHog exporter enabled for gateway telemetry (with full redaction)")
+
+ # Add OTLP Exporters (supports multiple)
+ if otlp_exporters:
+ for exporter_config in otlp_exporters:
+ otlp_exporter = OTLPSpanExporter(
+ endpoint=exporter_config.endpoint,
+ headers=exporter_config.headers,
+ )
+ provider.add_span_processor(OTelBatchSpanProcessor(otlp_exporter))
+ log.verbose(f"OTLP exporter '{exporter_config.name}' enabled: {exporter_config.endpoint}")
+
+ # Add Langfuse OTLP Exporter if enabled
+ if langfuse_config and langfuse_config.enabled:
+ langfuse_exporter = cls.make_langfuse_exporter(langfuse_config)
+ provider.add_span_processor(OTelBatchSpanProcessor(langfuse_exporter))
+ log.verbose("Langfuse OTLP exporter enabled")
+
+ # Get the Tracer and return both tracer and provider
+ tracer = provider.get_tracer(
+ instrumenting_module_name=OTelConstants.INSTRUMENTING_MODULE_NAME,
+ instrumenting_library_version=get_package_version(),
+ )
+ return tracer, provider
diff --git a/pipelex/system/telemetry/posthog_span_exporter.py b/pipelex/system/telemetry/posthog_span_exporter.py
new file mode 100644
index 000000000..422d63907
--- /dev/null
+++ b/pipelex/system/telemetry/posthog_span_exporter.py
@@ -0,0 +1,368 @@
+"""PostHog span exporter for OpenTelemetry.
+
+This module provides a SpanExporter that sends OTel spans to PostHog
+as $ai_generation or $ai_span events.
+"""
+
+from typing import Any, Mapping, Sequence, cast
+
+from opentelemetry.sdk.trace import ReadableSpan
+from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
+from opentelemetry.util.types import AttributeValue
+from posthog import Posthog
+from typing_extensions import override
+
+from pipelex import log
+from pipelex.system.telemetry.otel_constants import (
+ GenAISpanAttr,
+ OTelConstants,
+ PipelexSpanAttr,
+ PostHogAttr,
+ PostHogEvent,
+ SpanCategory,
+)
+from pipelex.system.telemetry.telemetry_config import TelemetryRedactionConfig
+
+
+class PostHogSpanExporter(SpanExporter):
+ """Exports OTel spans to PostHog as $ai_generation or $ai_span events.
+
+ Applies redaction rules from TelemetryRedactionConfig before sending events.
+ """
+
+ def __init__(
+ self,
+ posthog_client: Posthog,
+ distinct_id: str | None,
+ redaction_config: TelemetryRedactionConfig,
+ ):
+ self.posthog_client = posthog_client
+ self.distinct_id = distinct_id
+ self.redaction_config = redaction_config
+
+ def _capture_event(self, event: PostHogEvent, properties: dict[str, Any]) -> None:
+ """Capture an event to PostHog, handling anonymous vs identified users.
+
+ PostHog requires a valid distinct_id - passing None will cause the event to be rejected.
+ For anonymous tracking, we omit distinct_id and set $process_person_profile=False.
+ """
+ if self.distinct_id:
+ # Identified user: pass distinct_id
+ self.posthog_client.capture(
+ distinct_id=self.distinct_id,
+ event=event,
+ properties=properties,
+ )
+ else:
+ # Anonymous user: don't pass distinct_id, mark as anonymous
+ properties[PostHogAttr.PROCESS_PERSON_PROFILE] = False
+ self.posthog_client.capture(
+ event=event,
+ properties=properties,
+ )
+
+ def _truncate_content(self, content: str) -> str:
+ """Truncate content if it exceeds max length.
+
+ Args:
+ content: The content string to potentially truncate.
+
+ Returns:
+ The original content if no limit is set or within limit,
+ otherwise truncated content with suffix.
+ """
+ max_length = self.redaction_config.content_max_length
+ if max_length is None or len(content) <= max_length:
+ return content
+ truncate_at = max(0, max_length - len(OTelConstants.TRUNCATION_SUFFIX))
+ return content[:truncate_at] + OTelConstants.TRUNCATION_SUFFIX
+
+ def _apply_content_redaction(self, properties: dict[str, Any]) -> None:
+ """Apply content redaction to properties in place.
+
+ Removes or truncates content fields based on redaction config.
+
+ Args:
+ properties: The properties dict to modify in place.
+ """
+ if self.redaction_config.redact_content:
+ # Remove content fields entirely
+ properties.pop(PostHogAttr.INPUT, None)
+ properties.pop(PostHogAttr.OUTPUT_CHOICES, None)
+ else:
+ # Apply truncation if content exists
+ if properties.get(PostHogAttr.INPUT):
+ properties[PostHogAttr.INPUT] = self._truncate_content(str(properties[PostHogAttr.INPUT]))
+ if properties.get(PostHogAttr.OUTPUT_CHOICES):
+ properties[PostHogAttr.OUTPUT_CHOICES] = self._truncate_content(str(properties[PostHogAttr.OUTPUT_CHOICES]))
+
+ def _build_redacted_pipe_span_name(
+ self,
+ original_span_name: str,
+ pipe_type: str | None,
+ ) -> str:
+ """Build a redacted span name for pipe spans.
+
+ Pipe span names follow the format: "{pipe_type}: {pipe_code}"
+ This method rebuilds the name with redacted pipe code if needed.
+
+ Args:
+ original_span_name: The original span name from OTel.
+ pipe_type: The pipe type from attributes.
+
+ Returns:
+ The span name with redacted pipe code if redaction is enabled,
+ otherwise the original span name.
+ """
+ if not self.redaction_config.redact_pipe_codes:
+ return original_span_name
+
+ # Rebuild with redacted pipe code
+ if pipe_type:
+ return pipe_type
+ else:
+ return OTelConstants.PIPE_CODE_REDACTED
+
+ def _build_redacted_generation_span_name(
+ self,
+ original_span_name: str,
+ pipe_code: str | None,
+ unit_job_id: str | None,
+ model_name: str | None,
+ output_class_name: str | None,
+ ) -> str:
+ """Build a redacted span name for generation spans.
+
+ Generation span names follow the format:
+ "{pipe_code}: {unit_job_id} ({model_name}) -> {output_desc}"
+ where output_desc is either "text" or the output class name.
+
+ Args:
+ original_span_name: The original span name from OTel.
+ pipe_code: The original pipe code from attributes.
+ unit_job_id: The unit job ID (e.g., "LLM_GEN_TEXT").
+ model_name: The model name.
+ output_class_name: The output class name (for object generation).
+
+ Returns:
+ The span name with redacted parts based on redaction config.
+ """
+ redact_pipe_codes = self.redaction_config.redact_pipe_codes
+ redact_class_names = self.redaction_config.redact_output_class_names
+
+ if not redact_pipe_codes and not redact_class_names:
+ return original_span_name
+
+ # Build output description
+ if output_class_name:
+ display_output = OTelConstants.OUTPUT_CLASS_REDACTED if redact_class_names else output_class_name
+ else:
+ display_output = "text"
+
+ # Build redacted pipe code
+ if redact_pipe_codes:
+ return f"{unit_job_id or 'unknown'} ({model_name or 'unknown'}) -> {display_output}"
+ elif pipe_code:
+ return f"{pipe_code}: {unit_job_id or 'unknown'} ({model_name or 'unknown'}) -> {display_output}"
+ else:
+ return f"{unit_job_id or 'unknown'} ({model_name or 'unknown'}) -> {display_output}"
+
+ def _get_redacted_pipe_code(self, pipe_code: str | None) -> str | None:
+ """Get the pipe code, redacted if config requires it.
+
+ Args:
+ pipe_code: The original pipe code.
+
+ Returns:
+ The original pipe code or redacted value based on config.
+ """
+ if not self.redaction_config.redact_pipe_codes:
+ return pipe_code
+ return OTelConstants.PIPE_CODE_REDACTED if pipe_code else None
+
+ def _get_redacted_output_class_name(self, output_class_name: str | None) -> str | None:
+ """Get the output class name, redacted if config requires it.
+
+ Args:
+ output_class_name: The original output class name.
+
+ Returns:
+ The original output class name or redacted value based on config.
+ """
+ if not self.redaction_config.redact_output_class_names:
+ return output_class_name
+ return OTelConstants.PIPE_CODE_REDACTED if output_class_name else None
+
+ def _get_base_properties(self, span: ReadableSpan, attributes: Mapping[str, AttributeValue]) -> dict[str, Any]:
+ """Get common properties for all span types."""
+ properties: dict[str, Any] = {}
+ if span.end_time and span.start_time:
+ properties[PostHogAttr.LATENCY] = (span.end_time - span.start_time) / 1e9
+
+ # Add trace/span IDs for PostHog trace grouping
+ span_context = span.get_span_context()
+ if span_context and span_context.is_valid:
+ properties[PostHogAttr.TRACE_ID] = f"{span_context.trace_id:032x}"
+ properties[PostHogAttr.SPAN_ID] = f"{span_context.span_id:016x}"
+ # Use redacted or full trace name based on redaction config
+ if self.redaction_config.redact_pipe_codes:
+ properties[PostHogAttr.TRACE_NAME] = attributes.get(PipelexSpanAttr.TRACE_NAME_REDACTED)
+ else:
+ properties[PostHogAttr.TRACE_NAME] = attributes.get(PipelexSpanAttr.TRACE_NAME)
+
+ # Add parent span ID for trace hierarchy
+ # Filter out virtual root parent (used to set trace_id for root spans)
+ if span.parent and span.parent.span_id != OTelConstants.OTEL_VIRTUAL_ROOT_PARENT_SPAN_ID:
+ properties[PostHogAttr.PARENT_ID] = f"{span.parent.span_id:016x}"
+
+ return properties
+
+ def _export_generation_span(self, span: ReadableSpan, attributes: Mapping[str, AttributeValue]) -> None:
+ """Export a GenAI generation span."""
+ properties = self._get_base_properties(span=span, attributes=attributes)
+ provider_operation_combo = f"{attributes.get(GenAISpanAttr.PROVIDER_NAME)}:{attributes.get(GenAISpanAttr.OPERATION_NAME)}"
+
+ # Get raw attribute values for redaction
+ pipe_code = cast("str | None", attributes.get(PipelexSpanAttr.PIPE_CODE))
+ output_class_name = cast("str | None", attributes.get(PipelexSpanAttr.OUTPUT_CLASS_NAME))
+ unit_job_id = cast("str | None", attributes.get(GenAISpanAttr.OPERATION_NAME))
+ model_name = cast("str | None", attributes.get(GenAISpanAttr.REQUEST_MODEL))
+
+ properties.update(
+ {
+ PostHogAttr.MODEL: model_name,
+ PostHogAttr.MODEL_ID: attributes.get(GenAISpanAttr.RESPONSE_MODEL),
+ PostHogAttr.PROVIDER: provider_operation_combo,
+ PostHogAttr.TEMPERATURE: attributes.get(GenAISpanAttr.REQUEST_TEMPERATURE),
+ PostHogAttr.MAX_TOKENS: attributes.get(GenAISpanAttr.REQUEST_MAX_TOKENS),
+ PostHogAttr.SEED: attributes.get(GenAISpanAttr.REQUEST_SEED),
+ PostHogAttr.OUTPUT_TYPE: attributes.get(GenAISpanAttr.OUTPUT_TYPE),
+ PostHogAttr.INPUT_TOKENS: attributes.get(GenAISpanAttr.USAGE_INPUT_TOKENS),
+ PostHogAttr.OUTPUT_TOKENS: attributes.get(GenAISpanAttr.USAGE_OUTPUT_TOKENS),
+ }
+ )
+
+ # Add content if available
+ if prompt := attributes.get(GenAISpanAttr.PROMPT_CONTENT):
+ properties[PostHogAttr.INPUT] = prompt
+ if completion := attributes.get(GenAISpanAttr.COMPLETION_CONTENT):
+ properties[PostHogAttr.OUTPUT_CHOICES] = completion
+
+ # Apply content redaction (removes or truncates content)
+ self._apply_content_redaction(properties)
+
+ # Build redacted span name for display
+ redacted_span_name = self._build_redacted_generation_span_name(
+ original_span_name=span.name,
+ pipe_code=pipe_code,
+ unit_job_id=unit_job_id,
+ model_name=model_name,
+ output_class_name=output_class_name,
+ )
+ properties[PostHogAttr.SPAN_NAME] = redacted_span_name
+
+ # Apply pipe code and output class name redaction to properties (only add if not None)
+ if redacted_pipe_code := self._get_redacted_pipe_code(pipe_code):
+ properties["pipe_code"] = redacted_pipe_code
+ if redacted_output_class_name := self._get_redacted_output_class_name(output_class_name):
+ properties["output_class_name"] = redacted_output_class_name
+
+ # Add pipeline_run_id (never redacted - useful for debugging and correlation)
+ pipeline_run_id = attributes.get(PipelexSpanAttr.PIPELINE_RUN_ID)
+ properties["pipeline_run_id"] = pipeline_run_id
+
+ log.verbose(
+ f"[OTel->PostHog] EXPORT $ai_generation:\n"
+ f" pipe_code='{properties.get('pipe_code')}'\n"
+ f" pipeline_run_id='{pipeline_run_id}'\n"
+ f" trace_id={properties.get(PostHogAttr.TRACE_ID)}\n"
+ f" span_id={properties.get(PostHogAttr.SPAN_ID)}\n"
+ f" parent_id={properties.get(PostHogAttr.PARENT_ID)}\n"
+ f" model={properties.get(PostHogAttr.MODEL)}"
+ )
+
+ self._capture_event(event=PostHogEvent.GENERATION, properties=properties)
+
+ def _export_pipe_span(self, span: ReadableSpan, attributes: Mapping[str, AttributeValue]) -> None:
+ """Export a pipe execution span."""
+ properties = self._get_base_properties(span=span, attributes=attributes)
+
+ # Get raw attribute values for redaction
+ pipe_code = cast("str | None", attributes.get(PipelexSpanAttr.PIPE_CODE))
+ pipe_type = cast("str | None", attributes.get(PipelexSpanAttr.PIPE_TYPE))
+
+ # Build redacted span name
+ # The trace name is established by a "trace start" event emitted at pipeline setup,
+ # which ensures PostHog receives the correct trace name before any pipe spans arrive.
+ redacted_span_name = self._build_redacted_pipe_span_name(
+ original_span_name=span.name,
+ pipe_type=pipe_type,
+ )
+
+ # Add pipeline_run_id (never redacted - useful for debugging and correlation)
+ pipeline_run_id = attributes.get(PipelexSpanAttr.PIPELINE_RUN_ID)
+
+ properties[PostHogAttr.SPAN_NAME] = redacted_span_name
+ properties["pipe_type"] = pipe_type
+ properties["pipe_category"] = attributes.get(PipelexSpanAttr.PIPE_CATEGORY)
+ properties["outcome"] = attributes.get(PipelexSpanAttr.OUTCOME)
+ properties["pipeline_run_id"] = pipeline_run_id
+
+ # Apply pipe code redaction (only add if not None, for consistency)
+ if redacted_pipe_code := self._get_redacted_pipe_code(pipe_code):
+ properties["pipe_code"] = redacted_pipe_code
+ log.verbose(
+ f"[OTel->PostHog] EXPORT $ai_span:\n"
+ f" pipe_code='{properties.get('pipe_code')}'\n"
+ f" pipeline_run_id='{pipeline_run_id}'\n"
+ f" $ai_span_name='{redacted_span_name}'\n"
+ f" trace_id={properties.get(PostHogAttr.TRACE_ID)}\n"
+ f" span_id={properties.get(PostHogAttr.SPAN_ID)}\n"
+ f" parent_id={properties.get(PostHogAttr.PARENT_ID)}"
+ )
+
+ self._capture_event(event=PostHogEvent.SPAN, properties=properties)
+
+ @override
+ def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
+ log.verbose(f"[OTel->PostHog] export() called with {len(spans)} span(s)")
+
+ for span in spans:
+ try:
+ attributes = span.attributes or {}
+ span_category_str = cast("str", attributes.get(PipelexSpanAttr.SPAN_CATEGORY))
+ span_category = SpanCategory(span_category_str)
+
+ span_ctx = span.get_span_context()
+ parent_id = f"{span.parent.span_id:016x}" if span.parent else "None"
+ trace_id_str = f"{span_ctx.trace_id:032x}" if span_ctx else "unknown"
+ span_id_str = f"{span_ctx.span_id:016x}" if span_ctx else "unknown"
+ pipe_code = attributes.get(PipelexSpanAttr.PIPE_CODE)
+ pipeline_run_id = attributes.get(PipelexSpanAttr.PIPELINE_RUN_ID)
+ trace_name = attributes.get(PipelexSpanAttr.TRACE_NAME)
+ log.verbose(
+ f"[OTel->PostHog] Processing span:\n"
+ f" trace_name='{trace_name}'\n"
+ f" trace_id={trace_id_str}\n"
+ f" span_id={span_id_str}\n"
+ f" span_category={span_category}\n"
+ f" pipeline_run_id='{pipeline_run_id}'\n"
+ f" pipe_code='{pipe_code}'\n"
+ f" parent_id={parent_id}"
+ )
+
+ match span_category:
+ case SpanCategory.INFERENCE:
+ self._export_generation_span(span=span, attributes=attributes)
+ case SpanCategory.PIPE:
+ self._export_pipe_span(span=span, attributes=attributes)
+
+ except Exception as exc:
+ # Fail silently to avoid breaking app
+ log.debug(f"Failed to export span to PostHog: {exc}")
+
+ return SpanExportResult.SUCCESS
+
+ @override
+ def shutdown(self) -> None:
+ pass
diff --git a/pipelex/system/telemetry/telemetry_config.py b/pipelex/system/telemetry/telemetry_config.py
index e1bd34f49..0039b1d1d 100644
--- a/pipelex/system/telemetry/telemetry_config.py
+++ b/pipelex/system/telemetry/telemetry_config.py
@@ -1,12 +1,25 @@
-from pydantic import Field
+from functools import partial
+
+from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
from pipelex.system.configuration.config_model import ConfigModel
-from pipelex.types import StrEnum
+from pipelex.system.telemetry.exceptions import TelemetryConfigValidationError
+from pipelex.tools.misc.dict_utils import apply_to_strings_recursive
+from pipelex.tools.misc.toml_utils import load_toml_from_path
+from pipelex.tools.secrets.secrets_provider_abstract import SecretsProviderAbstract
+from pipelex.tools.secrets.secrets_utils import (
+ UnknownVarPrefixError,
+ substitute_vars,
+)
+from pipelex.tools.typing.pydantic_utils import empty_list_factory_of, format_pydantic_validation_error
+from pipelex.types import Self, StrEnum
TELEMETRY_CONFIG_FILE_NAME = "telemetry.toml"
-class TelemetryMode(StrEnum):
+class PostHogMode(StrEnum):
+ """Mode for PostHog event tracking."""
+
ANONYMOUS = "anonymous"
OFF = "off"
IDENTIFIED = "identified"
@@ -14,21 +27,201 @@ class TelemetryMode(StrEnum):
@property
def is_enabled(self) -> bool:
match self:
- case TelemetryMode.ANONYMOUS:
+ case PostHogMode.ANONYMOUS:
+ return True
+ case PostHogMode.OFF:
+ return False
+ case PostHogMode.IDENTIFIED:
return True
- case TelemetryMode.OFF:
+
+ @property
+ def is_identified(self) -> bool:
+ match self:
+ case PostHogMode.ANONYMOUS:
return False
- case TelemetryMode.IDENTIFIED:
+ case PostHogMode.OFF:
+ return False
+ case PostHogMode.IDENTIFIED:
return True
+class PostHogTracingCaptureConfig(BaseModel):
+ """Privacy controls for what data to capture in PostHog spans."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ content: bool = Field(default=False, description="Capture prompt/completion content")
+ content_max_length: int | None = Field(default=None, description="Max length for captured content (None = unlimited)")
+ pipe_codes: bool = Field(default=False, description="Include pipe codes in span names/attributes")
+ output_class_names: bool = Field(default=False, description="Include output class names in span names/attributes")
+
+
+class PostHogTracingConfig(BaseModel):
+ """Configuration for AI span tracing to your PostHog."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ enabled: bool = Field(default=False, description="Send AI spans to your PostHog")
+ capture: PostHogTracingCaptureConfig = Field(
+ default_factory=PostHogTracingCaptureConfig, description="Privacy controls for data sent to your PostHog"
+ )
+
+
+class PostHogConfig(BaseModel):
+ """PostHog configuration for event tracking and span export."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ mode: PostHogMode = Field(default=PostHogMode.OFF, strict=False, description="Event tracking mode")
+ user_id: str | None = Field(default=None, description="Required when mode is 'identified'")
+ endpoint: str = Field(default="https://us.i.posthog.com", description="PostHog endpoint URL")
+ api_key: str = Field(description="PostHog project API key")
+ geoip: bool = Field(default=True, description="Enable GeoIP lookup")
+ debug: bool = Field(default=False, description="Enable PostHog debug mode")
+ redact_properties: list[str] = Field(default_factory=list, description="Event properties to redact")
+ tracing: PostHogTracingConfig = Field(default_factory=PostHogTracingConfig, description="AI span tracing to your PostHog")
+
+ @model_validator(mode="after")
+ def validate_user_id(self) -> Self:
+ if self.mode.is_identified and not self.user_id:
+ msg = "user_id is required when mode is 'identified'"
+ raise ValueError(msg)
+ return self
+
+
+class LangfuseConfig(BaseModel):
+ """Langfuse integration configuration."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ enabled: bool = Field(default=False, description="Enable Langfuse OTLP exporter")
+ endpoint: str | None = Field(default=None, description="Override for self-hosted Langfuse (defaults to cloud)")
+ public_key: str | None = Field(default=None, description="Langfuse public key")
+ secret_key: str | None = Field(default=None, description="Langfuse secret key")
+
+
+class OtlpExporterConfig(BaseModel):
+ """Configuration for an additional OTLP exporter."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ name: str = Field(description="Identifier for logging")
+ endpoint: str = Field(description="OTLP endpoint URL")
+ headers: dict[str, str] = Field(default_factory=dict, description="Headers for OTLP export")
+
+
class TelemetryConfig(ConfigModel):
- telemetry_mode: TelemetryMode = Field(strict=False)
- host: str
- project_api_key: str
- respect_dnt: bool
- redact: list[str]
- geoip_enabled: bool
- dry_mode_enabled: bool
- verbose_enabled: bool
- user_id: str
+ """Main telemetry configuration with nested sections."""
+
+ posthog: PostHogConfig = Field(description="PostHog configuration")
+ langfuse: LangfuseConfig = Field(default_factory=LangfuseConfig, description="Langfuse configuration")
+ otlp: list[OtlpExporterConfig] = Field(default_factory=empty_list_factory_of(OtlpExporterConfig), description="Additional OTLP exporters")
+ custom_telemetry_allowed_modes: dict[str, bool] = Field(
+ default_factory=dict,
+ description="Which integration modes allow custom telemetry (e.g. cli=true, pytest=false)",
+ )
+
+ def is_custom_telemetry_allowed_for_mode(self, mode: str) -> bool:
+ """Check if custom telemetry is allowed for the given integration mode.
+
+ Args:
+ mode: The integration mode string to check.
+
+ Returns:
+ True if custom telemetry is allowed for this mode, False otherwise.
+ """
+ return self.custom_telemetry_allowed_modes.get(mode, False)
+
+
+class TelemetryRedactionConfig(BaseModel):
+ """Configuration for what telemetry data to redact at export time.
+
+ This config is passed to span exporters so they can apply appropriate
+ redaction rules before sending telemetry data to their destinations.
+ """
+
+ model_config = ConfigDict(frozen=True)
+
+ redact_content: bool = False
+ redact_pipe_codes: bool = False
+ redact_output_class_names: bool = False
+ content_max_length: int | None = None
+
+ @classmethod
+ def make_from_posthog_config(cls, posthog_config: PostHogConfig) -> Self:
+ """Create from PostHogConfig (inverse of capture settings).
+
+ Args:
+ posthog_config: The user's PostHog configuration.
+
+ Returns:
+ A TelemetryRedactionConfig with redaction settings derived from the config.
+ """
+ return cls(
+ redact_content=not posthog_config.tracing.capture.content,
+ redact_pipe_codes=not posthog_config.tracing.capture.pipe_codes,
+ redact_output_class_names=not posthog_config.tracing.capture.output_class_names,
+ content_max_length=posthog_config.tracing.capture.content_max_length,
+ )
+
+ @classmethod
+ def pipelex_config(cls) -> Self:
+ """Create config for Pipelex telemetry (redact everything).
+
+ Pipelex internal telemetry always redacts sensitive data like content,
+ pipe codes, and output class names to protect user privacy.
+
+ Returns:
+ A TelemetryRedactionConfig with all redaction options enabled.
+ """
+ return cls(redact_content=True, redact_pipe_codes=True, redact_output_class_names=True)
+
+ @classmethod
+ def no_redaction(cls) -> Self:
+ """Create config with no redaction (pass-through).
+
+ Use this when you want to explicitly indicate no redaction should occur,
+ rather than relying on default values.
+
+ Returns:
+ A TelemetryRedactionConfig with all redaction options disabled.
+ """
+ return cls()
+
+
+def load_telemetry_config(path: str, secrets_provider: SecretsProviderAbstract) -> TelemetryConfig:
+ """Load telemetry configuration from a TOML file with variable substitution.
+
+ Supports variable placeholders in string values:
+ - ${VAR_NAME} -> use secrets provider by default
+ - ${env:ENV_VAR_NAME} -> force use environment variable
+ - ${secret:SECRET_NAME} -> force use secrets provider
+ - ${env:ENV_VAR|secret:SECRET} -> try env first, then secret as fallback
+
+ Args:
+ path: Path to the telemetry.toml configuration file.
+ secrets_provider: Provider for resolving secret/env variable placeholders.
+
+ Returns:
+ Validated TelemetryConfig instance.
+
+ Raises:
+ TelemetryConfigValidationError: If configuration is invalid or variable substitution fails.
+ """
+ telemetry_config_toml_raw = load_toml_from_path(path=path)
+
+ # Apply variable substitution to all string values (keep placeholders for missing vars)
+ substitute_vars_with_provider = partial(substitute_vars, secrets_provider=secrets_provider, raise_on_missing_var=False)
+ try:
+ telemetry_config_toml = apply_to_strings_recursive(telemetry_config_toml_raw, substitute_vars_with_provider)
+ except UnknownVarPrefixError as exc:
+ msg = f"Variable substitution failed in telemetry configuration '{path}': {exc}"
+ raise TelemetryConfigValidationError(msg) from exc
+
+ try:
+ telemetry_config = TelemetryConfig.model_validate(telemetry_config_toml)
+ except ValidationError as exc:
+ validation_error_msg = format_pydantic_validation_error(exc)
+ msg = f"Invalid telemetry configuration in '{path}':\n{validation_error_msg}"
+ raise TelemetryConfigValidationError(msg) from exc
+ return telemetry_config
diff --git a/pipelex/system/telemetry/telemetry_factory.py b/pipelex/system/telemetry/telemetry_factory.py
new file mode 100644
index 000000000..46bb25df6
--- /dev/null
+++ b/pipelex/system/telemetry/telemetry_factory.py
@@ -0,0 +1,82 @@
+import os
+
+from pipelex import log
+from pipelex.system.configuration.config_loader import config_manager
+from pipelex.system.environment import is_env_var_truthy
+from pipelex.system.pipelex_service.exceptions import (
+ GatewayApiKeyMissingError,
+ GatewayDoNotTrackConflictError,
+ GatewayTelemetryManagerInjectedError,
+)
+from pipelex.system.pipelex_service.pipelex_details import PIPELEX_GATEWAY_API_KEY_VAR
+from pipelex.system.runtime import IntegrationMode
+from pipelex.system.telemetry.otel_constants import OTelConstants
+from pipelex.system.telemetry.telemetry_config import TELEMETRY_CONFIG_FILE_NAME, PostHogMode, TelemetryConfig, load_telemetry_config
+from pipelex.system.telemetry.telemetry_manager import TelemetryManager
+from pipelex.system.telemetry.telemetry_manager_abstract import (
+ TelemetryManagerAbstract,
+ TelemetryManagerNoOp,
+)
+from pipelex.tools.secrets.secrets_provider_abstract import SecretsProviderAbstract
+
+
+def make_telemetry_manager(
+ secrets_provider: SecretsProviderAbstract,
+ integration_mode: IntegrationMode,
+ is_pipelex_telemetry_enabled: bool,
+ telemetry_config: TelemetryConfig | None,
+ injected_telemetry_manager: TelemetryManagerAbstract | None,
+) -> TelemetryManagerAbstract:
+ gateway_api_key: str | None = None
+ if is_pipelex_telemetry_enabled:
+ # Cannot inject custom TelemetryManager when gateway is enabled
+ if injected_telemetry_manager is not None:
+ raise GatewayTelemetryManagerInjectedError
+
+ # Get gateway API key for telemetry distinct_id
+ gateway_api_key = secrets_provider.get_optional_secret(PIPELEX_GATEWAY_API_KEY_VAR)
+ if not gateway_api_key:
+ raise GatewayApiKeyMissingError
+
+ # Always load telemetry config first to determine allowed modes
+ if not telemetry_config:
+ telemetry_config_path = os.path.join(config_manager.pipelex_config_dir, TELEMETRY_CONFIG_FILE_NAME)
+ telemetry_config = load_telemetry_config(path=telemetry_config_path, secrets_provider=secrets_provider)
+
+ allows_custom_telemetry = telemetry_config.is_custom_telemetry_allowed_for_mode(integration_mode)
+
+ chosen_telemetry_manager: TelemetryManagerAbstract
+ if allows_custom_telemetry or is_pipelex_telemetry_enabled:
+ # Always respect DO_NOT_TRACK env var
+ if is_env_var_truthy(OTelConstants.DO_NOT_TRACK_ENV_VAR_KEY):
+ if is_pipelex_telemetry_enabled:
+ # Gateway requires telemetry but DNT is set - we respect DNT
+ raise GatewayDoNotTrackConflictError(dnt_env_var=OTelConstants.DO_NOT_TRACK_ENV_VAR_KEY)
+ chosen_telemetry_manager = TelemetryManagerNoOp()
+ log.debug(f"Telemetry is disabled by env var '{OTelConstants.DO_NOT_TRACK_ENV_VAR_KEY}'")
+ return chosen_telemetry_manager
+
+ match telemetry_config.posthog.mode:
+ case PostHogMode.OFF:
+ if is_pipelex_telemetry_enabled:
+ # Gateway requires telemetry - create manager with only Pipelex telemetry
+ chosen_telemetry_manager = TelemetryManager(
+ telemetry_config=telemetry_config,
+ pipelex_telemetry_enabled=True,
+ gateway_api_key=gateway_api_key,
+ )
+ log.debug("Custom telemetry is off, but Pipelex Gateway telemetry is enabled")
+ else:
+ chosen_telemetry_manager = TelemetryManagerNoOp()
+ log.debug("Telemetry is disabled because posthog.mode is set to 'off'")
+ case PostHogMode.ANONYMOUS | PostHogMode.IDENTIFIED:
+ chosen_telemetry_manager = injected_telemetry_manager or TelemetryManager(
+ telemetry_config=telemetry_config,
+ pipelex_telemetry_enabled=is_pipelex_telemetry_enabled,
+ gateway_api_key=gateway_api_key,
+ )
+ else:
+ chosen_telemetry_manager = TelemetryManagerNoOp()
+ log.verbose(f"Telemetry is disabled because the integration mode '{integration_mode}' does not allow it")
+
+ return chosen_telemetry_manager
diff --git a/pipelex/system/telemetry/telemetry_manager.py b/pipelex/system/telemetry/telemetry_manager.py
index 9067670f9..7aacd9f7d 100644
--- a/pipelex/system/telemetry/telemetry_manager.py
+++ b/pipelex/system/telemetry/telemetry_manager.py
@@ -1,48 +1,107 @@
from contextlib import contextmanager
-from typing import Any, Callable, Generator
+from typing import TYPE_CHECKING, Any, Generator
import posthog
-from posthog import Posthog, new_context, tag # type: ignore[attr-defined]
+from opentelemetry.trace import Tracer as OTelTracer
+from posthog import Posthog, new_context # type: ignore[attr-defined]
from posthog.args import ExceptionArg, OptionalCaptureArgs
from typing_extensions import Unpack, override
+from pipelex.plugins.portkey.portkey_constants import PortkeyEnvVar
+from pipelex.system.environment import is_env_var_truthy
from pipelex.system.exceptions import PipelexError
+from pipelex.system.pipelex_service.pipelex_details import PipelexDetails
from pipelex.system.runtime import IntegrationMode
-from pipelex.system.telemetry.events import EventName, EventProperty, Setting
-from pipelex.system.telemetry.telemetry_config import TelemetryConfig, TelemetryMode
+from pipelex.system.telemetry.events import EventName, EventProperty
+from pipelex.system.telemetry.otel_constants import OTelConstants, PostHogAttr, PostHogEvent
+from pipelex.system.telemetry.otel_factory import OtelFactory
+from pipelex.system.telemetry.telemetry_config import PostHogMode, TelemetryConfig, TelemetryRedactionConfig
from pipelex.system.telemetry.telemetry_manager_abstract import TelemetryManagerAbstract
from pipelex.tools.log.log import log
-from pipelex.tools.misc.package_utils import get_package_version
-DO_NOT_TRACK_ENV_VAR_KEY = "DO_NOT_TRACK"
+if TYPE_CHECKING:
+ from opentelemetry.sdk.trace import TracerProvider as OTelTracerProvider
class TelemetryManager(TelemetryManagerAbstract):
PRIVACY_NOTICE = "[Privacy: exception message redacted]"
- def __init__(self, telemetry_config: TelemetryConfig):
+ def __init__(
+ self,
+ telemetry_config: TelemetryConfig,
+ pipelex_telemetry_enabled: bool = False,
+ gateway_api_key: str | None = None,
+ ):
+ """Initialize the TelemetryManager with custom and optional Pipelex telemetry.
+
+ Args:
+ telemetry_config: User's telemetry configuration.
+ pipelex_telemetry_enabled: Whether Pipelex internal telemetry is enabled (for gateway).
+ gateway_api_key: The user's Pipelex Gateway API key (required if pipelex_telemetry_enabled).
+ """
self.telemetry_config = telemetry_config
+ self._pipelex_telemetry_enabled = pipelex_telemetry_enabled
+ self._pipelex_distinct_id: str | None = None
- # Create PostHog client
- self.posthog_client = Posthog(
- project_api_key=self.telemetry_config.project_api_key,
- host=self.telemetry_config.host,
- disable_geoip=not self.telemetry_config.geoip_enabled,
- debug=self.telemetry_config.verbose_enabled,
- on_error=self._handle_transmission_error,
- )
+ # Create custom PostHog client only if user's telemetry is enabled
+ self.custom_posthog_client: Posthog | None = None
+ if telemetry_config.posthog.mode.is_enabled:
+ self.custom_posthog_client = Posthog(
+ project_api_key=self.telemetry_config.posthog.api_key,
+ host=self.telemetry_config.posthog.endpoint,
+ disable_geoip=not self.telemetry_config.posthog.geoip,
+ debug=self.telemetry_config.posthog.debug,
+ on_error=self._handle_transmission_error,
+ )
- # Store original capture_exception method
- self._original_capture_exception: Callable[..., Any] = self.posthog_client.capture_exception
+ # Create Pipelex PostHog client if gateway telemetry is enabled
+ self.pipelex_posthog_client: Posthog | None = None
+ if pipelex_telemetry_enabled:
+ if gateway_api_key:
+ self._pipelex_distinct_id = PipelexDetails.make_distinct_id(gateway_api_key)
+ self.pipelex_posthog_client = Posthog(
+ project_api_key=PipelexDetails.POSTHOG_PROJECT_API_KEY,
+ host=PipelexDetails.POSTHOG_HOST,
+ disable_geoip=False, # GeoIP enabled for Pipelex telemetry
+ debug=self.telemetry_config.posthog.debug,
+ on_error=self._handle_pipelex_transmission_error,
+ )
+ log.verbose("Pipelex Gateway telemetry enabled")
+
+ # Create OTel tracer for AI tracing if enabled
+ self._otel_tracer: OTelTracer | None
+ self._tracer_provider: OTelTracerProvider | None
+ if telemetry_config.posthog.tracing.enabled or pipelex_telemetry_enabled:
+ # AI tracing is enabled if either custom or pipelex telemetry wants it
+ # Create redaction config from user settings for custom telemetry
+ custom_redaction_config = TelemetryRedactionConfig.make_from_posthog_config(posthog_config=telemetry_config.posthog)
+ self._otel_tracer, self._tracer_provider = OtelFactory.make_ai_tracer(
+ user_id=telemetry_config.posthog.user_id,
+ custom_posthog_client=self.custom_posthog_client if telemetry_config.posthog.tracing.enabled else None,
+ custom_redaction_config=custom_redaction_config,
+ pipelex_posthog_client=self.pipelex_posthog_client,
+ pipelex_distinct_id=self._pipelex_distinct_id,
+ otlp_exporters=telemetry_config.otlp,
+ langfuse_config=telemetry_config.langfuse,
+ )
+ log.verbose("AI tracing enabled: OpenTelemetry tracer created")
+ else:
+ self._otel_tracer = None
+ self._tracer_provider = None
+ log.verbose("AI tracing disabled: No OpenTelemetry tracer created")
- # Wrap capture_exception to sanitize before sending
- self._wrap_capture_exception()
+ # Wrap capture_exception to sanitize before sending (for whichever clients are enabled)
+ if self.custom_posthog_client:
+ self._wrap_capture_exception(self.custom_posthog_client)
+ if self.pipelex_posthog_client:
+ self._wrap_capture_exception(self.pipelex_posthog_client)
+ # Set global PostHog settings (prefer custom client, fall back to pipelex client)
posthog.privacy_mode = True
- posthog.default_client = self.posthog_client
+ posthog.default_client = self.custom_posthog_client or self.pipelex_posthog_client
def _handle_transmission_error(self, error: Exception | None, _items: list[dict[str, Any]]) -> None:
- """Handle errors that occur during telemetry transmission.
+ """Handle errors that occur during custom telemetry transmission.
Args:
error: The transmission error that occurred
@@ -51,8 +110,23 @@ class TelemetryManager(TelemetryManagerAbstract):
if error:
log.error(f"Telemetry transmission error: {error}")
- def _wrap_capture_exception(self) -> None:
- """Wrap the PostHog capture_exception method to sanitize exception messages."""
+ def _handle_pipelex_transmission_error(self, error: Exception | None, _items: list[dict[str, Any]]) -> None:
+ """Handle errors that occur during Pipelex telemetry transmission.
+
+ Args:
+ error: The transmission error that occurred
+ _items: List of telemetry items that failed to send
+ """
+ if error:
+ log.debug(f"Pipelex telemetry transmission error: {error}")
+
+ def _wrap_capture_exception(self, client: Posthog) -> None:
+ """Wrap a PostHog client's capture_exception method to sanitize exception messages.
+
+ Args:
+ client: The PostHog client to wrap.
+ """
+ original_capture_exception = client.capture_exception
def sanitized_capture_exception(
exception: ExceptionArg | None = None,
@@ -62,7 +136,7 @@ class TelemetryManager(TelemetryManagerAbstract):
if exception and isinstance(exception, PipelexError):
# Create a new exception with sanitized message while preserving the class type
# Use __new__ to create an instance without calling __init__, which may require extra args
- # This creates a "shell" instance with NO custom attributes (e.g., no tested_concept, wanted_concept, etc.)
+ # This creates a "shell" instance with NO custom attributes
exception_type = type(exception)
sanitized_exception = exception_type.__new__(exception_type)
@@ -77,40 +151,48 @@ class TelemetryManager(TelemetryManagerAbstract):
# Note: No custom attributes (tested_concept, wanted_concept, etc.) are present
# because we used __new__() without calling __init__(). The __dict__ is already empty.
- return self._original_capture_exception(sanitized_exception, **kwargs)
+ return original_capture_exception(sanitized_exception, **kwargs)
else:
# For non-PipelexError, capture as-is (or auto-detect current exception)
- return self._original_capture_exception(exception, **kwargs)
+ return original_capture_exception(exception, **kwargs)
- # Replace the method
- self.posthog_client.capture_exception = sanitized_capture_exception # type: ignore[method-assign]
+ client.capture_exception = sanitized_capture_exception # type: ignore[method-assign]
@override
def setup(self, integration_mode: IntegrationMode):
- if telemetry_mode := TelemetryManagerAbstract.telemetry_was_just_enabled():
- package_version = get_package_version()
- with new_context():
- tag(name=EventProperty.INTEGRATION, value=integration_mode)
- tag(name=EventProperty.PIPELEX_VERSION, value=package_version)
- tag(name=EventProperty.SETTING, value=Setting.TELEMETRY_MODE)
- self.posthog_client.capture(
- EventName.TELEMETRY_JUST_ENABLED,
- properties={
- EventProperty.TELEMETRY_MODE: telemetry_mode,
- EventProperty.PIPELEX_VERSION: package_version,
- },
- )
+ pass
@override
def teardown(self):
- if self.posthog_client:
+ # First, shutdown the TracerProvider to flush all pending spans
+ # This MUST happen before PostHog shutdown, otherwise spans won't be exported
+ if self._tracer_provider:
try:
- # PostHog client has a shutdown method to flush pending events
- # and close background threads
- self.posthog_client.shutdown()
+ log.verbose("Shutting down OTel TracerProvider (flushing pending spans)...")
+ self._tracer_provider.shutdown()
+ log.verbose("OTel TracerProvider shutdown complete")
except Exception as exc:
# Suppress any shutdown errors to avoid cascading failures
- log.debug(f"Error during PostHog shutdown: {exc}")
+ log.debug(f"Error during TracerProvider shutdown: {exc}")
+
+ # Then shutdown custom PostHog client
+ if self.custom_posthog_client:
+ try:
+ self.custom_posthog_client.shutdown()
+ except Exception as exc:
+ # Suppress any shutdown errors to avoid cascading failures
+ log.debug(f"Error during custom PostHog shutdown: {exc}")
+
+ # Then shutdown Pipelex PostHog client
+ if self.pipelex_posthog_client:
+ try:
+ self.pipelex_posthog_client.shutdown()
+ except Exception as exc:
+ # Suppress any shutdown errors to avoid cascading failures
+ log.debug(f"Error during Pipelex PostHog shutdown: {exc}")
+
+ # Clear singleton instance
+ TelemetryManagerAbstract.clear_instance()
@override
def track_event(self, event_name: EventName, properties: dict[EventProperty, Any] | None = None):
@@ -119,45 +201,53 @@ class TelemetryManager(TelemetryManagerAbstract):
# and to remove the properties that are in the redact list
tracked_properties: dict[str, Any]
if properties:
- tracked_properties = {key: value for key, value in properties.items() if key not in self.telemetry_config.redact}
+ tracked_properties = {key: value for key, value in properties.items() if key not in self.telemetry_config.posthog.redact_properties}
else:
tracked_properties = {}
- match self.telemetry_config.telemetry_mode:
- case TelemetryMode.ANONYMOUS:
+
+ # Always track to Pipelex PostHog if enabled (independent of posthog.mode)
+ if self._pipelex_telemetry_enabled:
+ self._track_to_pipelex(event_name=event_name, properties=tracked_properties)
+
+ # Track to custom PostHog based on user's posthog.mode
+ match self.telemetry_config.posthog.mode:
+ case PostHogMode.ANONYMOUS:
self._track_anonymous_event(event_name=event_name, properties=tracked_properties)
- case TelemetryMode.IDENTIFIED:
- if not self.telemetry_config.user_id:
+ case PostHogMode.IDENTIFIED:
+ if not self.telemetry_config.posthog.user_id:
log.error(f"Could not track event '{event_name}' as identified because user_id is not set, tracking as anonymous")
self._track_anonymous_event(event_name=event_name, properties=tracked_properties)
else:
- self._track_identified_event(event_name=event_name, properties=tracked_properties, user_id=self.telemetry_config.user_id)
- case TelemetryMode.OFF:
- log.verbose(f"Telemetry is off, skipping event '{event_name}'")
+ self._track_identified_event(
+ event_name=event_name,
+ properties=tracked_properties,
+ user_id=self.telemetry_config.posthog.user_id,
+ )
+ case PostHogMode.OFF:
+ log.verbose(f"Custom telemetry is off, skipping event '{event_name}' for custom client")
def _track_anonymous_event(self, event_name: str, properties: dict[str, Any]):
- if not self.posthog_client:
+ if not self.custom_posthog_client:
+ log.error("Could not track event to custom telemetry because custom_posthog_client is not set")
return
- if self.telemetry_config.dry_mode_enabled:
- if properties:
- log.debug(properties, title=f"Tracking anonymous event '{event_name}'. Properties")
- else:
- log.debug(f"Tracking anonymous event '{event_name}'. No properties.")
- else:
- properties["$process_person_profile"] = False
- self.posthog_client.capture(event_name, properties=properties)
- log.verbose(f"Tracked anonymous event '{event_name}' with properties: {properties}")
+ properties[PostHogAttr.PROCESS_PERSON_PROFILE] = False
+ self.custom_posthog_client.capture(event_name, properties=properties)
+ log.verbose(f"Tracked anonymous event '{event_name}' with properties: {properties}")
def _track_identified_event(self, event_name: str, properties: dict[str, Any], user_id: str):
- if not self.posthog_client:
+ if not self.custom_posthog_client:
+ log.error("Could not track event to custom telemetry because custom_posthog_client is not set")
return
- if self.telemetry_config.dry_mode_enabled:
- if properties:
- log.debug(properties, title=f"Tracking identified event '{event_name}'. Properties")
- else:
- log.debug(f"Tracking identified event '{event_name}'. No properties.")
- else:
- self.posthog_client.capture(event_name, distinct_id=user_id, properties=properties)
- log.verbose(f"Tracked identified event '{event_name}' with properties: {properties}")
+ self.custom_posthog_client.capture(event_name, distinct_id=user_id, properties=properties)
+ log.verbose(f"Tracked identified event '{event_name}' with properties: {properties}")
+
+ def _track_to_pipelex(self, event_name: str, properties: dict[str, Any]):
+ """Track event to Pipelex's PostHog (always identified)."""
+ if not self.pipelex_posthog_client or not self._pipelex_distinct_id:
+ log.error("Could not track event to Pipelex telemetry because pipelex_posthog_client or _pipelex_distinct_id is not set")
+ return
+ self.pipelex_posthog_client.capture(event_name, distinct_id=self._pipelex_distinct_id, properties=properties)
+ log.verbose(f"Tracked event '{event_name}' to Pipelex telemetry")
@override
@contextmanager
@@ -165,3 +255,121 @@ class TelemetryManager(TelemetryManagerAbstract):
"""Context manager that uses PostHog's new_context when telemetry is enabled."""
with new_context():
yield
+
+ @override
+ def is_portkey_logging_enabled(self, is_debug_configured: bool) -> bool:
+ is_debug: bool = is_debug_configured
+ if not is_debug and is_env_var_truthy(PortkeyEnvVar.FORCE_PORTKEY_DEBUG):
+ log.info(f"Force-enabling Portkey logging (debug mode) because '{PortkeyEnvVar.FORCE_PORTKEY_DEBUG}' is set")
+ is_debug = True
+ if is_debug and is_env_var_truthy(OTelConstants.DO_NOT_TRACK_ENV_VAR_KEY):
+ log.warning(
+ f"Disabling Portkey logging (debug mode) because '{OTelConstants.DO_NOT_TRACK_ENV_VAR_KEY}' is set and that setting takes precedence"
+ )
+ is_debug = False
+ return is_debug
+
+ @override
+ def is_portkey_tracing_enabled(self) -> bool:
+ if is_env_var_truthy(PortkeyEnvVar.FORCE_PORTKEY_TRACING):
+ log.info(f"Force-enabling Portkey tracing because '{PortkeyEnvVar.FORCE_PORTKEY_TRACING}' is set")
+ return True
+ else:
+ return False
+
+ @override
+ def get_otel_tracer(self) -> OTelTracer | None:
+ return self._otel_tracer
+
+ @property
+ @override
+ def capture_content_enabled(self) -> bool:
+ return self.telemetry_config.posthog.tracing.capture.content
+
+ @property
+ @override
+ def capture_pipe_codes_enabled(self) -> bool:
+ return self.telemetry_config.posthog.tracing.capture.pipe_codes
+
+ @property
+ @override
+ def capture_output_class_name_enabled(self) -> bool:
+ return self.telemetry_config.posthog.tracing.capture.output_class_names
+
+ @property
+ @override
+ def capture_content_max_length(self) -> int | None:
+ return self.telemetry_config.posthog.tracing.capture.content_max_length
+
+ @property
+ @override
+ def is_langfuse_enabled(self) -> bool:
+ return self.telemetry_config.langfuse.enabled
+
+ @property
+ @override
+ def is_pipelex_telemetry_enabled(self) -> bool:
+ return self._pipelex_telemetry_enabled
+
+ @override
+ def handle_trace_start(self, trace_name: str, trace_name_redacted: str, trace_id: int) -> None:
+ """Hook to do something when a trace starts.
+
+ Emits a trace start event to establish the trace name in PostHog.
+ We send a minimal $ai_span event with the trace_name as the span name.
+ This event is sent directly (not via OTel spans) to ensure it arrives
+ before any batched pipe spans, establishing the correct trace name.
+
+ Args:
+ trace_name: Full trace name with pipe code (for custom telemetry).
+ trace_name_redacted: Redacted trace name without pipe code (for Pipelex telemetry).
+ trace_id: The trace ID.
+ """
+ log.verbose(
+ f"[Telemetry] Emitting trace start event:\n"
+ f" trace_name='{trace_name}'\n"
+ f" trace_name_redacted='{trace_name_redacted}'\n"
+ f" trace_id={trace_id:032x}"
+ )
+
+ # Send to custom PostHog if configured (uses full trace name based on user's capture settings)
+ if self.custom_posthog_client and self.telemetry_config.posthog.tracing.enabled:
+ # Use full or redacted trace name based on user's capture_pipe_codes setting
+ custom_trace_name = trace_name if self.telemetry_config.posthog.tracing.capture.pipe_codes else trace_name_redacted
+ custom_properties: dict[str, Any] = {
+ PostHogAttr.TRACE_ID: f"{trace_id:032x}",
+ PostHogAttr.SPAN_NAME: custom_trace_name,
+ PostHogAttr.TRACE_NAME: custom_trace_name,
+ }
+ if self.telemetry_config.posthog.user_id:
+ self.custom_posthog_client.capture(
+ distinct_id=self.telemetry_config.posthog.user_id,
+ event=PostHogEvent.SPAN,
+ properties=custom_properties,
+ )
+ else:
+ custom_properties[PostHogAttr.PROCESS_PERSON_PROFILE] = False
+ self.custom_posthog_client.capture(
+ event=PostHogEvent.SPAN,
+ properties=custom_properties,
+ )
+
+ # Send to Pipelex PostHog if gateway telemetry is enabled (always uses redacted trace name)
+ if self.pipelex_posthog_client:
+ pipelex_properties: dict[str, Any] = {
+ PostHogAttr.TRACE_ID: f"{trace_id:032x}",
+ PostHogAttr.SPAN_NAME: trace_name_redacted,
+ PostHogAttr.TRACE_NAME: trace_name_redacted,
+ }
+ if self._pipelex_distinct_id:
+ self.pipelex_posthog_client.capture(
+ distinct_id=self._pipelex_distinct_id,
+ event=PostHogEvent.SPAN,
+ properties=pipelex_properties,
+ )
+ else:
+ pipelex_properties[PostHogAttr.PROCESS_PERSON_PROFILE] = False
+ self.pipelex_posthog_client.capture(
+ event=PostHogEvent.SPAN,
+ properties=pipelex_properties,
+ )
diff --git a/pipelex/system/telemetry/telemetry_manager_abstract.py b/pipelex/system/telemetry/telemetry_manager_abstract.py
index b57403c88..b353eb0ab 100644
--- a/pipelex/system/telemetry/telemetry_manager_abstract.py
+++ b/pipelex/system/telemetry/telemetry_manager_abstract.py
@@ -1,23 +1,86 @@
-from abc import ABC, abstractmethod
+from abc import abstractmethod
from contextlib import contextmanager
from typing import Any, Generator
+from opentelemetry.trace import Tracer as OTelTracer
from typing_extensions import override
+from pipelex.system.registries.singleton import ABCSingletonMeta, MetaSingleton
from pipelex.system.runtime import IntegrationMode
from pipelex.system.telemetry.events import EventName, EventProperty
-from pipelex.system.telemetry.telemetry_config import TelemetryMode
-class TelemetryManagerAbstract(ABC):
- telemetry_mode_just_set: TelemetryMode | None = None
+class TelemetryManagerAbstract(metaclass=ABCSingletonMeta):
+ @classmethod
+ def clear_instance(cls) -> None:
+ """Clear the singleton instance from MetaSingleton registry."""
+ MetaSingleton.clear_subclass_instances(TelemetryManagerAbstract)
+
+ @classmethod
+ def get_instance(cls) -> "TelemetryManagerAbstract | None":
+ """Get the singleton instance from MetaSingleton registry.
+
+ This provides a way to access the telemetry manager without importing from hub,
+ avoiding circular dependency issues.
+ """
+ return MetaSingleton.get_subclass_instance(TelemetryManagerAbstract) # type: ignore[type-abstract]
@classmethod
- def telemetry_was_just_enabled(cls) -> TelemetryMode | None:
- if cls.telemetry_mode_just_set is None:
+ def get_instance_tracer(cls) -> OTelTracer | None:
+ """Get the tracer from the singleton instance.
+
+ This provides a way to access the tracer without importing from hub,
+ avoiding circular dependency issues.
+ """
+ instance = cls.get_instance()
+ if instance is None:
return None
- else:
- return cls.telemetry_mode_just_set if cls.telemetry_mode_just_set.is_enabled else None
+ return instance.get_otel_tracer()
+
+ @classmethod
+ def is_capture_pipe_codes_enabled(cls) -> bool:
+ """Check if pipe code capture is enabled for telemetry.
+
+ When this returns False, pipe codes should be redacted from span names
+ and attributes, and excluded from run IDs.
+
+ Returns:
+ True if pipe code capture is enabled, False otherwise (including when
+ no telemetry manager is configured).
+ """
+ instance = cls.get_instance()
+ if instance is None:
+ return False
+ return instance.capture_pipe_codes_enabled
+
+ @classmethod
+ def is_capture_output_class_name_enabled(cls) -> bool:
+ """Check if output class name capture is enabled for telemetry.
+
+ When this returns False, output class names should be redacted from span names
+ and attributes.
+
+ Returns:
+ True if output class name capture is enabled, False otherwise (including when
+ no telemetry manager is configured).
+ """
+ instance = cls.get_instance()
+ if instance is None:
+ return False
+ return instance.capture_output_class_name_enabled
+
+ @classmethod
+ def get_langfuse_enabled(cls) -> bool:
+ """Check if Langfuse OTLP exporter is enabled for telemetry.
+
+ Returns:
+ True if Langfuse OTLP exporter is enabled, False otherwise (including when
+ no telemetry manager is configured).
+ """
+ instance = cls.get_instance()
+ if instance is None:
+ return False
+ return instance.is_langfuse_enabled
@abstractmethod
def setup(self, integration_mode: IntegrationMode):
@@ -36,6 +99,58 @@ class TelemetryManagerAbstract(ABC):
def telemetry_context(self) -> Generator[None, None, None]:
"""Safe context manager for telemetry that works whether telemetry is enabled or not."""
+ @abstractmethod
+ def is_portkey_logging_enabled(self, is_debug_configured: bool) -> bool:
+ pass
+
+ @abstractmethod
+ def is_portkey_tracing_enabled(self) -> bool:
+ pass
+
+ @abstractmethod
+ def get_otel_tracer(self) -> OTelTracer | None:
+ """Get the OpenTelemetry tracer for GenAI spans, if configured."""
+
+ @property
+ @abstractmethod
+ def capture_content_enabled(self) -> bool:
+ """Whether prompt/completion content should be captured in span attributes."""
+
+ @property
+ @abstractmethod
+ def capture_pipe_codes_enabled(self) -> bool:
+ """Whether pipe codes should appear in span names and attributes."""
+
+ @property
+ @abstractmethod
+ def capture_output_class_name_enabled(self) -> bool:
+ """Whether output class names should appear in span names and attributes."""
+
+ @property
+ @abstractmethod
+ def capture_content_max_length(self) -> int | None:
+ """Maximum length for captured content, or None if unlimited."""
+
+ @property
+ @abstractmethod
+ def is_langfuse_enabled(self) -> bool:
+ """Whether Langfuse OTLP exporter is enabled."""
+
+ @property
+ @abstractmethod
+ def is_pipelex_telemetry_enabled(self) -> bool:
+ """Whether Pipelex internal telemetry is enabled (for gateway usage)."""
+
+ @abstractmethod
+ def handle_trace_start(self, trace_name: str, trace_name_redacted: str, trace_id: int) -> None:
+ """Hook to do something when a trace starts.
+
+ Args:
+ trace_name: Full trace name with pipe code (for custom telemetry).
+ trace_name_redacted: Redacted trace name without pipe code (for Pipelex telemetry).
+ trace_id: The trace ID.
+ """
+
class TelemetryManagerNoOp(TelemetryManagerAbstract):
@override
@@ -44,7 +159,8 @@ class TelemetryManagerNoOp(TelemetryManagerAbstract):
@override
def teardown(self):
- pass
+ # Clear singleton instance to allow telemetry to be re-enabled in the same process
+ TelemetryManagerAbstract.clear_instance()
@override
def track_event(self, event_name: EventName, properties: dict[EventProperty, Any] | None = None):
@@ -55,3 +171,49 @@ class TelemetryManagerNoOp(TelemetryManagerAbstract):
def telemetry_context(self) -> Generator[None, None, None]:
"""No-op context manager that doesn't use PostHog."""
yield
+
+ @override
+ def is_portkey_logging_enabled(self, is_debug_configured: bool) -> bool:
+ return False
+
+ @override
+ def is_portkey_tracing_enabled(self) -> bool:
+ return False
+
+ @override
+ def get_otel_tracer(self) -> OTelTracer | None:
+ return None
+
+ @property
+ @override
+ def capture_content_enabled(self) -> bool:
+ return False
+
+ @property
+ @override
+ def capture_pipe_codes_enabled(self) -> bool:
+ return False
+
+ @property
+ @override
+ def capture_output_class_name_enabled(self) -> bool:
+ return False
+
+ @property
+ @override
+ def capture_content_max_length(self) -> int | None:
+ return None
+
+ @property
+ @override
+ def is_langfuse_enabled(self) -> bool:
+ return False
+
+ @property
+ @override
+ def is_pipelex_telemetry_enabled(self) -> bool:
+ return False
+
+ @override
+ def handle_trace_start(self, trace_name: str, trace_name_redacted: str, trace_id: int) -> None:
+ pass
diff --git a/pipelex/test_extras/shared_pytest_plugins.py b/pipelex/test_extras/shared_pytest_plugins.py
index 92d328ee2..f91b9c8a7 100644
--- a/pipelex/test_extras/shared_pytest_plugins.py
+++ b/pipelex/test_extras/shared_pytest_plugins.py
@@ -11,9 +11,10 @@ from pipelex.tools.misc.placeholder import make_placeholder_value, value_is_plac
# List of environment variables that may need placeholders in CI
ENV_VAR_KEYS_WHICH_MAY_NEED_PLACEHOLDERS_IN_CI = [
- "PIPELEX_API_TOKEN",
+ "PIPELEX_API_KEY",
"PIPELEX_API_BASE_URL",
"PIPELEX_INFERENCE_API_KEY",
+ "PIPELEX_GATEWAY_API_KEY",
"OPENAI_API_KEY",
"AWS_ACCESS_KEY_ID",
"AWS_SECRET_ACCESS_KEY",
@@ -29,6 +30,9 @@ ENV_VAR_KEYS_WHICH_MAY_NEED_PLACEHOLDERS_IN_CI = [
"MISTRAL_API_KEY",
"PERPLEXITY_API_KEY",
"PERPLEXITY_API_ENDPOINT",
+ "PORTKEY_API_KEY",
+ "SCALEWAY_ENDPOINT",
+ "SCALEWAY_API_KEY",
"XAI_API_KEY",
"XAI_API_ENDPOINT",
"FAL_API_KEY",
diff --git a/pipelex/tools/misc/attribute_utils.py b/pipelex/tools/misc/attribute_utils.py
index 11a64369f..868449156 100644
--- a/pipelex/tools/misc/attribute_utils.py
+++ b/pipelex/tools/misc/attribute_utils.py
@@ -1,9 +1,10 @@
-from typing import Any, ClassVar
+from typing import Any, ClassVar, cast
class AttributePolisher:
- base_64_truncate_length: ClassVar[int] = 64
- url_truncate_length: ClassVar[int] = 128
+ base_64_truncate_length: ClassVar[int] = 100
+ url_truncate_length: ClassVar[int] = 100
+ long_string_truncate_length: ClassVar[int] = 512
truncate_suffix: ClassVar[str] = "…"
@classmethod
@@ -29,6 +30,33 @@ class AttributePolisher:
name == "url" and isinstance(value, str) and value.startswith("data:image/") and len(value) > cls.url_truncate_length
)
+ @classmethod
+ def should_truncate_any_long_string(cls, value: Any) -> bool:
+ """Check if a value should be truncated based on common patterns for long strings.
+
+ This is a more aggressive truncation that catches base64-like patterns
+ regardless of field name, useful for pretty printing unknown structures.
+ """
+ if not isinstance(value, str):
+ return False
+
+ # Truncate data URLs (base64 images)
+ if value.startswith("data:"):
+ return len(value) > cls.url_truncate_length
+
+ # Truncate any very long string that looks like base64
+ # (long alphanumeric strings without spaces are likely encoded data)
+ if len(value) > cls.long_string_truncate_length:
+ # Check if it looks like base64: mostly alphanumeric, +, /, =
+ sample = value[:200]
+ base64_chars = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=")
+ non_base64_count = sum(1 for char in sample if char not in base64_chars)
+ # If less than 5% non-base64 chars, it's probably encoded data
+ if non_base64_count < len(sample) * 0.05:
+ return True
+
+ return False
+
@classmethod
def get_truncated_value(cls, name: str, value: str | bytes) -> str | bytes:
"""Get the truncated value based on the field name and value type."""
@@ -39,3 +67,50 @@ class AttributePolisher:
if name == "url" and value.startswith("data:image/"):
return cls._truncate_string(value, cls.url_truncate_length)
return value
+
+ @classmethod
+ def get_truncated_long_string(cls, value: str) -> str:
+ """Truncate a long string that was detected by should_truncate_any_long_string."""
+ if value.startswith("data:"):
+ return cls._truncate_string(value, cls.url_truncate_length)
+ return cls._truncate_string(value, cls.long_string_truncate_length)
+
+ @classmethod
+ def apply_truncation_recursive(cls, obj: Any, name: str | None = None) -> Any:
+ """Recursively apply truncation logic to a data structure.
+
+ Args:
+ obj: The object to process
+ name: The field name (for truncation logic)
+
+ Returns:
+ The processed object with truncation applied where appropriate
+
+ """
+ # First check if this specific object should be truncated by field name
+ if name and cls.should_truncate(name=name, value=obj):
+ return cls.get_truncated_value(name, obj)
+
+ # Check for long strings that look like base64 (regardless of field name)
+ if cls.should_truncate_any_long_string(obj):
+ return cls.get_truncated_long_string(obj)
+
+ # If it's a dictionary, recurse into its values
+ if isinstance(obj, dict):
+ obj_dict = cast("dict[str, Any]", obj)
+ truncated_dict: dict[str, Any] = {}
+ for key, value in obj_dict.items():
+ truncated_dict[key] = cls.apply_truncation_recursive(value, name=key)
+ return truncated_dict
+
+ # If it's a list, recurse into its items
+ if isinstance(obj, list):
+ obj_list = cast("list[Any]", obj)
+ return [cls.apply_truncation_recursive(item, name=name) for item in obj_list]
+
+ # If it's a tuple, recurse into its items and return as tuple
+ if isinstance(obj, tuple):
+ return tuple(cls.apply_truncation_recursive(item, name=name) for item in obj) # pyright: ignore[reportUnknownVariableType]
+
+ # For all other types, return as-is
+ return obj
diff --git a/pipelex/tools/misc/base_64_utils.py b/pipelex/tools/misc/base_64_utils.py
index fe7cab3ce..c6f28e38d 100644
--- a/pipelex/tools/misc/base_64_utils.py
+++ b/pipelex/tools/misc/base_64_utils.py
@@ -3,13 +3,15 @@ import base64
import aiofiles
-from pipelex.tools.misc.file_utils import save_bytes_to_binary_file
-from pipelex.tools.misc.filetype_utils import detect_file_type_from_base64
+from pipelex.tools.misc.file_fetch_utils import fetch_file_from_url_httpx_async
+from pipelex.tools.misc.file_utils import load_binary, load_binary_async, save_bytes_to_binary_file
+from pipelex.tools.misc.filetype_utils import FileType, detect_file_type_from_base64, detect_file_type_from_bytes
+from pipelex.tools.misc.path_utils import clarify_path_or_url
def load_binary_as_base64(path: str) -> bytes:
- with open(path, "rb") as fp:
- return base64.b64encode(fp.read())
+ with open(path, "rb") as file_pointer:
+ return base64.b64encode(file_pointer.read())
async def load_binary_as_base64_async(path: str) -> bytes:
@@ -18,9 +20,42 @@ async def load_binary_as_base64_async(path: str) -> bytes:
return base64.b64encode(data_bytes)
-async def load_binary_async(path: str) -> bytes:
- async with aiofiles.open(path, "rb") as fp: # pyright: ignore[reportUnknownMemberType]
- return await fp.read()
+def make_base_64_url_from_path(path: str) -> str:
+ raw_bytes = load_binary(path=path)
+ base_64 = base64.b64encode(raw_bytes)
+ file_type = detect_file_type_from_bytes(buf=raw_bytes)
+ return make_base_64_url(base_64=base_64, file_type=file_type)
+
+
+async def make_base_64_url_from_path_async(path: str) -> str:
+ raw_bytes = await load_binary_async(path=path)
+ base_64 = base64.b64encode(raw_bytes)
+ file_type = detect_file_type_from_bytes(buf=raw_bytes)
+ return make_base_64_url(base_64=base_64, file_type=file_type)
+
+
+async def make_base_64_url_from_url_async(url: str) -> str:
+ raw_bytes = await fetch_file_from_url_httpx_async(url=url)
+ base_64 = base64.b64encode(raw_bytes)
+ file_type = detect_file_type_from_bytes(buf=raw_bytes)
+ return make_base_64_url(base_64=base_64, file_type=file_type)
+
+
+async def make_base_64_url_from_location_async(location: str) -> str:
+ pdf_path, pdf_url = clarify_path_or_url(path_or_uri=location)
+ if pdf_url:
+ base_64_url = await make_base_64_url_from_url_async(url=pdf_url)
+ else: # pdf_path must be provided based on validation
+ assert pdf_path is not None
+ base_64_url = await make_base_64_url_from_path_async(path=pdf_path)
+ return base_64_url
+
+
+def make_base_64_url(
+ base_64: bytes,
+ file_type: FileType,
+) -> str:
+ return f"data:{file_type.mime};base64,{base_64.decode('utf-8')}"
def encode_to_base64(data_bytes: bytes) -> bytes:
diff --git a/pipelex/tools/misc/diff.py b/pipelex/tools/misc/diff.py
index e7e8ef6cf..d68caa2f9 100644
--- a/pipelex/tools/misc/diff.py
+++ b/pipelex/tools/misc/diff.py
@@ -16,30 +16,44 @@ if TYPE_CHECKING:
from pipelex.tools.misc.pretty import PrettyPrintable
-def has_diff_dirs(dir1: str | Path, dir2: str | Path) -> bool:
+def has_diff_dirs(dir1: str | Path, dir2: str | Path, exclude_files: set[str] | None = None) -> bool:
"""Check if there are any differences between two directories.
- Returns True if there are any files only in left, only in right, or different files.
+ Args:
+ dir1: First directory path.
+ dir2: Second directory path.
+ exclude_files: Set of file names to exclude from comparison (e.g., {"pipelex_service.toml"}).
+
+ Returns:
+ True if there are any files only in left, only in right, or different files.
"""
dir1 = Path(dir1)
dir2 = Path(dir2)
+ exclude_files = exclude_files or set()
+
+ def _filter_excluded(file_list: list[str]) -> list[str]:
+ return [file for file in file_list if file not in exclude_files]
def _has_diff(dir_comparison: filecmp.dircmp[str]) -> bool:
- # Check for files only in left or right
- if dir_comparison.left_only or dir_comparison.right_only:
+ # Check for files only in left or right (excluding excluded files)
+ left_only_filtered = _filter_excluded(dir_comparison.left_only)
+ right_only_filtered = _filter_excluded(dir_comparison.right_only)
+ if left_only_filtered or right_only_filtered:
return True
- # Check for different files using shallow comparison
- if dir_comparison.diff_files:
+ # Check for different files using shallow comparison (excluding excluded files)
+ diff_files_filtered = _filter_excluded(dir_comparison.diff_files)
+ if diff_files_filtered:
return True
# Force deep comparison for common files that passed shallow comparison
# This is needed because shallow comparison only checks metadata (size, mtime)
- if dir_comparison.common_files:
+ common_files_filtered = _filter_excluded(dir_comparison.common_files)
+ if common_files_filtered:
_, mismatch, errors = filecmp.cmpfiles(
dir_comparison.left,
dir_comparison.right,
- dir_comparison.common_files,
+ common_files_filtered,
shallow=False, # Force byte-by-byte comparison
)
if mismatch or errors:
@@ -183,21 +197,32 @@ def _generate_diff_summary(diff_content: str, left_is_newer: bool) -> str | None
return f" Sync would {' and '.join(summary_parts)} in {obsolete_location}"
-def make_diff_dirs_pretty(dir1: str | Path, dir2: str | Path) -> PrettyPrintable:
+def make_diff_dirs_pretty(dir1: str | Path, dir2: str | Path, exclude_files: set[str] | None = None) -> PrettyPrintable:
"""Generate a PrettyPrintable representation of directory differences.
- Returns a Rich renderable showing files only in left, only in right,
- and different files with full diff content. For different files, indicates
- which version is newer based on modification time.
+ Args:
+ dir1: First directory path.
+ dir2: Second directory path.
+ exclude_files: Set of file names to exclude from comparison (e.g., {"pipelex_service.toml"}).
+
+ Returns:
+ A Rich renderable showing files only in left, only in right,
+ and different files with full diff content. For different files, indicates
+ which version is newer based on modification time.
"""
dir1 = Path(dir1)
dir2 = Path(dir2)
+ exclude_files = exclude_files or set()
sections: list[PrettyPrintable] = []
+ def _filter_excluded(file_list: list[str]) -> list[str]:
+ return [file for file in file_list if file not in exclude_files]
+
def _collect_diffs(dir_comparison: filecmp.dircmp[str], relative_path: str = "") -> None:
- # Files only in left directory
- if dir_comparison.left_only:
+ # Files only in left directory (excluding excluded files)
+ left_only_filtered = _filter_excluded(dir_comparison.left_only)
+ if left_only_filtered:
table = Table(
title=f"[yellow]Only in {dir_comparison.left}[/yellow]",
show_header=False,
@@ -206,13 +231,14 @@ def make_diff_dirs_pretty(dir1: str | Path, dir2: str | Path) -> PrettyPrintable
padding=(0, 1),
)
table.add_column("File", style="yellow")
- for name in sorted(dir_comparison.left_only):
+ for name in sorted(left_only_filtered):
full_path = Path(relative_path, name) if relative_path else Path(name)
table.add_row(str(full_path))
sections.append(table)
- # Files only in right directory
- if dir_comparison.right_only:
+ # Files only in right directory (excluding excluded files)
+ right_only_filtered = _filter_excluded(dir_comparison.right_only)
+ if right_only_filtered:
table = Table(
title=f"[cyan]Only in {dir_comparison.right}[/cyan]",
show_header=False,
@@ -221,21 +247,23 @@ def make_diff_dirs_pretty(dir1: str | Path, dir2: str | Path) -> PrettyPrintable
padding=(0, 1),
)
table.add_column("File", style="cyan")
- for name in sorted(dir_comparison.right_only):
+ for name in sorted(right_only_filtered):
full_path = Path(relative_path, name) if relative_path else Path(name)
table.add_row(str(full_path))
sections.append(table)
# Different files - combine shallow diff_files with deep comparison of common_files
# This is needed because diff_files only contains files that failed shallow comparison
- different_files = set(dir_comparison.diff_files)
+ # Apply exclusion filter to diff_files
+ different_files = set(_filter_excluded(dir_comparison.diff_files))
- # Force deep comparison for common files
- if dir_comparison.common_files:
+ # Force deep comparison for common files (excluding excluded files)
+ common_files_filtered = _filter_excluded(dir_comparison.common_files)
+ if common_files_filtered:
_, mismatch, errors = filecmp.cmpfiles(
dir_comparison.left,
dir_comparison.right,
- dir_comparison.common_files,
+ common_files_filtered,
shallow=False, # Force byte-by-byte comparison
)
different_files.update(mismatch)
diff --git a/pipelex/tools/misc/file_utils.py b/pipelex/tools/misc/file_utils.py
index 0301d74ef..3345629f1 100644
--- a/pipelex/tools/misc/file_utils.py
+++ b/pipelex/tools/misc/file_utils.py
@@ -3,6 +3,8 @@ import os
import shutil
from pathlib import Path
+import aiofiles
+
########################################################
# Save & Load
########################################################
@@ -91,6 +93,16 @@ def failable_load_text_from_path(path: str) -> str | None:
return load_text_from_path(path)
+def load_binary(path: str) -> bytes:
+ with open(path, "rb") as file_pointer:
+ return file_pointer.read()
+
+
+async def load_binary_async(path: str) -> bytes:
+ async with aiofiles.open(path, "rb") as fp: # pyright: ignore[reportUnknownMemberType]
+ return await fp.read()
+
+
########################################################
# Copy & Remove
########################################################
diff --git a/pipelex/tools/misc/pretty.py b/pipelex/tools/misc/pretty.py
index 33dfd279e..7112e1401 100644
--- a/pipelex/tools/misc/pretty.py
+++ b/pipelex/tools/misc/pretty.py
@@ -4,6 +4,7 @@ from io import StringIO
from typing import Any, ClassVar
from kajson import kajson
+from pydantic import BaseModel
from rich.console import Console, Group
from rich.json import JSON
from rich.markdown import Markdown
@@ -16,7 +17,9 @@ from rich.table import Table
from rich.terminal_theme import TerminalTheme
from rich.text import Text, TextType
+from pipelex.tools.misc.attribute_utils import AttributePolisher
from pipelex.tools.misc.terminal_utils import BOLD_FONT, RESET_FONT, TerminalColor, print_to_stderr
+from pipelex.tools.typing.pydantic_utils import CustomBaseModel, make_truncated_wrapper
from pipelex.types import StrEnum
TEXT_COLOR = TerminalColor.WHITE
@@ -241,12 +244,16 @@ class PrettyPrinter:
# Format the value
if isinstance(value, PrettyPrintable):
pretty = value
+ elif isinstance(value, BaseModel) and not isinstance(value, CustomBaseModel):
+ # Wrap regular BaseModel to get truncated __rich_repr__ with proper class name
+ pretty = Pretty(make_truncated_wrapper(value))
elif isinstance(value, dict):
- # For dicts, use JSON rendering
+ # For dicts, apply truncation and use JSON rendering
+ truncated_data = AttributePolisher.apply_truncation_recursive(value)
try:
- pretty = JSON.from_data(value, indent=4)
+ pretty = JSON.from_data(truncated_data, indent=4)
except TypeError:
- json_string = kajson.dumps(value, indent=4)
+ json_string = kajson.dumps(truncated_data, indent=4)
pretty = Syntax(json_string, "json", theme="monokai")
elif isinstance(value, list):
# For lists, build a table without headers
@@ -269,6 +276,9 @@ class PrettyPrinter:
# Handle URLs specially, otherwise use Text for simple strings
if value.startswith(("http://", "https://")):
pretty = Text(value, style="link " + value, no_wrap=True)
+ elif AttributePolisher.should_truncate_any_long_string(value):
+ # Truncate long base64-like strings
+ pretty = Text(AttributePolisher.get_truncated_long_string(value))
else:
# Use Text instead of Markdown to allow proper auto-sizing
pretty = Text(value)
diff --git a/pipelex/tools/secrets/secrets_utils.py b/pipelex/tools/secrets/secrets_utils.py
index 0a6d3acd0..f3b82303e 100644
--- a/pipelex/tools/secrets/secrets_utils.py
+++ b/pipelex/tools/secrets/secrets_utils.py
@@ -32,7 +32,11 @@ class VarPrefix(StrEnum):
SECRET = "secret"
-def substitute_vars(content: str, secrets_provider: SecretsProviderAbstract) -> str:
+def substitute_vars(
+ content: str,
+ secrets_provider: SecretsProviderAbstract,
+ raise_on_missing_var: bool = True,
+) -> str:
"""Substitute variable placeholders with values from environment variables or secrets.
Supports the following placeholder formats:
@@ -44,44 +48,52 @@ def substitute_vars(content: str, secrets_provider: SecretsProviderAbstract) ->
Args:
content: Text content with variable placeholders
secrets_provider: The secrets provider to use for secret lookups
+ raise_on_missing_var: If True (default), raise VarNotFoundError when a variable
+ is not found. If False, keep the original placeholder in the output.
Returns:
Content with variables substituted
Raises:
VarNotFoundError: If required variable is missing from all specified sources
+ and raise_on_missing_var is True
"""
def replace_var(match: re.Match[str]) -> str:
var_spec = match.group(1)
- # Check if it's a fallback pattern (contains |)
- if "|" in var_spec:
- return _handle_fallback_pattern(var_spec, secrets_provider)
-
- # Check if it has a prefix (env: or secret:)
- if ":" in var_spec:
- prefix_str, var_name = var_spec.split(":", 1)
- prefix_str = prefix_str.strip()
-
- try:
- prefix = VarPrefix(prefix_str)
- except ValueError as exc:
- msg = f"Unknown variable prefix: '{prefix_str}'"
- raise UnknownVarPrefixError(
- var_name=var_name,
- message=msg,
- ) from exc
-
- match prefix:
- case VarPrefix.ENV:
- return _get_env_var(var_name)
- case VarPrefix.SECRET:
- return _get_secret(var_name, secrets_provider)
- else:
- # Default behavior: use secrets provider
- return _get_secret(var_spec, secrets_provider)
+ try:
+ # Check if it's a fallback pattern (contains |)
+ if "|" in var_spec:
+ return _handle_fallback_pattern(var_spec, secrets_provider)
+
+ # Check if it has a prefix (env: or secret:)
+ if ":" in var_spec:
+ prefix_str, var_name = var_spec.split(":", 1)
+ prefix_str = prefix_str.strip()
+
+ try:
+ prefix = VarPrefix(prefix_str)
+ except ValueError as exc:
+ msg = f"Unknown variable prefix: '{prefix_str}'"
+ raise UnknownVarPrefixError(
+ var_name=var_name,
+ message=msg,
+ ) from exc
+
+ match prefix:
+ case VarPrefix.ENV:
+ return _get_env_var(var_name)
+ case VarPrefix.SECRET:
+ return _get_secret(var_name, secrets_provider)
+ else:
+ # Default behavior: use secrets provider
+ return _get_secret(var_spec, secrets_provider)
+ except (VarNotFoundError, VarFallbackPatternError):
+ if raise_on_missing_var:
+ raise
+ return match.group(0) # Keep original placeholder
# Pattern matches ${VAR_NAME} or ${prefix:VAR_NAME} or ${env:VAR|secret:VAR}
# Restrict to not match across newlines, quotes, or nested braces
diff --git a/pipelex/tools/typing/pydantic_utils.py b/pipelex/tools/typing/pydantic_utils.py
index a7688dd22..5d2efacb7 100644
--- a/pipelex/tools/typing/pydantic_utils.py
+++ b/pipelex/tools/typing/pydantic_utils.py
@@ -11,6 +11,8 @@ from pipelex.types import StrEnum
BaseModelTypeVar = TypeVar("BaseModelTypeVar", bound=BaseModel)
T = TypeVar("T")
+K = TypeVar("K")
+V = TypeVar("V")
def empty_list_factory_of(_: type[T]) -> Callable[[], list[T]]:
@@ -20,6 +22,24 @@ def empty_list_factory_of(_: type[T]) -> Callable[[], list[T]]:
return _factory
+def empty_dict_factory_of(_key: type[K], _val: type[V] | None = None) -> Callable[[], dict[K, Any]]:
+ """Create a typed empty dict factory.
+
+ Args:
+ _key: The key type (used for type inference)
+ _val: The value type (optional, used for type inference)
+
+ Returns:
+ A callable that returns an empty dict
+
+ """
+
+ def _factory() -> dict[K, Any]:
+ return {}
+
+ return _factory
+
+
class PydanticValidationErrorAnalysis(BaseModel):
error_msg: str
@@ -248,25 +268,59 @@ def serialize_model(
return data
+def _truncated_rich_repr_from_items(rich_repr_items: RichReprResult) -> RichReprResult:
+ """Apply truncation to rich repr items.
+
+ This applies AttributePolisher truncation to field values recursively,
+ handling nested dicts, lists, and BaseModel objects.
+ """
+ for item in rich_repr_items:
+ if isinstance(item, tuple):
+ tuple_item = cast("tuple[Any, ...]", item)
+ if len(tuple_item) >= 2:
+ name = tuple_item[0]
+ value = tuple_item[1]
+ # Apply recursive truncation to handle nested structures
+ truncated_value = AttributePolisher.apply_truncation_recursive(value, name=name)
+ if len(tuple_item) == 3:
+ yield name, truncated_value, tuple_item[2]
+ else:
+ yield name, truncated_value
+ else:
+ yield item
+
+
+def make_truncated_wrapper(model: BaseModel) -> Any:
+ """Create a wrapper that provides truncated __rich_repr__ for a BaseModel.
+
+ This dynamically creates a class with the same name as the model's class,
+ so Rich's Pretty displays the correct type name while applying
+ AttributePolisher truncation to long string values.
+ """
+ model_class_name = model.__class__.__name__
+
+ def rich_repr_method(_self: Any) -> RichReprResult:
+ # Call BaseModel's __rich_repr__ directly to avoid recursion if model is a CustomBaseModel
+ base_repr = BaseModel.__rich_repr__(model) # type: ignore[misc, arg-type]
+ return _truncated_rich_repr_from_items(base_repr)
+
+ # Create a dynamic class with the correct name
+ wrapper_class = type(
+ model_class_name,
+ (),
+ {
+ "__rich_repr__": rich_repr_method,
+ },
+ )
+
+ return wrapper_class()
+
+
class CustomBaseModel(BaseModel):
@override
def __rich_repr__(self) -> RichReprResult:
- for item in super().__rich_repr__(): # type: ignore[misc]
- if isinstance(item, tuple):
- tuple_item = cast("tuple[Any, ...]", item)
- if len(tuple_item) >= 2:
- name = tuple_item[0]
- value = tuple_item[1]
- if AttributePolisher.should_truncate(name=name, value=value):
- truncated_value = AttributePolisher.get_truncated_value(name, value)
- if len(tuple_item) == 3:
- yield name, truncated_value, tuple_item[2]
- else:
- yield name, truncated_value
- else:
- yield item
- else:
- yield item
+ # Use super().__rich_repr__() to get base items, avoiding recursion
+ yield from _truncated_rich_repr_from_items(super().__rich_repr__()) # type: ignore[misc]
@override
def __repr_args__(self) -> Sequence[tuple[str | None, Any]]:
@@ -295,40 +349,5 @@ class CustomBaseModel(BaseModel):
# Get the model dump with serialize_as_any=True
dumped_data = self.model_dump(**kwargs)
- # Apply truncation logic recursively
- return self._apply_truncation_recursive(dumped_data)
-
- def _apply_truncation_recursive(self, obj: Any, name: str | None = None) -> Any:
- """Recursively apply AttributePolisher truncation logic to a data structure.
-
- Args:
- obj: The object to process
- name: The field name (for truncation logic)
-
- Returns:
- The processed object with truncation applied where appropriate
-
- """
- # First check if this specific object should be truncated
- if name and AttributePolisher.should_truncate(name=name, value=obj):
- return AttributePolisher.get_truncated_value(name, obj)
-
- # If it's a dictionary, recurse into its values
- if isinstance(obj, dict):
- obj_dict = cast("dict[str, Any]", obj)
- truncated_dict: dict[str, Any] = {}
- for key, value in obj_dict.items():
- truncated_dict[key] = self._apply_truncation_recursive(value, name=key)
- return truncated_dict
-
- # If it's a list, recurse into its items
- if isinstance(obj, list):
- obj_list = cast("list[Any]", obj)
- return [self._apply_truncation_recursive(item, name=name) for item in obj_list]
-
- # If it's a tuple, recurse into its items and return as tuple
- if isinstance(obj, tuple):
- return tuple(self._apply_truncation_recursive(item, name=name) for item in obj) # pyright: ignore[reportUnknownVariableType]
-
- # For all other types, return as-is
- return obj
+ # Apply truncation logic recursively using the shared utility
+ return AttributePolisher.apply_truncation_recursive(dumped_data)
diff --git a/pipelex/urls.py b/pipelex/urls.py
index b917cddcb..4ea74ee11 100644
--- a/pipelex/urls.py
+++ b/pipelex/urls.py
@@ -1,9 +1,13 @@
class URLs:
homepage = "https://pipelex.com"
+ app = "https://app.pipelex.com/"
repository = "https://github.com/Pipelex/pipelex"
documentation = "https://docs.pipelex.com/"
changelog = "https://docs.pipelex.com/changelog/"
discord = "https://go.pipelex.com/discord"
+ privacy_policy = "https://go.pipelex.com/privacy-policy"
+ telemetry_docs = "https://docs.pipelex.com/home/5-setup/telemetry/"
+ gateway_docs = "https://docs.pipelex.com/home/5-setup/configure-ai-providers/#option-1-pipelex-gateway-easiest-for-getting-started"
pipe_func_docs = "https://docs.pipelex.com/home/6-build-reliable-ai-workflows/pipes/pipe-operators/PipeFunc/"
backend_provider_docs = "https://docs.pipelex.com/home/5-setup/configure-ai-providers/"
native_concepts_docs = "https://docs.pipelex.com/home/6-build-reliable-ai-workflows/concepts/native-concepts/"
diff --git a/pyproject.toml b/pyproject.toml
index b34a5e0e5..883d5cdfb 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -29,8 +29,13 @@ dependencies = [
"markdown>=3.6",
"networkx>=3.4.2",
"openai>=1.108.1",
+ "opentelemetry-api",
+ "opentelemetry-exporter-otlp-proto-http",
+ "opentelemetry-semantic-conventions",
+ "opentelemetry-sdk",
"pillow>=11.2.1",
"polyfactory>=2.21.0",
+ "portkey-ai>=2.1.0",
"posthog>=6.7.0",
"pypdfium2>=4.30.0,!=4.30.1",
"pydantic>=2.10.6,<3.0.0",
diff --git a/tests/acceptance/init_command.md b/tests/acceptance/init_command.md
index ecc7d113c..e3d7c9e5d 100644
--- a/tests/acceptance/init_command.md
+++ b/tests/acceptance/init_command.md
@@ -21,15 +21,15 @@ Before each test scenario, ensure:
- [ ] Press Enter to confirm initialization
- [ ] Verify config files are copied successfully
- [ ] Verify backend selection panel is displayed with numbered options
-- [ ] Select option `1` (pipelex_inference) and press Enter
+- [ ] Select option `1` (pipelex_gateway) and press Enter
- [ ] Verify confirmation message shows 1 backend configured
-- [ ] Verify routing profile is set to "pipelex_first"
+- [ ] Verify routing profile is set to "pipelex_gateway_first"
- [ ] Verify telemetry selection panel is displayed
- [ ] Select option `1` (OFF) and press Enter
- [ ] Verify telemetry mode is set successfully
- [ ] Verify `.pipelex/` directory exists with all config files
-- [ ] Verify `.pipelex/inference/backends.toml` has pipelex_inference enabled
-- [ ] Verify `.pipelex/inference/routing_profiles.toml` has active = "pipelex_first"
+- [ ] Verify `.pipelex/inference/backends.toml` has pipelex_gateway enabled
+- [ ] Verify `.pipelex/inference/routing_profiles.toml` has active = "pipelex_gateway_first"
- [ ] Verify `.pipelex/telemetry.toml` has telemetry_mode = "off"
**Test Case 1.2: Initialization with multiple backends**
@@ -323,11 +323,11 @@ Before each test scenario, ensure:
### 9. Edge Cases
-**Test Case 9.1: pipelex_inference always sets pipelex_first**
+**Test Case 9.1: pipelex_gateway always sets pipelex_gateway_first**
- [ ] Run: `pipelex init`
-- [ ] Select pipelex_inference as one of multiple backends
-- [ ] Verify routing is set to "pipelex_first" automatically
+- [ ] Select pipelex_gateway as one of multiple backends
+- [ ] Verify routing is set to "pipelex_gateway_first" automatically
- [ ] Verify NO primary/fallback prompts
**Test Case 9.2: Single non-pipelex backend**
diff --git a/tests/cases/documents.py b/tests/cases/documents.py
index 27a18dcb9..7965ee3e9 100644
--- a/tests/cases/documents.py
+++ b/tests/cases/documents.py
@@ -10,12 +10,19 @@ class PDFTestCases:
TEST_DOCUMENT_DIRECTORY = "tests/data/documents"
# Local file paths
- PDF_FILE_PATH_1 = f"{TEST_DOCUMENT_DIRECTORY}/solar_system.pdf"
- PDF_FILE_PATH_2 = f"{TEST_DOCUMENT_DIRECTORY}/illustrated_train_article.pdf"
+ PDF_FILE_PATH_1 = f"{TEST_DOCUMENT_DIRECTORY}/Job-Offer.pdf"
+ PDF_FILE_PATH_2 = f"{TEST_DOCUMENT_DIRECTORY}/solar_system.pdf"
+ PDF_FILE_PATH_3 = f"{TEST_DOCUMENT_DIRECTORY}/illustrated_train_article.pdf"
DOCUMENT_FILE_PATHS: ClassVar[list[str]] = [
PDF_FILE_PATH_1,
PDF_FILE_PATH_2,
+ PDF_FILE_PATH_3,
]
# Remote URLs
- DOCUMENT_URLS: ClassVar[list[str]] = ["https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"]
+ PDF_FILE_URL_1 = "https://pipelex-web.s3.amazonaws.com/demo/Job-Offer.pdf"
+ PDF_FILE_URL_2 = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
+ DOCUMENT_URLS: ClassVar[list[str]] = [
+ PDF_FILE_URL_1,
+ PDF_FILE_URL_2,
+ ]
diff --git a/tests/cases/images.py b/tests/cases/images.py
index 8bb42a77c..f015728a5 100644
--- a/tests/cases/images.py
+++ b/tests/cases/images.py
@@ -10,7 +10,9 @@ class ImageTestCases:
TEST_IMAGE_DIRECTORY = "tests/data/images"
# Individual file paths
- IMAGE_FILE_PATH_PNG = f"{TEST_IMAGE_DIRECTORY}/ai_lympics.png"
+ IMAGE_FILE_PATH_PNG_1 = f"{TEST_IMAGE_DIRECTORY}/ai_lympics.png"
+ IMAGE_FILE_PATH_JPG_1 = f"{TEST_IMAGE_DIRECTORY}/solar_system.jpg"
+ IMAGE_FILE_PATH_PNG_2 = f"{TEST_IMAGE_DIRECTORY}/solar_system.png"
# Remote URLs
IMAGE_URL_PNG = "https://www.python.org/static/community_logos/python-logo-master-v3-TM.png"
@@ -20,6 +22,10 @@ class ImageTestCases:
f"{TEST_IMAGE_DIRECTORY}/ai_lympics.png",
f"{TEST_IMAGE_DIRECTORY}/animal_lympics.jpg",
]
+ IMAGE_TEXT_FILE_PATHS: ClassVar[list[str]] = [
+ IMAGE_FILE_PATH_JPG_1,
+ IMAGE_FILE_PATH_PNG_2,
+ ]
# URL collections
IMAGE_URLS: ClassVar[list[str]] = [
diff --git a/tests/conftest.py b/tests/conftest.py
index 24578696f..8796d8d69 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -6,7 +6,7 @@ import pytest
from pipelex import log
from pipelex.hub import get_library_manager, set_current_library
from pipelex.pipelex import Pipelex
-from pipelex.system.runtime import IntegrationMode
+from pipelex.system.runtime import IntegrationMode, runtime_manager
pytest_plugins = [
"pipelex.test_extras.shared_pytest_plugins",
@@ -15,6 +15,18 @@ pytest_plugins = [
TEST_OUTPUTS_DIR = "temp/test_outputs"
+def _get_test_integration_mode() -> IntegrationMode:
+ """Return the appropriate integration mode for tests.
+
+ Uses CI mode in CI environments (no terms acceptance required),
+ PYTEST mode for local development (terms acceptance required).
+ """
+ if runtime_manager.is_ci_testing:
+ return IntegrationMode.CI
+ else:
+ return IntegrationMode.PYTEST
+
+
@pytest.fixture(scope="module")
def routing_profile_setup(request: pytest.FixtureRequest): # noqa: ARG001 # pyright: ignore[reportUnusedFunction]
"""Hook for downstream conftest to inject routing profile setup before Pipelex init.
@@ -27,9 +39,9 @@ def routing_profile_setup(request: pytest.FixtureRequest): # noqa: ARG001 # py
@pytest.fixture(scope="module", autouse=True)
def reset_pipelex_config_fixture(routing_profile_setup: str | None): # noqa: ARG001
- pipelex_instance = Pipelex.make(integration_mode=IntegrationMode.PYTEST)
+ Pipelex.make(integration_mode=_get_test_integration_mode())
yield
- pipelex_instance.teardown()
+ Pipelex.teardown_if_needed()
@pytest.fixture(scope="class")
diff --git a/tests/data/documents/Job-Offer.pdf b/tests/data/documents/Job-Offer.pdf
new file mode 100644
index 000000000..061d7131e
Binary files /dev/null and b/tests/data/documents/Job-Offer.pdf differ
diff --git a/tests/data/images/ai_lympics.png b/tests/data/images/ai_lympics.png
index c01ae2093..c64a50659 100644
Binary files a/tests/data/images/ai_lympics.png and b/tests/data/images/ai_lympics.png differ
diff --git a/tests/data/images/animal_lympics.png b/tests/data/images/animal_lympics.png
index 4d264fd27..b77141cb3 100644
Binary files a/tests/data/images/animal_lympics.png and b/tests/data/images/animal_lympics.png differ
diff --git a/tests/data/images/diagram.png b/tests/data/images/diagram.png
index c105d922d..360ce0d72 100644
Binary files a/tests/data/images/diagram.png and b/tests/data/images/diagram.png differ
diff --git a/tests/data/images/eiffel_tower.png b/tests/data/images/eiffel_tower.png
index e7a455b29..7432e13f8 100644
Binary files a/tests/data/images/eiffel_tower.png and b/tests/data/images/eiffel_tower.png differ
diff --git a/tests/data/documents/solar_system.jpg b/tests/data/images/solar_system.jpg
similarity index 100%
rename from tests/data/documents/solar_system.jpg
rename to tests/data/images/solar_system.jpg
diff --git a/tests/data/documents/solar_system.png b/tests/data/images/solar_system.png
similarity index 100%
rename from tests/data/documents/solar_system.png
rename to tests/data/images/solar_system.png
diff --git a/tests/e2e/pipelex/cli/test_init_cmd_edge_cases.py b/tests/e2e/pipelex/cli/test_init_cmd_edge_cases.py
index 2cefa1f4b..0fe7b20b2 100644
--- a/tests/e2e/pipelex/cli/test_init_cmd_edge_cases.py
+++ b/tests/e2e/pipelex/cli/test_init_cmd_edge_cases.py
@@ -8,35 +8,37 @@ if TYPE_CHECKING:
from pipelex.cli.commands.init.command import init_cmd
from pipelex.cli.commands.init.ui.types import InitFocus
+from pipelex.cogt.model_backends.backend import PipelexBackend
+from pipelex.cogt.model_routing.routing_profile import PipelexRoutingProfile
from pipelex.kit.paths import get_kit_configs_dir
from pipelex.tools.misc.toml_utils import load_toml_with_tomlkit, save_toml_to_path
from tests.helpers.init_cmd_helpers import MockedInitEnvironment, get_backend_indices_helper
class TestEdgeCases:
- def test_pipelex_inference_sets_pipelex_first(self, tmp_path: Path, mocker: MockerFixture) -> None:
- """Test Case 9.1: pipelex_inference always sets pipelex_first."""
+ def test_pipelex_gateway_sets_pipelex_gateway_first(self, tmp_path: Path, mocker: MockerFixture) -> None:
+ """Test Case 9.1: pipelex_gateway always sets pipelex_gateway_first."""
# Setup environment
env = MockedInitEnvironment(tmp_path, mocker)
env.setup_empty_dir()
- # Get indices for pipelex_inference and openai
+ # Get indices for pipelex_gateway and openai
kit_backends = Path(str(get_kit_configs_dir())) / "inference" / "backends.toml"
- indices = get_backend_indices_helper(str(kit_backends), ["pipelex_inference", "openai"])
+ indices = get_backend_indices_helper(str(kit_backends), [PipelexBackend.GATEWAY, "openai"])
indices_str = ",".join(str(i) for i in indices)
# User inputs - no primary/fallback prompts expected
env.add_confirm_input(True) # Confirm initialization
- env.add_prompt_input(indices_str) # Select pipelex_inference and openai
- env.add_prompt_input("1") # Telemetry
+ env.add_confirm_input(True) # Accept gateway terms of service
+ env.add_prompt_input(indices_str) # Select pipelex_gateway and openai
env.setup_mocks()
# Execute
init_cmd(focus=InitFocus.ALL, reset=False)
- # Verify pipelex_first is set automatically
- env.verify_routing("pipelex_first")
+ # Verify pipelex_gateway_first is set automatically
+ env.verify_routing(PipelexRoutingProfile.PIPELEX_GATEWAY_FIRST)
def test_single_non_pipelex_backend(self, tmp_path: Path, mocker: MockerFixture) -> None:
"""Test Case 9.2: Single non-pipelex backend."""
@@ -52,7 +54,6 @@ class TestEdgeCases:
env.add_confirm_input(True) # Confirm initialization
env.add_prompt_input(str(indices[0])) # Select only openai
env.add_confirm_input(True) # Confirm creating profile if needed
- env.add_prompt_input("1") # Telemetry
env.setup_mocks()
@@ -77,7 +78,6 @@ class TestEdgeCases:
env.add_confirm_input(True) # Confirm initialization
env.add_prompt_input(indices_str) # Select anthropic, openai
env.add_prompt_input("1") # Primary backend: anthropic (first in selection)
- env.add_prompt_input("1") # Telemetry
env.setup_mocks()
@@ -96,12 +96,12 @@ class TestEdgeCases:
# Set initial state
backends_path = env.inference_dir / "backends.toml"
toml_doc = load_toml_with_tomlkit(str(backends_path))
- toml_doc["pipelex_inference"]["enabled"] = True # type: ignore[index]
+ toml_doc[PipelexBackend.GATEWAY]["enabled"] = True # type: ignore[index]
save_toml_to_path(toml_doc, str(backends_path))
telemetry_path = env.pipelex_dir / "telemetry.toml"
toml_doc_tel = load_toml_with_tomlkit(str(telemetry_path))
- toml_doc_tel["telemetry_mode"] = "identified"
+ toml_doc_tel["posthog"]["mode"] = "identified" # type: ignore[index]
save_toml_to_path(toml_doc_tel, str(telemetry_path))
# Get index for anthropic
@@ -112,7 +112,6 @@ class TestEdgeCases:
env.add_confirm_input(True) # Confirm reset
env.add_prompt_input(str(indices[0])) # Select anthropic
env.add_confirm_input(True) # Confirm creating profile if needed
- env.add_prompt_input("1") # Telemetry: OFF
env.setup_mocks()
@@ -138,7 +137,6 @@ class TestEdgeCases:
env.add_confirm_input(True) # Confirm initialization
env.add_prompt_input(indices_str) # Select openai, mistral
env.add_prompt_input("1") # Primary backend
- env.add_prompt_input("1") # Telemetry
env.setup_mocks()
@@ -153,7 +151,7 @@ class TestEdgeCases:
assert toml_doc["mistral"]["enabled"] is True # type: ignore[index]
# Non-selected backends should be disabled
- assert toml_doc["pipelex_inference"]["enabled"] is False # type: ignore[index]
+ assert toml_doc[PipelexBackend.GATEWAY]["enabled"] is False # type: ignore[index]
assert toml_doc["anthropic"]["enabled"] is False # type: ignore[index]
# Internal backend should be enabled
diff --git a/tests/e2e/pipelex/cli/test_init_cmd_first_time.py b/tests/e2e/pipelex/cli/test_init_cmd_first_time.py
index d92589109..9026a2460 100644
--- a/tests/e2e/pipelex/cli/test_init_cmd_first_time.py
+++ b/tests/e2e/pipelex/cli/test_init_cmd_first_time.py
@@ -11,6 +11,8 @@ if TYPE_CHECKING:
from pipelex.cli.commands.init.command import init_cmd
from pipelex.cli.commands.init.ui.types import InitFocus
+from pipelex.cogt.model_backends.backend import PipelexBackend
+from pipelex.cogt.model_routing.routing_profile import PipelexRoutingProfile
from pipelex.kit.paths import get_kit_configs_dir
from pipelex.tools.misc.toml_utils import load_toml_with_tomlkit
from tests.helpers.init_cmd_helpers import MockedInitEnvironment, get_backend_indices_helper
@@ -23,10 +25,10 @@ class TestFirstTimeInitialization:
env = MockedInitEnvironment(tmp_path, mocker)
env.setup_empty_dir()
- # User inputs: confirm, default backend (1), telemetry OFF (1)
- env.add_confirm_input(True)
- env.add_prompt_input("1") # Default: pipelex_inference
- env.add_prompt_input("1") # Telemetry: OFF
+ # User inputs: confirm init, default backend (1), accept gateway terms
+ env.add_confirm_input(True) # Confirm initialization
+ env.add_confirm_input(True) # Accept gateway terms of service
+ env.add_prompt_input("1") # Default: pipelex_gateway
env.setup_mocks()
@@ -38,8 +40,8 @@ class TestFirstTimeInitialization:
env.verify_file_exists("inference/backends.toml")
env.verify_file_exists("inference/routing_profiles.toml")
env.verify_file_exists("telemetry.toml")
- env.verify_backends_enabled(["pipelex_inference"])
- env.verify_routing("pipelex_first")
+ env.verify_backends_enabled([PipelexBackend.GATEWAY])
+ env.verify_routing(PipelexRoutingProfile.PIPELEX_GATEWAY_FIRST)
env.verify_telemetry("off")
def test_init_with_multiple_backends_and_routing(self, tmp_path: Path, mocker: MockerFixture) -> None:
@@ -58,7 +60,6 @@ class TestFirstTimeInitialization:
env.add_prompt_input(indices_str) # Select 3 backends
env.add_prompt_input("1") # Primary: first one (anthropic)
env.add_prompt_input("2,1") # Custom fallback order (mistral, anthropic)
- env.add_prompt_input("2") # Telemetry: ANONYMOUS
env.setup_mocks()
@@ -71,8 +72,8 @@ class TestFirstTimeInitialization:
# Verify custom routing
env.verify_routing("custom_routing", expected_default="anthropic")
- # Verify telemetry
- env.verify_telemetry("anonymous")
+ # Verify telemetry (default mode from template)
+ env.verify_telemetry("off")
def test_init_with_all_backends(self, tmp_path: Path, mocker: MockerFixture) -> None:
"""Test Case 1.3: Initialization with all backends."""
@@ -82,8 +83,8 @@ class TestFirstTimeInitialization:
# User inputs
env.add_confirm_input(True) # Confirm initialization
+ env.add_confirm_input(True) # Accept gateway terms of service (since all includes gateway)
env.add_prompt_input("all") # Select all backends
- env.add_prompt_input("1") # Telemetry: OFF
env.setup_mocks()
@@ -96,8 +97,8 @@ class TestFirstTimeInitialization:
if backend_key != "internal":
assert toml_doc[backend_key]["enabled"] is True # type: ignore[index]
- # Verify routing (pipelex_first since pipelex_inference is included)
- env.verify_routing("pipelex_first")
+ # Verify routing (pipelex_gateway_first since pipelex_gateway is included)
+ env.verify_routing(PipelexRoutingProfile.PIPELEX_GATEWAY_FIRST)
def test_cancel_at_backend_selection(self, tmp_path: Path, mocker: MockerFixture) -> None:
"""Test Case 1.4: Cancel at backend selection."""
@@ -121,9 +122,9 @@ class TestFirstTimeInitialization:
# Verify config files were created but backends remain in template state
env.verify_file_exists("inference/backends.toml")
- # Verify pipelex_inference is still enabled (default template state)
+ # Verify pipelex_gateway is still enabled (default template state)
toml_doc = load_toml_with_tomlkit(str(env.inference_dir / "backends.toml"))
- assert toml_doc["pipelex_inference"]["enabled"] is True # type: ignore[index]
+ assert toml_doc[PipelexBackend.GATEWAY]["enabled"] is True # type: ignore[index]
def test_cancel_at_initialization_confirmation(self, tmp_path: Path, mocker: MockerFixture) -> None:
"""Test Case 1.5: Cancel at initialization confirmation."""
diff --git a/tests/e2e/pipelex/cli/test_init_cmd_focused.py b/tests/e2e/pipelex/cli/test_init_cmd_focused.py
index 5ac6249da..7449a71a8 100644
--- a/tests/e2e/pipelex/cli/test_init_cmd_focused.py
+++ b/tests/e2e/pipelex/cli/test_init_cmd_focused.py
@@ -8,6 +8,8 @@ if TYPE_CHECKING:
from pipelex.cli.commands.init.command import init_cmd
from pipelex.cli.commands.init.ui.types import InitFocus
+from pipelex.cogt.model_backends.backend import PipelexBackend
+from pipelex.cogt.model_routing.routing_profile import PipelexRoutingProfile
from pipelex.kit.paths import get_kit_configs_dir
from pipelex.tools.misc.toml_utils import load_toml_with_tomlkit, save_toml_to_path
from tests.helpers.init_cmd_helpers import MockedInitEnvironment, get_backend_indices_helper
@@ -22,8 +24,8 @@ class TestFocusedInitialization:
# User inputs
env.add_confirm_input(True) # Confirm initialization
- env.add_prompt_input("1") # Backend selection
- env.add_prompt_input("1") # Telemetry
+ env.add_confirm_input(True) # Accept gateway terms of service
+ env.add_prompt_input("1") # Backend selection (pipelex_gateway)
env.setup_mocks()
@@ -70,10 +72,10 @@ class TestFocusedInitialization:
env = MockedInitEnvironment(tmp_path, mocker)
env.setup_with_configs(include_backends=True, include_routing=True, include_telemetry=True)
- # Set pipelex_inference as initially enabled
+ # Set pipelex_gateway as initially enabled
backends_path = env.inference_dir / "backends.toml"
toml_doc = load_toml_with_tomlkit(str(backends_path))
- toml_doc["pipelex_inference"]["enabled"] = True # type: ignore[index]
+ toml_doc[PipelexBackend.GATEWAY]["enabled"] = True # type: ignore[index]
save_toml_to_path(toml_doc, str(backends_path))
# Get index for mistral
@@ -157,60 +159,58 @@ class TestFocusedInitialization:
env.verify_routing("all_openai")
def test_telemetry_only_initialization(self, tmp_path: Path, mocker: MockerFixture) -> None:
- """Test Case 5.1: Initialize telemetry only."""
+ """Test Case 5.1: Initialize telemetry only - just copies template."""
# Setup environment with existing config but no telemetry
env = MockedInitEnvironment(tmp_path, mocker)
env.setup_with_configs(include_backends=True, include_routing=True, include_telemetry=False)
- # User inputs
+ # Only need to confirm initialization
env.add_confirm_input(True) # Confirm initialization
- env.add_prompt_input("2") # Telemetry: ANONYMOUS
env.setup_mocks()
# Execute with TELEMETRY focus
init_cmd(focus=InitFocus.TELEMETRY, reset=False)
- # Verify telemetry was created
- env.verify_telemetry("anonymous")
+ # Verify telemetry was created with default mode (off)
+ env.verify_telemetry("off")
def test_reconfigure_telemetry(self, tmp_path: Path, mocker: MockerFixture) -> None:
- """Test Case 5.2: Telemetry already configured - reconfigure."""
+ """Test Case 5.2: Telemetry already configured - reset replaces with template."""
# Setup environment with existing telemetry
env = MockedInitEnvironment(tmp_path, mocker)
env.setup_with_configs(include_backends=True, include_routing=True, include_telemetry=True)
- # Set initial telemetry to OFF
+ # Set initial telemetry to IDENTIFIED
telemetry_path = env.pipelex_dir / "telemetry.toml"
toml_doc = load_toml_with_tomlkit(str(telemetry_path))
- toml_doc["telemetry_mode"] = "off"
+ toml_doc["posthog"]["mode"] = "identified" # type: ignore[index]
save_toml_to_path(toml_doc, str(telemetry_path))
- # User inputs
+ # User inputs - confirm reconfigure
env.add_confirm_input(True) # Confirm reconfigure
- env.add_prompt_input("3") # Change to IDENTIFIED
env.setup_mocks()
- # Execute with TELEMETRY focus
+ # Execute with TELEMETRY focus (will prompt to reconfigure since file exists)
init_cmd(focus=InitFocus.TELEMETRY, reset=False)
- # Verify telemetry was changed
- env.verify_telemetry("identified")
+ # After reconfigure, telemetry should be reset to default (off)
+ env.verify_telemetry("off")
- def test_reset_routing_with_pipelex_inference(self, tmp_path: Path, mocker: MockerFixture) -> None:
- """Test Case: Reset routing when only pipelex_inference is enabled (bug fix test)."""
- # Setup environment with existing config and pipelex_inference enabled
+ def test_reset_routing_with_pipelex_gateway(self, tmp_path: Path, mocker: MockerFixture) -> None:
+ """Test Case: Reset routing when only pipelex_gateway is enabled (bug fix test)."""
+ # Setup environment with existing config and pipelex_gateway enabled
env = MockedInitEnvironment(tmp_path, mocker)
env.setup_with_configs(include_backends=True, include_routing=True, include_telemetry=True)
- # Enable only pipelex_inference (disable everything else)
+ # Enable only pipelex_gateway (disable everything else)
backends_path = env.inference_dir / "backends.toml"
toml_doc = load_toml_with_tomlkit(str(backends_path))
for backend_key in toml_doc:
if backend_key == "internal":
continue
- toml_doc[backend_key]["enabled"] = backend_key == "pipelex_inference" # type: ignore[index]
+ toml_doc[backend_key]["enabled"] = backend_key == PipelexBackend.GATEWAY # type: ignore[index]
save_toml_to_path(toml_doc, str(backends_path))
# Modify routing to have wrong config (simulating the bug scenario)
@@ -227,8 +227,8 @@ class TestFocusedInitialization:
# Execute with ROUTING focus and reset flag
init_cmd(focus=InitFocus.ROUTING, reset=True)
- # Verify routing was reset to pipelex_first (correct for pipelex_inference)
- env.verify_routing("pipelex_first")
+ # Verify routing was reset to pipelex_gateway_first (correct for pipelex_gateway)
+ env.verify_routing(PipelexRoutingProfile.PIPELEX_GATEWAY_FIRST)
def test_everything_already_configured(self, tmp_path: Path, mocker: MockerFixture) -> None:
"""Test Case 7.1: Everything configured - decline reconfigure."""
diff --git a/tests/e2e/pipelex/cli/test_init_cmd_validation.py b/tests/e2e/pipelex/cli/test_init_cmd_validation.py
index 1956bf77e..6f1d08749 100644
--- a/tests/e2e/pipelex/cli/test_init_cmd_validation.py
+++ b/tests/e2e/pipelex/cli/test_init_cmd_validation.py
@@ -8,6 +8,7 @@ if TYPE_CHECKING:
from pipelex.cli.commands.init.command import init_cmd
from pipelex.cli.commands.init.ui.types import InitFocus
+from pipelex.cogt.model_backends.backend import PipelexBackend
from pipelex.kit.paths import get_kit_configs_dir
from tests.helpers.init_cmd_helpers import MockedInitEnvironment, get_backend_indices_helper
@@ -21,9 +22,9 @@ class TestInputValidation:
# User inputs: invalid index, then valid
env.add_confirm_input(True) # Confirm initialization
+ env.add_confirm_input(True) # Accept gateway terms of service
env.add_prompt_input("99") # Invalid index
- env.add_prompt_input("1") # Valid: pipelex_inference
- env.add_prompt_input("1") # Telemetry
+ env.add_prompt_input("1") # Valid: pipelex_gateway
env.setup_mocks()
@@ -31,7 +32,7 @@ class TestInputValidation:
init_cmd(focus=InitFocus.ALL, reset=False)
# Verify successful completion with valid selection
- env.verify_backends_enabled(["pipelex_inference"])
+ env.verify_backends_enabled([PipelexBackend.GATEWAY])
def test_invalid_non_numeric_input_then_valid(self, tmp_path: Path, mocker: MockerFixture) -> None:
"""Test Case 8.2: Non-numeric input, then valid."""
@@ -41,9 +42,9 @@ class TestInputValidation:
# User inputs
env.add_confirm_input(True) # Confirm initialization
+ env.add_confirm_input(True) # Accept gateway terms of service
env.add_prompt_input("abc") # Invalid non-numeric
- env.add_prompt_input("1") # Valid: pipelex_inference
- env.add_prompt_input("1") # Telemetry
+ env.add_prompt_input("1") # Valid: pipelex_gateway
env.setup_mocks()
@@ -51,7 +52,7 @@ class TestInputValidation:
init_cmd(focus=InitFocus.ALL, reset=False)
# Verify successful completion
- env.verify_backends_enabled(["pipelex_inference"])
+ env.verify_backends_enabled([PipelexBackend.GATEWAY])
def test_space_separated_backend_indices(self, tmp_path: Path, mocker: MockerFixture) -> None:
"""Test Case 8.3: Space-separated backend indices."""
@@ -69,7 +70,6 @@ class TestInputValidation:
env.add_prompt_input(indices_str) # Space-separated indices
env.add_prompt_input("1") # Primary backend
env.add_prompt_input("") # Accept default fallback order
- env.add_prompt_input("1") # Telemetry
env.setup_mocks()
@@ -87,8 +87,8 @@ class TestInputValidation:
# User inputs: empty string for default
env.add_confirm_input(True) # Confirm initialization
- env.add_prompt_input("") # Empty = default (pipelex_inference)
- env.add_prompt_input("1") # Telemetry
+ env.add_confirm_input(True) # Accept gateway terms of service
+ env.add_prompt_input("") # Empty = default (pipelex_gateway)
env.setup_mocks()
@@ -96,27 +96,7 @@ class TestInputValidation:
init_cmd(focus=InitFocus.ALL, reset=False)
# Verify default backend is selected
- env.verify_backends_enabled(["pipelex_inference"])
-
- def test_invalid_telemetry_selection_then_valid(self, tmp_path: Path, mocker: MockerFixture) -> None:
- """Test Case 8.6: Invalid telemetry selection."""
- # Setup environment
- env = MockedInitEnvironment(tmp_path, mocker)
- env.setup_empty_dir()
-
- # User inputs
- env.add_confirm_input(True) # Confirm initialization
- env.add_prompt_input("1") # Backend selection
- env.add_prompt_input("5") # Invalid telemetry option
- env.add_prompt_input("2") # Valid: ANONYMOUS
-
- env.setup_mocks()
-
- # Execute
- init_cmd(focus=InitFocus.ALL, reset=False)
-
- # Verify successful completion with valid telemetry
- env.verify_telemetry("anonymous")
+ env.verify_backends_enabled([PipelexBackend.GATEWAY])
def test_invalid_fallback_order_wrong_count(self, tmp_path: Path, mocker: MockerFixture) -> None:
"""Test Case 8.7: Invalid fallback order - wrong count."""
@@ -135,7 +115,6 @@ class TestInputValidation:
env.add_prompt_input("1") # Primary backend
env.add_prompt_input("1") # Invalid: only 1 index instead of 2
env.add_prompt_input("1,2") # Valid: 2 indices for remaining backends
- env.add_prompt_input("1") # Telemetry
env.setup_mocks()
@@ -162,7 +141,6 @@ class TestInputValidation:
env.add_prompt_input("1") # Primary backend
env.add_prompt_input("1,1") # Invalid: duplicate indices
env.add_prompt_input("1,2") # Valid: unique indices
- env.add_prompt_input("1") # Telemetry
env.setup_mocks()
diff --git a/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_1.py b/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_1.py
index 576ae0f07..12db4b601 100644
--- a/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_1.py
+++ b/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_1.py
@@ -2,7 +2,6 @@ from pathlib import Path
from typing import Callable
import pytest
-from pytest import FixtureRequest
from pipelex import pretty_print
from pipelex.core.concepts.concept_factory import ConceptFactory
@@ -27,7 +26,6 @@ class TestPipeConditionExpressionTemplate:
)
async def test_pipe_condition_routing_expression_template(
self,
- request: FixtureRequest,
pipe_run_mode: PipeRunMode,
category: str,
load_test_library: Callable[[list[Path]], None],
@@ -56,7 +54,7 @@ class TestPipeConditionExpressionTemplate:
pipe=get_required_pipe(pipe_code="basic_condition_by_category_2"),
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
working_memory=working_memory,
- job_metadata=JobMetadata(job_name=request.node.originalname), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
),
)
diff --git a/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_2.py b/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_2.py
index c614ac0e1..f799de0cc 100644
--- a/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_2.py
+++ b/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_2.py
@@ -2,7 +2,6 @@ from pathlib import Path
from typing import Callable
import pytest
-from pytest import FixtureRequest
from pipelex import pretty_print
from pipelex.core.concepts.concept_factory import ConceptFactory
@@ -27,7 +26,6 @@ class TestPipeConditionExpression:
)
async def test_pipe_condition_routing_expression(
self,
- request: FixtureRequest,
pipe_run_mode: PipeRunMode,
category: str,
load_test_library: Callable[[list[Path]], None],
@@ -56,7 +54,7 @@ class TestPipeConditionExpression:
pipe=get_required_pipe(pipe_code="basic_condition_by_category"),
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
working_memory=working_memory,
- job_metadata=JobMetadata(job_name=request.node.originalname), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
),
)
diff --git a/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_simple.py b/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_simple.py
index 4eedc246d..082f51214 100644
--- a/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_simple.py
+++ b/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_simple.py
@@ -48,7 +48,7 @@ class TestPipeConditionSimple:
with pytest.raises(PipeRunInputsError) as exc_info:
await pipe_condition.run_pipe(
- job_metadata=JobMetadata(job_name="test_direct_condition_fail"),
+ job_metadata=JobMetadata(),
working_memory=empty_working_memory,
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=PipeRunMode.DRY),
)
@@ -96,7 +96,7 @@ class TestPipeConditionSimple:
try:
pipe_output = await pipe_condition.run_pipe(
- job_metadata=JobMetadata(job_name="test_direct_condition_succeed"),
+ job_metadata=JobMetadata(),
working_memory=working_memory,
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=PipeRunMode.DRY),
)
diff --git a/tests/e2e/pipelex/pipes/pipe_controller/pipe_parallel/test_pipe_parallel_1.py b/tests/e2e/pipelex/pipes/pipe_controller/pipe_parallel/test_pipe_parallel_1.py
index 4994996bb..8385bd50b 100644
--- a/tests/e2e/pipelex/pipes/pipe_controller/pipe_parallel/test_pipe_parallel_1.py
+++ b/tests/e2e/pipelex/pipes/pipe_controller/pipe_parallel/test_pipe_parallel_1.py
@@ -2,7 +2,6 @@ from pathlib import Path
from typing import Callable, cast
import pytest
-from pytest import FixtureRequest
from pipelex import pretty_print
from pipelex.core.concepts.concept_factory import ConceptFactory
@@ -31,7 +30,6 @@ class TestPipeParallelDocumentAnalysis:
)
async def test_pipe_parallel_document_analysis(
self,
- request: FixtureRequest,
pipe_run_mode: PipeRunMode,
document_text: str,
load_test_library: Callable[[list[Path]], None],
@@ -60,7 +58,7 @@ class TestPipeParallelDocumentAnalysis:
pipe=get_required_pipe(pipe_code="parallel_document_analysis"),
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
working_memory=working_memory,
- job_metadata=JobMetadata(job_name=request.node.originalname), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
),
)
diff --git a/tests/e2e/pipelex/pipes/pipe_controller/pipe_sequence/test_pipe_sequence_batching.py b/tests/e2e/pipelex/pipes/pipe_controller/pipe_sequence/test_pipe_sequence_batching.py
index 756c7ab61..b37aeee31 100644
--- a/tests/e2e/pipelex/pipes/pipe_controller/pipe_sequence/test_pipe_sequence_batching.py
+++ b/tests/e2e/pipelex/pipes/pipe_controller/pipe_sequence/test_pipe_sequence_batching.py
@@ -42,7 +42,7 @@ async def test_review_analysis_sequence_with_batching(pipe_run_mode: PipeRunMode
)
pipe = get_required_pipe(pipe_code="analyze_reviews_sequence")
pipe_output = await pipe.run_pipe(
- job_metadata=JobMetadata(job_name="test_review_analysis_sequence_with_batching"),
+ job_metadata=JobMetadata(),
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=PipeRunMode.DRY),
working_memory=working_memory,
)
diff --git a/tests/e2e/pipelex/pipes/pipe_controller/pipe_sequence/test_pipe_sequence_simple.py b/tests/e2e/pipelex/pipes/pipe_controller/pipe_sequence/test_pipe_sequence_simple.py
index 66671ed17..6435942f9 100644
--- a/tests/e2e/pipelex/pipes/pipe_controller/pipe_sequence/test_pipe_sequence_simple.py
+++ b/tests/e2e/pipelex/pipes/pipe_controller/pipe_sequence/test_pipe_sequence_simple.py
@@ -40,7 +40,7 @@ class TestPipeSequenceSimple:
pipe = get_required_pipe(pipe_code="simple_text_sequence")
pipe_output = await pipe.run_pipe(
- job_metadata=JobMetadata(job_name="test_simple_text_sequence"),
+ job_metadata=JobMetadata(),
working_memory=working_memory,
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
)
diff --git a/tests/e2e/pipelex/pipes/pipe_operators/test_pipe_llm_vision.py b/tests/e2e/pipelex/pipes/pipe_operators/test_pipe_llm_vision.py
index 86fc2fd29..0c3cbdd28 100644
--- a/tests/e2e/pipelex/pipes/pipe_operators/test_pipe_llm_vision.py
+++ b/tests/e2e/pipelex/pipes/pipe_operators/test_pipe_llm_vision.py
@@ -22,7 +22,7 @@ class TestPipeLLMVision:
pipe_code="describe_image_e2e",
library_dirs=["tests/e2e/pipelex/pipes/pipe_operators"],
inputs={
- "image": ImageContent(url=LLMVisionTestCases.URL_CLOUDFRONT_ALAN_TURING),
+ "image": ImageContent(url=LLMVisionTestCases.URL_CLOUDFRONT_ALAN_TURING_JPG),
},
pipe_run_mode=pipe_run_mode,
)
@@ -57,7 +57,7 @@ class TestPipeLLMVision:
pipe_code=pipe_code,
library_dirs=["tests/e2e/pipelex/pipes/pipe_operators"],
inputs={
- "image_a": ImageContent(url=LLMVisionTestCases.URL_CLOUDFRONT_ALAN_TURING),
+ "image_a": ImageContent(url=LLMVisionTestCases.URL_CLOUDFRONT_ALAN_TURING_JPG),
"image_b": ImageContent(url=PipeTestCases.URL_IMG_FASHION_PHOTO_1),
},
pipe_run_mode=pipe_run_mode,
@@ -72,7 +72,7 @@ class TestPipeLLMVision:
pipe_output = await execute_pipeline(
pipe_code="vision_analysis_e2e",
inputs={
- "image": ImageContent(url=PipeTestCases.URL_IMG_GANTT_1),
+ "image": ImageContent(url=PipeTestCases.URL_IMG_GANTT_PNG),
},
pipe_run_mode=pipe_run_mode,
)
diff --git a/tests/helpers/init_cmd_helpers.py b/tests/helpers/init_cmd_helpers.py
index 4572135ba..77831f588 100644
--- a/tests/helpers/init_cmd_helpers.py
+++ b/tests/helpers/init_cmd_helpers.py
@@ -91,7 +91,8 @@ def verify_telemetry_config(telemetry_config_path: str, expected_mode: str) -> N
expected_mode: Expected telemetry mode ("off", "anonymous", or "identified").
"""
toml_doc = load_toml_with_tomlkit(telemetry_config_path)
- assert toml_doc["telemetry_mode"] == expected_mode, f"Expected telemetry_mode '{expected_mode}', got '{toml_doc['telemetry_mode']}'"
+ actual_mode = toml_doc["posthog"]["mode"] # type: ignore[index]
+ assert actual_mode == expected_mode, f"Expected posthog.mode '{expected_mode}', got '{actual_mode}'"
class MockedInitEnvironment:
@@ -198,10 +199,8 @@ class MockedInitEnvironment:
self.mocker.patch("pipelex.cli.commands.init.routing.get_console", return_value=self.mock_console)
# Patch UI modules that still instantiate Console directly
- self.mocker.patch("pipelex.cli.commands.init.telemetry.Console")
self.mocker.patch("pipelex.cli.commands.init.ui.backends_ui.Console")
self.mocker.patch("pipelex.cli.commands.init.ui.routing_ui.Console")
- self.mocker.patch("pipelex.cli.commands.init.ui.telemetry_ui.Console")
def add_prompt_input(self, value: str) -> None:
"""Add a prompt input to the sequence.
diff --git a/tests/integration/pipelex/builder/concept/test_concept_spec_generation.py b/tests/integration/pipelex/builder/concept/test_concept_spec_generation.py
index 524b1b2df..98a569418 100644
--- a/tests/integration/pipelex/builder/concept/test_concept_spec_generation.py
+++ b/tests/integration/pipelex/builder/concept/test_concept_spec_generation.py
@@ -45,7 +45,6 @@ class TestConceptSpecGeneration:
user_text=user_prompt,
),
llm_job_config=LLMJobConfig(
- is_streaming_enabled=False,
max_retries=3,
),
llm_job_params=llm_job_params,
diff --git a/tests/integration/pipelex/cli/test_init_cmd_backend_customization.py b/tests/integration/pipelex/cli/test_init_cmd_backend_customization.py
index bd11c89c7..6e1ae841e 100644
--- a/tests/integration/pipelex/cli/test_init_cmd_backend_customization.py
+++ b/tests/integration/pipelex/cli/test_init_cmd_backend_customization.py
@@ -2,40 +2,22 @@ from __future__ import annotations
import shutil
from pathlib import Path
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from pytest_mock import MockerFixture
from pipelex.cli.commands.init.backends import customize_backends_config
from pipelex.cli.commands.init.config_files import init_config
+from pipelex.cogt.model_backends.backend import PipelexBackend
from pipelex.kit.paths import get_kit_configs_dir
from pipelex.tools.misc.toml_utils import load_toml_with_tomlkit
-
-
-def get_backend_indices(backends_toml_path: str, backend_names: list[str]) -> list[int]:
- """Get 1-based indices for given backend names from backends.toml.
-
- Args:
- backends_toml_path: Path to backends.toml file.
- backend_names: List of backend keys to find indices for.
-
- Returns:
- List of 1-based indices corresponding to the backend names.
- """
- toml_doc = load_toml_with_tomlkit(backends_toml_path)
- backend_list: list[str] = [key for key in toml_doc if key != "internal"]
- indices: list[int] = []
- for name in backend_names:
- if name in backend_list:
- # 1-based index for user input
- indices.append(backend_list.index(name) + 1)
- return indices
+from tests.helpers.init_cmd_helpers import get_backend_indices_helper
class TestBackendCustomization:
def test_customize_backends_config_with_default_selection(self, tmp_path: Path, mocker: MockerFixture) -> None:
- """Test backend customization with default selection (pipelex_inference)."""
+ """Test backend customization with default selection (pipelex_gateway)."""
# Setup directories with actual backends.toml
inference_dir = tmp_path / ".pipelex" / "inference"
inference_dir.mkdir(parents=True)
@@ -45,14 +27,34 @@ class TestBackendCustomization:
test_backends = inference_dir / "backends.toml"
shutil.copy2(actual_backends, test_backends)
- # Mock config_manager and user input
+ # Mock config_manager
mock_config_manager = mocker.MagicMock()
mock_config_manager.pipelex_config_dir = str(tmp_path / ".pipelex")
mocker.patch("pipelex.cli.commands.init.backends.config_manager", mock_config_manager)
- # Mock console provider and Prompt to simulate user selecting default [1]
+ # Mock console provider
mocker.patch("pipelex.cli.commands.init.backends.get_console", return_value=mocker.MagicMock())
- mocker.patch("pipelex.cli.commands.init.ui.backends_ui.Prompt.ask", return_value="1")
+
+ # Setup input queues - global patching like MockedInitEnvironment
+ prompt_inputs = ["1"] # Select pipelex_gateway
+ confirm_inputs = [True] # Accept gateway terms
+
+ def prompt_side_effect(*args: Any, **_kwargs: Any) -> str:
+ if not prompt_inputs:
+ question = str(args[0]) if args else "<unknown prompt>"
+ msg = f"Unexpected prompt without predefined input: {question}"
+ raise AssertionError(msg)
+ return prompt_inputs.pop(0)
+
+ def confirm_side_effect(*args: Any, **_kwargs: Any) -> bool:
+ if not confirm_inputs:
+ question = str(args[0]) if args else "<unknown confirmation>"
+ msg = f"Unexpected confirm without predefined input: {question}"
+ raise AssertionError(msg)
+ return confirm_inputs.pop(0)
+
+ mocker.patch("rich.prompt.Prompt.ask", side_effect=prompt_side_effect)
+ mocker.patch("rich.prompt.Confirm.ask", side_effect=confirm_side_effect)
# Execute
customize_backends_config()
@@ -60,9 +62,9 @@ class TestBackendCustomization:
# Verify backends.toml was customized
toml_doc = load_toml_with_tomlkit(str(test_backends))
- # pipelex_inference should be enabled
- assert "enabled" in toml_doc["pipelex_inference"] # type: ignore[operator]
- assert toml_doc["pipelex_inference"]["enabled"] is True # type: ignore[index]
+ # pipelex_gateway should be enabled
+ assert "enabled" in toml_doc[PipelexBackend.GATEWAY] # type: ignore[operator]
+ assert toml_doc[PipelexBackend.GATEWAY]["enabled"] is True # type: ignore[index]
# Other backends should be disabled
for backend in ["openai", "anthropic", "mistral", "fal"]:
@@ -84,17 +86,28 @@ class TestBackendCustomization:
# Dynamically get indices for the backends we want to test
backend_names = ["openai", "anthropic", "mistral"]
- indices = get_backend_indices(str(actual_backends), backend_names)
- indices_str = ",".join(str(i) for i in indices)
+ indices = get_backend_indices_helper(str(actual_backends), backend_names)
+ indices_str = ",".join(str(idx) for idx in indices)
# Mock config_manager
mock_config_manager = mocker.MagicMock()
mock_config_manager.pipelex_config_dir = str(tmp_path / ".pipelex")
mocker.patch("pipelex.cli.commands.init.backends.config_manager", mock_config_manager)
- # Mock user input with dynamically determined indices
+ # Mock console provider
mocker.patch("pipelex.cli.commands.init.backends.get_console", return_value=mocker.MagicMock())
- mocker.patch("pipelex.cli.commands.init.ui.backends_ui.Prompt.ask", return_value=indices_str)
+
+ # Setup input queues - no gateway selected, so no confirm needed
+ prompt_inputs = [indices_str]
+
+ def prompt_side_effect(*args: Any, **_kwargs: Any) -> str:
+ if not prompt_inputs:
+ question = str(args[0]) if args else "<unknown prompt>"
+ msg = f"Unexpected prompt without predefined input: {question}"
+ raise AssertionError(msg)
+ return prompt_inputs.pop(0)
+
+ mocker.patch("rich.prompt.Prompt.ask", side_effect=prompt_side_effect)
# Execute
customize_backends_config()
@@ -107,8 +120,8 @@ class TestBackendCustomization:
assert toml_doc["anthropic"]["enabled"] is True # type: ignore[index]
assert toml_doc["mistral"]["enabled"] is True # type: ignore[index]
- # pipelex_inference should be disabled
- assert toml_doc["pipelex_inference"]["enabled"] is False # type: ignore[index]
+ # pipelex_gateway should be disabled
+ assert toml_doc[PipelexBackend.GATEWAY]["enabled"] is False # type: ignore[index]
# fal should be disabled
assert toml_doc["fal"]["enabled"] is False # type: ignore[index]
@@ -126,17 +139,38 @@ class TestBackendCustomization:
shutil.copy2(actual_backends, test_backends)
# Dynamically get indices for the backends we want to test
- backend_names = ["pipelex_inference", "openai", "fal"]
- indices = get_backend_indices(str(actual_backends), backend_names)
- indices_str = " ".join(str(i) for i in indices)
+ backend_names = [PipelexBackend.GATEWAY, "openai", "fal"]
+ indices = get_backend_indices_helper(str(actual_backends), backend_names)
+ indices_str = " ".join(str(idx) for idx in indices)
+ # Mock config_manager
mock_config_manager = mocker.MagicMock()
mock_config_manager.pipelex_config_dir = str(tmp_path / ".pipelex")
mocker.patch("pipelex.cli.commands.init.backends.config_manager", mock_config_manager)
- # Mock user input with spaces and dynamically determined indices
+ # Mock console provider
mocker.patch("pipelex.cli.commands.init.backends.get_console", return_value=mocker.MagicMock())
- mocker.patch("pipelex.cli.commands.init.ui.backends_ui.Prompt.ask", return_value=indices_str)
+
+ # Setup input queues - gateway selected, so confirm needed
+ prompt_inputs = [indices_str]
+ confirm_inputs = [True] # Accept gateway terms
+
+ def prompt_side_effect(*args: Any, **_kwargs: Any) -> str:
+ if not prompt_inputs:
+ question = str(args[0]) if args else "<unknown prompt>"
+ msg = f"Unexpected prompt without predefined input: {question}"
+ raise AssertionError(msg)
+ return prompt_inputs.pop(0)
+
+ def confirm_side_effect(*args: Any, **_kwargs: Any) -> bool:
+ if not confirm_inputs:
+ question = str(args[0]) if args else "<unknown confirmation>"
+ msg = f"Unexpected confirm without predefined input: {question}"
+ raise AssertionError(msg)
+ return confirm_inputs.pop(0)
+
+ mocker.patch("rich.prompt.Prompt.ask", side_effect=prompt_side_effect)
+ mocker.patch("rich.prompt.Confirm.ask", side_effect=confirm_side_effect)
# Execute
customize_backends_config()
@@ -145,7 +179,7 @@ class TestBackendCustomization:
toml_doc = load_toml_with_tomlkit(str(test_backends))
# Selected backends should be enabled
- assert toml_doc["pipelex_inference"]["enabled"] is True # type: ignore[index]
+ assert toml_doc[PipelexBackend.GATEWAY]["enabled"] is True # type: ignore[index]
assert toml_doc["openai"]["enabled"] is True # type: ignore[index]
assert toml_doc["fal"]["enabled"] is True # type: ignore[index]
@@ -188,9 +222,9 @@ class TestBackendCustomization:
# Verify backend customization was NOT applied (original values preserved)
toml_doc = load_toml_with_tomlkit(str(target_dir / "inference" / "backends.toml"))
- # Verify original enabled states from template (template has all backends enabled by default)
- assert toml_doc["pipelex_inference"]["enabled"] is True # type: ignore[index]
- assert toml_doc["openai"]["enabled"] is True # type: ignore[index]
+ # Verify original enabled states from template
+ # pipelex_gateway is enabled by default, pipelex_inference is deprecated (disabled)
+ assert toml_doc[PipelexBackend.GATEWAY]["enabled"] is True # type: ignore[index]
assert toml_doc["anthropic"]["enabled"] is True # type: ignore[index]
assert toml_doc["mistral"]["enabled"] is True # type: ignore[index]
assert toml_doc["internal"]["enabled"] is True # type: ignore[index]
diff --git a/tests/integration/pipelex/cli/test_init_cmd_integration.py b/tests/integration/pipelex/cli/test_init_cmd_integration.py
index 59a8ed7e2..51a83b45a 100644
--- a/tests/integration/pipelex/cli/test_init_cmd_integration.py
+++ b/tests/integration/pipelex/cli/test_init_cmd_integration.py
@@ -8,6 +8,8 @@ if TYPE_CHECKING:
from pipelex.cli.commands.init.command import init_cmd
from pipelex.cli.commands.init.ui.types import InitFocus
+from pipelex.cogt.model_backends.backend import PipelexBackend
+from pipelex.cogt.model_routing.routing_profile import PipelexRoutingProfile
from pipelex.kit.paths import get_kit_configs_dir
from pipelex.tools.misc.toml_utils import load_toml_with_tomlkit, save_toml_to_path
from tests.helpers.init_cmd_helpers import MockedInitEnvironment, get_backend_indices_helper
@@ -20,10 +22,10 @@ class TestInitCommandIntegration:
env = MockedInitEnvironment(tmp_path, mocker)
env.setup_empty_dir()
- # User inputs: confirm init, select all backends, select telemetry OFF
+ # User inputs: confirm init, select all backends
env.add_confirm_input(True) # Confirm initialization
+ env.add_confirm_input(True) # Accept gateway terms of service (since "all" includes gateway)
env.add_prompt_input("all") # Select all backends
- env.add_prompt_input("1") # Telemetry: OFF
env.setup_mocks()
@@ -36,10 +38,10 @@ class TestInitCommandIntegration:
if backend_key != "internal":
assert toml_doc[backend_key]["enabled"] is True # type: ignore[index]
- # Verify routing was set to pipelex_first (since pipelex_inference is in "all")
- env.verify_routing("pipelex_first")
+ # Verify routing was set to pipelex_gateway_first (since pipelex_gateway is in "all")
+ env.verify_routing(PipelexRoutingProfile.PIPELEX_GATEWAY_FIRST)
- # Verify telemetry
+ # Verify telemetry (always "off" - default from template)
env.verify_telemetry("off")
def test_init_with_multiple_backends_custom_routing(self, tmp_path: Path, mocker: MockerFixture) -> None:
@@ -58,7 +60,6 @@ class TestInitCommandIntegration:
env.add_prompt_input(indices_str) # Select anthropic, mistral, openai
env.add_prompt_input("1") # Primary backend: first one (anthropic)
env.add_prompt_input("") # Accept default fallback order
- env.add_prompt_input("2") # Telemetry: ANONYMOUS
env.setup_mocks()
@@ -71,8 +72,8 @@ class TestInitCommandIntegration:
# Verify custom routing was created
env.verify_routing("custom_routing", expected_default="anthropic")
- # Verify telemetry
- env.verify_telemetry("anonymous")
+ # Verify telemetry (always "off" - default from template)
+ env.verify_telemetry("off")
def test_init_with_single_backend_auto_routing(self, tmp_path: Path, mocker: MockerFixture) -> None:
"""Test initialization with single backend sets auto routing."""
@@ -88,7 +89,6 @@ class TestInitCommandIntegration:
env.add_confirm_input(True) # Confirm initialization
env.add_prompt_input(str(indices[0])) # Select only openai
env.add_confirm_input(True) # Confirm creating profile if needed
- env.add_prompt_input("3") # Telemetry: IDENTIFIED
env.setup_mocks()
@@ -101,8 +101,8 @@ class TestInitCommandIntegration:
# Verify routing is set to all_openai
env.verify_routing("all_openai")
- # Verify telemetry
- env.verify_telemetry("identified")
+ # Verify telemetry (always "off" - default from template)
+ env.verify_telemetry("off")
def test_init_config_only_focus(self, tmp_path: Path, mocker: MockerFixture) -> None:
"""Test focused initialization: config files only."""
@@ -112,8 +112,8 @@ class TestInitCommandIntegration:
# User inputs - CONFIG focus still runs full init on first time
env.add_confirm_input(True) # Confirm initialization
- env.add_prompt_input("1") # Backend selection (pipelex_inference)
- env.add_prompt_input("1") # Telemetry
+ env.add_confirm_input(True) # Accept gateway terms of service
+ env.add_prompt_input("1") # Backend selection (pipelex_gateway)
env.setup_mocks()
@@ -125,8 +125,8 @@ class TestInitCommandIntegration:
env.verify_file_exists("inference/backends.toml")
# CONFIG focus on first init triggers full flow
- env.verify_backends_enabled(["pipelex_inference"])
- env.verify_routing("pipelex_first")
+ env.verify_backends_enabled([PipelexBackend.GATEWAY])
+ env.verify_routing(PipelexRoutingProfile.PIPELEX_GATEWAY_FIRST)
# Telemetry should be created
if (env.pipelex_dir / "telemetry.toml").exists():
env.verify_telemetry("off")
@@ -168,17 +168,16 @@ class TestInitCommandIntegration:
env = MockedInitEnvironment(tmp_path, mocker)
env.setup_with_configs(include_backends=True, include_routing=True, include_telemetry=False)
- # User inputs
+ # Only need to confirm initialization
env.add_confirm_input(True) # Confirm initialization
- env.add_prompt_input("2") # Telemetry: ANONYMOUS
env.setup_mocks()
# Execute with TELEMETRY focus
init_cmd(focus=InitFocus.TELEMETRY, reset=False)
- # Verify telemetry was created
- env.verify_telemetry("anonymous")
+ # Verify telemetry was created with default mode (off)
+ env.verify_telemetry("off")
def test_init_with_reset_flag(self, tmp_path: Path, mocker: MockerFixture) -> None:
"""Test initialization with reset flag overwrites existing config."""
@@ -186,10 +185,10 @@ class TestInitCommandIntegration:
env = MockedInitEnvironment(tmp_path, mocker)
env.setup_with_configs(include_backends=True, include_routing=True, include_telemetry=True)
- # Modify telemetry to a different value
+ # Modify telemetry to a different value (using new nested path)
telemetry_path = env.pipelex_dir / "telemetry.toml"
toml_doc = load_toml_with_tomlkit(str(telemetry_path))
- toml_doc["telemetry_mode"] = "identified"
+ toml_doc["posthog"]["mode"] = "identified" # type: ignore[index]
save_toml_to_path(toml_doc, str(telemetry_path))
# Get index for mistral
@@ -200,7 +199,6 @@ class TestInitCommandIntegration:
env.add_confirm_input(True) # Confirm reset
env.add_prompt_input(str(indices[0])) # Select mistral only
env.add_confirm_input(True) # Confirm creating profile if needed
- env.add_prompt_input("1") # Telemetry: OFF
env.setup_mocks()
@@ -210,7 +208,7 @@ class TestInitCommandIntegration:
# Verify backends were reset
env.verify_backends_enabled(["mistral"])
- # Verify telemetry was reset to OFF
+ # Verify telemetry was reset to OFF (default from template)
env.verify_telemetry("off")
def test_init_reconfigure_existing_inference(self, tmp_path: Path, mocker: MockerFixture) -> None:
@@ -219,10 +217,10 @@ class TestInitCommandIntegration:
env = MockedInitEnvironment(tmp_path, mocker)
env.setup_with_configs(include_backends=True, include_routing=True, include_telemetry=True)
- # Set pipelex_inference as enabled initially
+ # Set pipelex_gateway as enabled initially
backends_path = env.inference_dir / "backends.toml"
toml_doc = load_toml_with_tomlkit(str(backends_path))
- toml_doc["pipelex_inference"]["enabled"] = True # type: ignore[index]
+ toml_doc[PipelexBackend.GATEWAY]["enabled"] = True # type: ignore[index]
save_toml_to_path(toml_doc, str(backends_path))
# Get index for openai
@@ -260,7 +258,6 @@ class TestInitCommandIntegration:
env.add_confirm_input(True) # Confirm initialization
env.add_prompt_input(indices_str) # Select anthropic, openai
env.add_prompt_input("1") # Primary backend: anthropic (first in selection)
- env.add_prompt_input("1") # Telemetry: OFF
env.setup_mocks()
@@ -273,21 +270,21 @@ class TestInitCommandIntegration:
# Verify custom routing with automatic fallback order
env.verify_routing("custom_routing", expected_default="anthropic", expected_fallback_order=["anthropic", "openai"])
- def test_init_pipelex_inference_sets_pipelex_first(self, tmp_path: Path, mocker: MockerFixture) -> None:
- """Test that selecting pipelex_inference automatically sets pipelex_first routing."""
+ def test_init_pipelex_gateway_sets_pipelex_gateway_first(self, tmp_path: Path, mocker: MockerFixture) -> None:
+ """Test that selecting pipelex_gateway automatically sets pipelex_gateway_first routing."""
# Setup environment
env = MockedInitEnvironment(tmp_path, mocker)
env.setup_empty_dir()
- # Get indices for pipelex_inference and openai
+ # Get indices for pipelex_gateway and openai
kit_backends = Path(str(get_kit_configs_dir())) / "inference" / "backends.toml"
- indices = get_backend_indices_helper(str(kit_backends), ["pipelex_inference", "openai"])
+ indices = get_backend_indices_helper(str(kit_backends), [PipelexBackend.GATEWAY, "openai"])
indices_str = ",".join(str(i) for i in indices)
- # User inputs - no primary/fallback prompts because pipelex_inference is included
+ # User inputs - no primary/fallback prompts because pipelex_gateway is included
env.add_confirm_input(True) # Confirm initialization
- env.add_prompt_input(indices_str) # Select pipelex_inference and openai
- env.add_prompt_input("1") # Telemetry: OFF
+ env.add_confirm_input(True) # Accept gateway terms of service
+ env.add_prompt_input(indices_str) # Select pipelex_gateway and openai
env.setup_mocks()
@@ -295,7 +292,7 @@ class TestInitCommandIntegration:
init_cmd(focus=InitFocus.ALL, reset=False)
# Verify backends
- env.verify_backends_enabled(["pipelex_inference", "openai"])
+ env.verify_backends_enabled([PipelexBackend.GATEWAY, "openai"])
- # Verify routing is automatically set to pipelex_first
- env.verify_routing("pipelex_first")
+ # Verify routing is automatically set to pipelex_gateway_first
+ env.verify_routing(PipelexRoutingProfile.PIPELEX_GATEWAY_FIRST)
diff --git a/tests/integration/pipelex/cogt/test_content_generator.py b/tests/integration/pipelex/cogt/test_content_generator.py
index ac8372521..3a76916a6 100644
--- a/tests/integration/pipelex/cogt/test_content_generator.py
+++ b/tests/integration/pipelex/cogt/test_content_generator.py
@@ -1,5 +1,4 @@
import pytest
-from pytest import FixtureRequest
from pipelex import pretty_print
from pipelex.cogt.exceptions import ModelNotFoundError
@@ -56,11 +55,11 @@ Write a haiku about the meaning of life
class TestContentGenerator:
@pytest.mark.llm
@pytest.mark.inference
- async def test_make_llm_text_only(self, request: FixtureRequest):
+ async def test_make_llm_text_only(self):
llm_setting_main = get_model_deck().get_llm_setting(llm_choice="llm_for_testing_gen_text")
text: str = await get_content_generator().make_llm_text(
- job_metadata=JobMetadata(job_name=request.node.originalname), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
llm_prompt_for_text=LLMPrompt(user_text=USER_TEXT_FOR_BASE),
llm_setting_main=llm_setting_main,
)
@@ -70,11 +69,11 @@ class TestContentGenerator:
@pytest.mark.llm
@pytest.mark.inference
- async def test_make_object_direct(self, request: FixtureRequest):
+ async def test_make_object_direct(self):
llm_setting_for_object = get_model_deck().get_llm_setting(llm_choice="llm_for_testing_gen_object")
person_direct: Employee = await get_content_generator().make_object_direct(
- job_metadata=JobMetadata(job_name=request.node.originalname), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
object_class=Employee,
llm_prompt_for_object=LLMPrompt(user_text=USER_TEXT_FOR_SINGLE_PERSON),
llm_setting_for_object=llm_setting_for_object,
@@ -85,11 +84,11 @@ class TestContentGenerator:
@pytest.mark.llm
@pytest.mark.inference
- async def test_make_object_list_direct(self, request: FixtureRequest):
+ async def test_make_object_list_direct(self):
llm_setting_for_object = get_model_deck().get_llm_setting(llm_choice="llm_for_testing_gen_object")
person_list_direct: list[Employee] = await get_content_generator().make_object_list_direct(
- job_metadata=JobMetadata(job_name=request.node.originalname), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
object_class=Employee,
llm_prompt_for_object_list=LLMPrompt(user_text=USER_TEXTS_FOR_PEOPLE_STR),
llm_setting_for_object_list=llm_setting_for_object,
@@ -101,11 +100,11 @@ class TestContentGenerator:
@pytest.mark.img_gen
@pytest.mark.inference
- async def test_make_image(self, request: FixtureRequest):
+ async def test_make_image(self):
img_gen_handle = "fast-lightning-sdxl"
positive_text = "A dog with sunglasses coding on a laptop"
image: GeneratedImage = await get_content_generator().make_single_image(
- job_metadata=JobMetadata(job_name=request.node.originalname), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
img_gen_handle=img_gen_handle,
img_gen_prompt=ImgGenPrompt(
positive_text=positive_text,
@@ -129,11 +128,11 @@ class TestContentGenerator:
@pytest.mark.extract
@pytest.mark.inference
- async def test_make_extract_pages_from_image(self, extract_handle_from_image: str, request: FixtureRequest):
+ async def test_make_extract_pages_from_image(self, extract_handle_from_image: str):
extract_output = await get_content_generator().make_extract_pages(
- job_metadata=JobMetadata(job_name=request.node.originalname), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
extract_handle=extract_handle_from_image,
- extract_input=ExtractInput(image_uri=ImageTestCases.IMAGE_FILE_PATH_PNG),
+ extract_input=ExtractInput(image_uri=ImageTestCases.IMAGE_FILE_PATH_PNG_1),
extract_job_params=ExtractJobParams.make_default_extract_job_params(),
extract_job_config=ExtractJobConfig(),
)
@@ -142,9 +141,9 @@ class TestContentGenerator:
@pytest.mark.extract
@pytest.mark.inference
- async def test_make_extract_pages_from_pdf(self, extract_handle: str, request: FixtureRequest):
+ async def test_make_extract_pages_from_pdf(self, extract_handle: str):
extract_output = await get_content_generator().make_extract_pages(
- job_metadata=JobMetadata(job_name=request.node.originalname), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
extract_handle=extract_handle,
extract_input=ExtractInput(pdf_uri=PDFTestCases.PDF_FILE_PATH_1),
extract_job_params=ExtractJobParams.make_default_extract_job_params(),
@@ -155,11 +154,11 @@ class TestContentGenerator:
@pytest.mark.llm
@pytest.mark.inference
- async def test_make_llm_text_with_error(self, request: FixtureRequest):
+ async def test_make_llm_text_with_error(self):
llm_setting_main = LLMSetting(model="bad_handle_to_test_failure", temperature=0.5, max_tokens=100)
with pytest.raises(ModelNotFoundError) as excinfo:
await get_content_generator().make_llm_text(
- job_metadata=JobMetadata(job_name=request.node.originalname), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
llm_prompt_for_text=LLMPrompt(user_text=USER_TEXT_FOR_BASE),
llm_setting_main=llm_setting_main,
)
diff --git a/tests/integration/pipelex/cogt/test_data.py b/tests/integration/pipelex/cogt/test_data.py
index bebe14c97..0267a9520 100644
--- a/tests/integration/pipelex/cogt/test_data.py
+++ b/tests/integration/pipelex/cogt/test_data.py
@@ -47,11 +47,10 @@ class ImageDescription(BaseModel):
class LLMVisionTestCases:
- VISION_USER_TEXT_1 = "Describe the provide image."
- VISION_USER_TEXT_2 = "What is this image about?"
- VISION_IMAGES_COMPARE_PROMPT = "Compare these two images"
+ VISION_USER_TEXT = "Describe the provide image in 1-2 concise sentences."
+ VISION_IMAGES_COMPARE_PROMPT = "Compare these two images in 2-3 concise bullet points."
- URL_CLOUDFRONT_ALAN_TURING = "https://d2cinlfp2qnig1.cloudfront.net/tests/alan_turing.jpg"
+ URL_CLOUDFRONT_ALAN_TURING_JPG = "https://d2cinlfp2qnig1.cloudfront.net/tests/alan_turing.jpg"
TEST_IMAGE_DIRECTORY = "tests/data/images"
@@ -67,10 +66,12 @@ class LLMVisionTestCases:
PATH_IMG_GANTT_1 = f"{TEST_IMAGE_DIRECTORY}/diagram.png"
IMAGE_PATHS: ClassVar[list[tuple[str, str]]] = [ # topic, image_path
+ ("Gantt Chart", PATH_IMG_GANTT_1),
("AI Lympics PNG", PATH_IMG_PNG_1),
+ ("Animal Lympics PNG", PATH_IMG_PNG_2),
("AI Lympics JPEG", PATH_IMG_JPEG_1),
- ("Gantt Chart", PATH_IMG_GANTT_1),
("Eiffel Tower", PATH_IMG_JPEG_3),
+ ("Eiffel Tower", PATH_IMG_PNG_3),
]
IMAGE_PATH_PAIRS: ClassVar[list[tuple[str, tuple[str, str]]]] = [ # topic, image_pair
("AI Lympics PNG", (PATH_IMG_PNG_1, PATH_IMG_PNG_2)),
@@ -79,18 +80,26 @@ class LLMVisionTestCases:
IMAGE_URLS: ClassVar[list[tuple[str, str]]] = [ # topic, image_uri
(
"Alan Turing",
- URL_CLOUDFRONT_ALAN_TURING,
+ URL_CLOUDFRONT_ALAN_TURING_JPG,
),
(
"Gantt chart",
- PipeTestCases.URL_IMG_GANTT_1,
+ PipeTestCases.URL_IMG_GANTT_PNG,
),
]
class LLMTestConstants:
- USER_TEXT_SHORT = "In one sentence, who is Bill Gates?"
+ USER_TEXT_SHORT = "In one short sentence, who is Bill Gates?"
+ USER_TEXT_SUPER_SHORT = "In one short sentence (< 5 words), who is Bill Gates?"
USER_TEXT_TO_EXTRACT_PERSON = "It's Robert, the nice plumber, he turns 57 next week."
+ USER_TEXT_TRICKY_1 = """
+When my son was 7 he was 3ft tall. When he was 8 he was 4ft tall. When he was 9 he was 5ft tall.
+How tall do you think he was when he was 12? and at 15?
+"""
+ USER_TEXT_TRICKY_2 = """
+Count the Rs in "Strawberry"
+"""
# USER_TEXT_SHORT = "What's the biggest football match tonight in Europe?"
PROMPT_TEMPLATE_TEXT = "Can you give one example of flower which is {color} in color ?"
PROMPT_COLOR_EXAMPLES: ClassVar[list[str]] = [
diff --git a/tests/integration/pipelex/cogt/test_extract.py b/tests/integration/pipelex/cogt/test_extract.py
index 3972f840c..bb50165e8 100644
--- a/tests/integration/pipelex/cogt/test_extract.py
+++ b/tests/integration/pipelex/cogt/test_extract.py
@@ -34,17 +34,17 @@ class TestExtract:
extract_input=ExtractInput(pdf_uri=url),
)
extract_output = await extract_worker.extract_pages(extract_job=extract_job)
- pretty_print(extract_output, title="OCR Output")
+ pretty_print(extract_output, title="Extract Output")
assert extract_output.pages
- @pytest.mark.parametrize("file_path", ImageTestCases.IMAGE_FILE_PATHS)
- async def test_extract_image_file(self, extract_handle_from_image: str, file_path: str):
+ @pytest.mark.parametrize("file_path", ImageTestCases.IMAGE_TEXT_FILE_PATHS)
+ async def test_extract_image_path(self, extract_handle_from_image: str, file_path: str):
extract_worker = get_extract_worker(extract_handle=extract_handle_from_image)
extract_job = ExtractJobFactory.make_extract_job(
extract_input=ExtractInput(image_uri=file_path),
)
extract_output = await extract_worker.extract_pages(extract_job=extract_job)
- pretty_print(extract_output, title="OCR Output")
+ pretty_print(extract_output, title="Extract Output")
assert extract_output.pages
@pytest.mark.parametrize("url", ImageTestCases.IMAGE_URLS)
@@ -54,7 +54,7 @@ class TestExtract:
extract_input=ExtractInput(image_uri=url),
)
extract_output = await extract_worker.extract_pages(extract_job=extract_job)
- pretty_print(extract_output, title="OCR Output")
+ pretty_print(extract_output, title="Extract Output")
assert extract_output.pages
@pytest.mark.parametrize("file_path", PDFTestCases.DOCUMENT_FILE_PATHS)
@@ -73,7 +73,7 @@ class TestExtract:
extract_job_params=extract_job_params,
)
extract_output = await extract_worker.extract_pages(extract_job=extract_job)
- pretty_print(extract_output, title="OCR Output")
+ pretty_print(extract_output, title="Extract Output")
directory = get_incremental_directory_path(
base_path="results/test_ocr_image_save",
base_name="extract_output",
diff --git a/tests/integration/pipelex/cogt/test_img_gen.py b/tests/integration/pipelex/cogt/test_img_gen.py
index 8c9197bfb..930beab52 100644
--- a/tests/integration/pipelex/cogt/test_img_gen.py
+++ b/tests/integration/pipelex/cogt/test_img_gen.py
@@ -105,3 +105,15 @@ class TestImageGeneration:
output_path = f"{image_name}{extension}"
image.save(output_path)
print_to_stderr(f"✓ Image saved to: {output_path}\n")
+
+ @pytest.mark.parametrize(("topic", "img_gen_prompt_text"), ImageGenTestCases.IMAGE_DESC)
+ async def test_img_gen_multiple(self, img_gen_handle: str, topic: str, img_gen_prompt_text: str):
+ img_gen_worker_async = get_img_gen_worker(img_gen_handle=img_gen_handle)
+ img_gen_job = ImgGenJobFactory.make_img_gen_job_from_prompt_contents(
+ positive_text=img_gen_prompt_text,
+ )
+ generated_image_list = await img_gen_worker_async.gen_image_list(
+ img_gen_job=img_gen_job,
+ nb_images=3,
+ )
+ pretty_print(generated_image_list, title=f"Images generated by '{img_gen_handle}' for topic '{topic}'")
diff --git a/tests/integration/pipelex/cogt/test_llm_gen_object.py b/tests/integration/pipelex/cogt/test_llm_gen_object.py
index c00c72fd8..4fe237556 100644
--- a/tests/integration/pipelex/cogt/test_llm_gen_object.py
+++ b/tests/integration/pipelex/cogt/test_llm_gen_object.py
@@ -23,7 +23,6 @@ def get_async_worker_and_job(llm_preset_id: str, user_text: str):
),
llm_job_params=llm_job_params,
llm_job_config=LLMJobConfig(
- is_streaming_enabled=False,
max_retries=3,
),
)
@@ -46,7 +45,6 @@ class TestLLMGenObject:
),
llm_job_params=llm_job_params,
llm_job_config=LLMJobConfig(
- is_streaming_enabled=False,
max_retries=3,
),
)
@@ -87,7 +85,6 @@ class TestLLMGenObject:
),
llm_job_params=llm_job_params,
llm_job_config=LLMJobConfig(
- is_streaming_enabled=False,
max_retries=3,
),
)
@@ -117,7 +114,6 @@ class TestLLMGenObject:
),
llm_job_params=llm_job.job_params,
llm_job_config=LLMJobConfig(
- is_streaming_enabled=False,
max_retries=3,
),
)
diff --git a/tests/integration/pipelex/cogt/test_llm_gen_text.py b/tests/integration/pipelex/cogt/test_llm_gen_text.py
index d261522e4..2791afe35 100644
--- a/tests/integration/pipelex/cogt/test_llm_gen_text.py
+++ b/tests/integration/pipelex/cogt/test_llm_gen_text.py
@@ -9,7 +9,7 @@ from pipelex.cogt.llm.llm_job_factory import LLMJobFactory
from pipelex.cogt.llm.llm_prompt import LLMPrompt
from pipelex.cogt.llm.llm_worker_abstract import LLMWorkerAbstract
from pipelex.cogt.llm.llm_worker_internal_abstract import LLMWorkerInternalAbstract
-from pipelex.cogt.model_backends.model_constraints import ModelConstraints
+from pipelex.cogt.model_backends.constraints import ListedConstraint, ValuedConstraint
from pipelex.hub import get_llm_worker, get_model_deck
from tests.integration.pipelex.cogt.test_data import LLMTestCases
@@ -26,7 +26,6 @@ def get_worker_and_job(llm_preset_id: str, user_text: str) -> tuple[LLMWorkerAbs
),
llm_job_params=llm_job_params,
llm_job_config=LLMJobConfig(
- is_streaming_enabled=False,
max_retries=3,
),
)
@@ -48,7 +47,6 @@ class TestLLMGenText:
),
llm_job_params=llm_job_params,
llm_job_config=LLMJobConfig(
- is_streaming_enabled=False,
max_retries=3,
),
)
@@ -77,11 +75,12 @@ class TestLLMGenText:
break
llm_job.job_params = job_params_base.model_copy(update={"max_tokens": max_tokens, "temperature": temperature})
if isinstance(llm_worker, LLMWorkerInternalAbstract):
- if ModelConstraints.TEMPERATURE_MUST_BE_1 in llm_worker.inference_model.constraints:
- log.warning("ModelConstraints TEMPERATURE_MUST_BE_1, forcing temprature to 1, setting minimum tokens to avoid empty output")
- llm_job.job_params = job_params_base.model_copy(update={"temperature": 1})
- if ModelConstraints.MAX_TOKENS_MUST_BE_HIGH_ENOUGH in llm_worker.inference_model.constraints:
- log.warning("ModelConstraints MAX_TOKENS_MUST_BE_HIGH_ENOUGH, forcing max tokens to at least2000")
+ fixed_temp = llm_worker.inference_model.valued_constraints.get(ValuedConstraint.FIXED_TEMPERATURE)
+ if fixed_temp is not None:
+ log.warning(f"ValuedConstraint FIXED_TEMPERATURE={fixed_temp}, forcing temperature")
+ llm_job.job_params = job_params_base.model_copy(update={"temperature": fixed_temp})
+ if ListedConstraint.MAX_TOKENS_MUST_BE_HIGH_ENOUGH in llm_worker.inference_model.listed_constraints:
+ log.warning("ListedConstraint MAX_TOKENS_MUST_BE_HIGH_ENOUGH, forcing max tokens to at least2000")
completion_max_tokens = max(max_tokens, 2000)
llm_job.job_params = job_params_base.model_copy(update={"max_tokens": completion_max_tokens})
task: asyncio.Task[str] = asyncio.create_task(llm_worker.gen_text(llm_job=llm_job))
diff --git a/tests/integration/pipelex/cogt/test_llm_inference.py b/tests/integration/pipelex/cogt/test_llm_inference.py
index b8c4ea571..e2c67d874 100644
--- a/tests/integration/pipelex/cogt/test_llm_inference.py
+++ b/tests/integration/pipelex/cogt/test_llm_inference.py
@@ -15,20 +15,22 @@ from tests.integration.pipelex.cogt.test_data import ImageDescription, LLMTestCo
@pytest.mark.asyncio(loop_scope="class")
@pytest.mark.usefixtures("routing_profile_override")
class TestLLMInference:
- async def test_simple_gen_text_from_text(self, llm_job_params: LLMJobParams, llm_handle: str):
+ @pytest.mark.parametrize("user_text", [LLMTestConstants.USER_TEXT_SUPER_SHORT])
+ async def test_simple_gen_text_from_text(self, llm_job_params: LLMJobParams, llm_handle: str, user_text: str):
log.info(f"test_simple_gen_text_from_text: Testing llm_handle '{llm_handle}'")
llm_worker = get_inference_manager().get_llm_worker(llm_handle=llm_handle)
log.info(f"Using llm_worker: {llm_worker.desc}")
llm_job = LLMJobFactory.make_llm_job(
llm_prompt=LLMPrompt(
system_text=None,
- user_text=LLMTestConstants.USER_TEXT_SHORT,
+ user_text=user_text,
),
llm_job_params=llm_job_params,
)
generated_text = await llm_worker.gen_text(llm_job=llm_job)
assert generated_text
pretty_print(generated_text)
+ # get_report_delegate().generate_report()
async def test_simple_gen_object_from_text(self, llm_job_params: LLMJobParams, llm_handle: str):
log.info(f"test_simple_gen_object_from_text: Testing llm_handle '{llm_handle}'")
@@ -47,6 +49,7 @@ class TestLLMInference:
generated_object = await llm_worker.gen_object(llm_job=llm_job, schema=Person)
assert generated_object
pretty_print(generated_object)
+ # get_report_delegate().generate_report()
@pytest.mark.parametrize("image_path", [LLMVisionTestCases.PATH_IMG_PNG_1])
async def test_gen_text_from_image(self, llm_job_params: LLMJobParams, llm_handle: str, image_path: str):
@@ -60,7 +63,7 @@ class TestLLMInference:
llm_job = LLMJobFactory.make_llm_job(
llm_prompt=LLMPrompt(
- user_text=LLMVisionTestCases.VISION_USER_TEXT_2,
+ user_text=LLMVisionTestCases.VISION_USER_TEXT,
user_images=[prompt_image],
),
llm_job_params=llm_job_params,
@@ -71,6 +74,7 @@ class TestLLMInference:
pretty_print(generated_text, title=f"Vision of {image_path}")
except PromptImageFormatError as exc:
pytest.skip(f"Prompt Image format not supported for this LLM: {llm_handle} because {exc}")
+ # get_report_delegate().generate_report()
@pytest.mark.parametrize("image_path", [LLMVisionTestCases.PATH_IMG_PNG_1])
async def test_gen_object_from_image(self, llm_job_params: LLMJobParams, llm_handle: str, image_path: str):
@@ -104,3 +108,4 @@ class TestLLMInference:
pretty_print(generated_object, title=f"Image Description of {image_path}")
except PromptImageFormatError as exc:
pytest.skip(f"Prompt Image format not supported for this LLM: {llm_handle} because {exc}")
+ # get_report_delegate().generate_report()
diff --git a/tests/integration/pipelex/cogt/test_llm_report.py b/tests/integration/pipelex/cogt/test_llm_report.py
index 2350a0d7a..fbe74ced7 100644
--- a/tests/integration/pipelex/cogt/test_llm_report.py
+++ b/tests/integration/pipelex/cogt/test_llm_report.py
@@ -10,7 +10,6 @@ from pipelex.hub import get_llm_worker, get_model_deck, get_report_delegate
from tests.integration.pipelex.cogt.test_data import LLMTestCases
def test_llm_report_without_running_anything():
get_report_delegate().generate_report()
@@ -37,7 +36,6 @@ class TestLLMReport:
user_text=prompt_text,
),
llm_job_config=LLMJobConfig(
- is_streaming_enabled=False,
max_retries=3,
),
llm_job_params=llm_job_params,
diff --git a/tests/integration/pipelex/cogt/test_llm_vision.py b/tests/integration/pipelex/cogt/test_llm_vision.py
index d2798cfdd..7b4f95601 100644
--- a/tests/integration/pipelex/cogt/test_llm_vision.py
+++ b/tests/integration/pipelex/cogt/test_llm_vision.py
@@ -18,16 +18,16 @@ from tests.integration.pipelex.cogt.test_data import LLMVisionTestCases
@pytest.mark.usefixtures("routing_profile_override")
class TestLLMVision:
@pytest.mark.parametrize(("topic", "image_uri"), LLMVisionTestCases.IMAGE_URLS)
- async def test_gen_text_from_vision_by_url(self, llm_handle_for_vision: str, topic: str, image_uri: str):
+ async def test_gen_text_from_vision_by_url(self, llm_job_params: LLMJobParams, llm_handle: str, topic: str, image_uri: str):
prompt_image = PromptImageFactory.make_prompt_image(url=image_uri)
- llm_worker = get_llm_worker(llm_handle=llm_handle_for_vision)
+ llm_worker = get_llm_worker(llm_handle=llm_handle)
log.info(f"Using llm_worker: {llm_worker.desc}")
llm_job = LLMJobFactory.make_llm_job(
llm_prompt=LLMPrompt(
- user_text=LLMVisionTestCases.VISION_USER_TEXT_2,
+ user_text=LLMVisionTestCases.VISION_USER_TEXT,
user_images=[prompt_image],
),
- llm_job_params=LLMJobParams(temperature=0.5, max_tokens=1000, seed=None),
+ llm_job_params=llm_job_params,
)
try:
@@ -35,68 +35,68 @@ class TestLLMVision:
assert generated_text
pretty_print(generated_text, title=f"Vision of {topic}")
except LLMCapabilityError as exc:
- pytest.skip(f"Vision capability not supported for this LLM: {llm_handle_for_vision} because {exc}")
+ pytest.skip(f"Vision capability not supported for this LLM: {llm_handle} because {exc}")
except PromptImageFormatError as exc:
- pytest.skip(f"Prompt Image format not supported for this LLM: {llm_handle_for_vision} because {exc}")
+ pytest.skip(f"Prompt Image format not supported for this LLM: {llm_handle} because {exc}")
@pytest.mark.parametrize(("topic", "image_path"), LLMVisionTestCases.IMAGE_PATHS)
- async def test_gen_text_from_vision_by_bytes(self, llm_handle_for_vision: str, topic: str, image_path: str):
+ async def test_gen_text_from_vision_by_bytes(self, llm_job_params: LLMJobParams, llm_handle: str, topic: str, image_path: str):
image_bytes = load_binary_as_base64(path=image_path)
prompt_image = PromptImageBase64(base_64=image_bytes)
- llm_worker = get_llm_worker(llm_handle=llm_handle_for_vision)
+ llm_worker = get_llm_worker(llm_handle=llm_handle)
llm_job = LLMJobFactory.make_llm_job(
llm_prompt=LLMPrompt(
- user_text=LLMVisionTestCases.VISION_USER_TEXT_2,
+ user_text=LLMVisionTestCases.VISION_USER_TEXT,
user_images=[prompt_image],
),
- llm_job_params=LLMJobParams(temperature=0.5, max_tokens=1000, seed=None),
+ llm_job_params=llm_job_params,
)
try:
generated_text = await llm_worker.gen_text(llm_job=llm_job)
assert generated_text
pretty_print(generated_text, title=f"Vision of {topic}")
except LLMCapabilityError as exc:
- pytest.skip(f"Vision capability not supported for this LLM: {llm_handle_for_vision} because {exc}")
+ pytest.skip(f"Vision capability not supported for this LLM: {llm_handle} because {exc}")
except PromptImageFormatError as exc:
- pytest.skip(f"Prompt Image format not supported for this LLM: {llm_handle_for_vision} because {exc}")
+ pytest.skip(f"Prompt Image format not supported for this LLM: {llm_handle} because {exc}")
@pytest.mark.parametrize(("topic", "image_path"), LLMVisionTestCases.IMAGE_PATHS)
- async def test_gen_text_from_vision_by_path(self, llm_handle_for_vision: str, topic: str, image_path: str):
+ async def test_gen_text_from_vision_by_path(self, llm_job_params: LLMJobParams, llm_handle: str, topic: str, image_path: str):
prompt_image = PromptImagePath(file_path=image_path)
- llm_worker = get_llm_worker(llm_handle=llm_handle_for_vision)
+ llm_worker = get_llm_worker(llm_handle=llm_handle)
llm_job = LLMJobFactory.make_llm_job(
llm_prompt=LLMPrompt(
- user_text=LLMVisionTestCases.VISION_USER_TEXT_2,
+ user_text=LLMVisionTestCases.VISION_USER_TEXT,
user_images=[prompt_image],
),
- llm_job_params=LLMJobParams(temperature=0.5, max_tokens=1000, seed=None),
+ llm_job_params=llm_job_params,
)
try:
generated_text = await llm_worker.gen_text(llm_job=llm_job)
assert generated_text
pretty_print(generated_text, title=f"Vision of {topic}")
except LLMCapabilityError as exc:
- pytest.skip(f"Vision capability not supported for this LLM: {llm_handle_for_vision} because {exc}")
+ pytest.skip(f"Vision capability not supported for this LLM: {llm_handle} because {exc}")
except PromptImageFormatError as exc:
- pytest.skip(f"Prompt Image format not supported for this LLM: {llm_handle_for_vision} because {exc}")
+ pytest.skip(f"Prompt Image format not supported for this LLM: {llm_handle} because {exc}")
@pytest.mark.parametrize(("topic", "image_pair"), LLMVisionTestCases.IMAGE_PATH_PAIRS)
- async def test_gen_text_from_vision_2_images(self, llm_handle_for_vision: str, topic: str, image_pair: tuple[str, str]):
+ async def test_gen_text_from_vision_2_images(self, llm_job_params: LLMJobParams, llm_handle: str, topic: str, image_pair: tuple[str, str]):
prompt_image1 = PromptImagePath(file_path=image_pair[0])
prompt_image2 = PromptImagePath(file_path=image_pair[1])
- llm_worker = get_llm_worker(llm_handle=llm_handle_for_vision)
+ llm_worker = get_llm_worker(llm_handle=llm_handle)
llm_job = LLMJobFactory.make_llm_job(
llm_prompt=LLMPrompt(
user_text=LLMVisionTestCases.VISION_IMAGES_COMPARE_PROMPT,
user_images=[prompt_image1, prompt_image2],
),
- llm_job_params=LLMJobParams(temperature=0.5, max_tokens=2000, seed=None),
+ llm_job_params=llm_job_params,
)
try:
generated_text = await llm_worker.gen_text(llm_job=llm_job)
assert generated_text
pretty_print(generated_text, title=f"Comparative vision of {topic}")
except LLMCapabilityError as exc:
- pytest.skip(f"Vision capability not supported for this LLM: {llm_handle_for_vision} because {exc}")
+ pytest.skip(f"Vision capability not supported for this LLM: {llm_handle} because {exc}")
except PromptImageFormatError as exc:
- pytest.skip(f"Prompt Image format not supported for this LLM: {llm_handle_for_vision} because {exc}")
+ pytest.skip(f"Prompt Image format not supported for this LLM: {llm_handle} because {exc}")
diff --git a/tests/integration/pipelex/conftest.py b/tests/integration/pipelex/conftest.py
index 3c8020bd6..91b3aa74c 100644
--- a/tests/integration/pipelex/conftest.py
+++ b/tests/integration/pipelex/conftest.py
@@ -15,8 +15,8 @@ from .fixtures.extract_fixtures import (
extract_handle_from_image,
)
from .fixtures.img_gen_fixtures import img_gen_handle
-from .fixtures.llm_fixtures import llm_handle, llm_handle_for_vision, llm_job_params, llm_preset_id
-from .fixtures.plugin_fixtures import openai_endpoint, plugin_for_anthropic, plugin_for_openai
+from .fixtures.llm_fixtures import llm_handle, llm_job_params, llm_preset_id
+from .fixtures.plugin_fixtures import plugin_for_anthropic, plugin_for_openai
from .fixtures.routing_fixtures import (
check_backend_supports_model,
extract_backend_from_profile_name_if_possible,
@@ -33,12 +33,10 @@ __all__ = [
# LLM fixtures
"llm_preset_id",
"llm_handle",
- "llm_handle_for_vision",
"llm_job_params",
# Plugin fixtures
"plugin_for_openai",
"plugin_for_anthropic",
- "openai_endpoint",
# Image generation fixtures
"img_gen_handle",
# Extract fixtures
diff --git a/tests/integration/pipelex/fixtures/llm_fixtures.py b/tests/integration/pipelex/fixtures/llm_fixtures.py
index e8f76b086..505bd354d 100644
--- a/tests/integration/pipelex/fixtures/llm_fixtures.py
+++ b/tests/integration/pipelex/fixtures/llm_fixtures.py
@@ -3,6 +3,7 @@
import pytest
from pipelex import log
+from pipelex.cogt.image.prompt_image import PromptImageDetail
from pipelex.cogt.llm.llm_job_components import LLMJobParams
from pipelex.hub import get_model_deck
from tests.integration.pipelex.fixtures.routing_fixtures import ALL_BACKENDS, check_backend_supports_model
@@ -54,8 +55,6 @@ AMAZON_MODELS = [
ANTHROPIC_MODELS = [
"claude-3-haiku",
"claude-3-opus",
- "claude-3.5-haiku",
- "claude-3.5-sonnet",
"claude-3.7-sonnet",
"claude-4-opus",
"claude-4-sonnet",
@@ -68,17 +67,19 @@ ANTHROPIC_MODELS = [
# --- DeepSeek Models ----------------------------------------------------------------------------
DEEPSEEK_MODELS = [
- "deepseek-chat-free",
- "deepseek-r1-free",
+ "deepseek-chat",
+ "deepseek-r1",
+ "deepseek-v3.1",
+ "deepseek-r1-distill-llama-70b",
]
# --- Google Models (Gemini) ---------------------------------------------------------------------
GOOGLE_MODELS = [
+ "gemini-flash-1.5-8b",
"gemini-2.0-flash",
"gemini-2.5-flash",
"gemini-2.5-flash-lite",
"gemini-2.5-pro",
- "gemini-flash-1.5-8b",
"gemini-3.0-pro",
]
@@ -92,6 +93,7 @@ GROQ_MODELS = [
META_MODELS = [
"bedrock-meta-llama-3-3-70b-instruct",
"llama-3.1-8b-instant",
+ "llama-3.1-8b-instruct",
"llama-3.2-11b-vision-instruct",
"llama-3.3-70b-instruct",
"llama-3.3-70b-instruct-free",
@@ -101,7 +103,7 @@ META_MODELS = [
]
# --- Mistral Models -----------------------------------------------------------------------------
-MISTRAL_MODELS = [
+MISTRALAI_MODELS = [
"bedrock-mistral-large",
"ministral-3b",
"ministral-8b",
@@ -120,51 +122,57 @@ MISTRAL_MODELS = [
]
# --- Moonshot AI Models -------------------------------------------------------------------------
-MOONSHOT_MODELS = [
- "moonshotai/kimi-k2-instruct-0905",
+MOONSHOTAI_MODELS = [
+ "kimi-k2-instruct-0905",
]
# --- OpenAI Models ------------------------------------------------------------------------------
OPENAI_MODELS = [
- "gpt-3.5-turbo",
- "gpt-4",
- "gpt-4-turbo",
- "gpt-4.1",
- "gpt-4.1-mini",
- "gpt-4.1-nano",
- "gpt-4o",
- "gpt-4o-2024-11-20",
"gpt-4o-mini",
- "gpt-4o-mini-2024-07-18",
- "gpt-5",
- "gpt-5-chat",
- "gpt-5-mini",
- "gpt-5-nano",
- "gpt-5.1",
- "gpt-5.1-chat",
- "o1",
+ "gpt-4o",
+ "gpt-4.1-nano",
+ "gpt-4.1-mini",
+ "gpt-4.1",
"o1-mini",
- "o3",
+ "o1",
"o3-mini",
+ "o3",
"o4-mini",
- "openai/gpt-oss-120b",
- "openai/gpt-oss-20b",
- "openai/gpt-oss-safeguard-20b",
+ "gpt-5-nano",
+ "gpt-5-mini",
+ "gpt-5-chat",
+ "gpt-5",
+ "gpt-5.1-chat",
+ "gpt-5.1",
+ "gpt-5.1-codex",
+]
+
+# --- OpenAI OSS Models --------------------------------------------------------------------------
+OPENAI_OSS_MODELS = [
+ "gpt-oss-20b",
+ "gpt-oss-120b",
+ "gpt-oss-safeguard-20b",
]
# --- Qwen Models --------------------------------------------------------------------------------
QWEN_MODELS = [
"qwen-2.5-72b-instruct",
- "qwen/qwen3-32b",
+ "qwen3-32b",
"qwen2.5-vl-72b-instruct",
+ "qwen3-vl-235b-a22b",
+ "qwen3-235b-a22b-instruct-2507",
+ "qwen3-coder-30b-a3b-instruct",
]
# --- XAI Models (Grok) --------------------------------------------------------------------------
XAI_MODELS = [
"grok-3",
- "grok-3-fast",
"grok-3-mini",
+ "grok-4",
+ "grok-3-fast",
"grok-3-mini-fast",
+ "grok-4-fast-reasoning",
+ "grok-4-fast-non-reasoning",
]
# --- All LLM Handles ----------------------------------------------------------------------------
@@ -175,9 +183,10 @@ ALL_LLM_HANDLES = [
*GOOGLE_MODELS,
*GROQ_MODELS,
*META_MODELS,
- *MISTRAL_MODELS,
- *MOONSHOT_MODELS,
+ *MISTRALAI_MODELS,
+ *MOONSHOTAI_MODELS,
*OPENAI_MODELS,
+ *OPENAI_OSS_MODELS,
*QWEN_MODELS,
*XAI_MODELS,
]
@@ -188,6 +197,7 @@ ALL_LLM_HANDLES = [
LLMJobParams(
temperature=0.5,
max_tokens=None,
+ image_detail=PromptImageDetail.AUTO,
seed=None,
),
],
diff --git a/tests/integration/pipelex/fixtures/plugin_fixtures.py b/tests/integration/pipelex/fixtures/plugin_fixtures.py
index 3e3d63159..5a89d56e7 100644
--- a/tests/integration/pipelex/fixtures/plugin_fixtures.py
+++ b/tests/integration/pipelex/fixtures/plugin_fixtures.py
@@ -25,14 +25,3 @@ def plugin_for_openai(request: pytest.FixtureRequest) -> Plugin:
def plugin_for_anthropic(request: pytest.FixtureRequest) -> Plugin:
assert isinstance(request.param, Plugin)
return request.param
-
-
- params=[
- # None,
- "https://inference.pipelex.com/v1",
- ],
-)
-def openai_endpoint(request: pytest.FixtureRequest) -> str | None:
- assert isinstance(request.param, str) or request.param is None
- return request.param
diff --git a/tests/integration/pipelex/fixtures/routing_fixtures.py b/tests/integration/pipelex/fixtures/routing_fixtures.py
index ddbda05d8..e2b8777a9 100644
--- a/tests/integration/pipelex/fixtures/routing_fixtures.py
+++ b/tests/integration/pipelex/fixtures/routing_fixtures.py
@@ -17,6 +17,7 @@ from pipelex.tools.misc.toml_utils import load_toml_from_path, load_toml_with_to
# ================================================================================================
ALL_BACKENDS = [
+ "pipelex_gateway",
"anthropic",
"azure_openai",
"bedrock",
@@ -27,9 +28,11 @@ ALL_BACKENDS = [
"mistral",
"ollama",
"openai",
- "pipelex_inference",
+ "portkey",
+ "scaleway",
"vertexai",
"xai",
+ "internal",
]
@@ -40,6 +43,7 @@ def get_all_routing_profiles() -> list[str]:
# Get all profiles starting with 'all_'
all_profiles = [profile_name for profile_name in profiles if profile_name.startswith("all_")]
+ # all_profiles.append()
# Filter to only include profiles for enabled backends
enabled_profiles: list[str] = []
@@ -48,7 +52,7 @@ def get_all_routing_profiles() -> list[str]:
if backend_name and backend_name in ALL_BACKENDS:
enabled_profiles.append(profile_name)
- return sorted(enabled_profiles) or ["pipelex_first"]
+ return sorted(enabled_profiles)
def extract_backend_from_profile_name_if_possible(profile_name: str) -> str | None:
diff --git a/tests/integration/pipelex/pipes/controller/pipe_batch/test_pipe_batch_simple.py b/tests/integration/pipelex/pipes/controller/pipe_batch/test_pipe_batch_simple.py
index 8c1d8f942..0b7b5bcbf 100644
--- a/tests/integration/pipelex/pipes/controller/pipe_batch/test_pipe_batch_simple.py
+++ b/tests/integration/pipelex/pipes/controller/pipe_batch/test_pipe_batch_simple.py
@@ -2,7 +2,6 @@ from pathlib import Path
from typing import Callable, cast
import pytest
-from pytest import FixtureRequest
from pipelex import pretty_print
from pipelex.core.concepts.concept_blueprint import ConceptBlueprint
@@ -30,7 +29,6 @@ class TestPipeBatchSimple:
async def test_simple_batch_processing(
self,
- request: FixtureRequest,
pipe_run_mode: PipeRunMode,
load_test_library: Callable[[list[Path]], None],
):
@@ -107,7 +105,7 @@ class TestPipeBatchSimple:
# Actually run the PipeBatch pipe
pipe_output = await pipe_batch.run_pipe( # pyright: ignore[reportPrivateUsage]
- job_metadata=JobMetadata(job_name=cast("str", request.node.originalname)), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
working_memory=working_memory,
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
output_name="batch_result",
diff --git a/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_complex.py b/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_complex.py
index 168b19211..94311457e 100644
--- a/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_complex.py
+++ b/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_complex.py
@@ -2,10 +2,9 @@
from collections.abc import Callable
from pathlib import Path
-from typing import Literal, cast
+from typing import Literal
import pytest
-from pytest import FixtureRequest
from pipelex import pretty_print
from pipelex.core.concepts.concept_factory import ConceptFactory
@@ -29,9 +28,7 @@ from tests.integration.pipelex.pipes.controller.pipe_condition.pipe_condition_co
@pytest.mark.llm
@pytest.mark.asyncio(loop_scope="class")
class TestPipeConditionComplex:
- async def test_technical_urgent_routing(
- self, request: FixtureRequest, pipe_run_mode: PipeRunMode, load_test_library: Callable[[list[Path]], None]
- ):
+ async def test_technical_urgent_routing(self, pipe_run_mode: PipeRunMode, load_test_library: Callable[[list[Path]], None]):
"""Test technical document with urgent priority routing."""
load_test_library([Path("tests/integration/pipelex/pipes/controller/pipe_condition")])
# Create complex input data
@@ -67,7 +64,7 @@ class TestPipeConditionComplex:
pipe=get_required_pipe(pipe_code="complex_document_processor"),
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
working_memory=working_memory,
- job_metadata=JobMetadata(job_name=cast("str", request.node.originalname)), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
),
)
@@ -82,9 +79,7 @@ class TestPipeConditionComplex:
if pipe_run_mode != PipeRunMode.DRY:
assert "URGENT_TECHNICAL_PROCESSED" in final_result.content.text
- async def test_business_finance_routing(
- self, request: FixtureRequest, pipe_run_mode: PipeRunMode, load_test_library: Callable[[list[Path]], None]
- ):
+ async def test_business_finance_routing(self, pipe_run_mode: PipeRunMode, load_test_library: Callable[[list[Path]], None]):
"""Test business document for finance department routing."""
load_test_library([Path("tests/integration/pipelex/pipes/controller/pipe_condition")])
doc_request = DocumentRequest(document_type="business", priority="normal", language="english", complexity="medium")
@@ -118,7 +113,7 @@ class TestPipeConditionComplex:
pipe=get_required_pipe(pipe_code="complex_document_processor"),
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
working_memory=working_memory,
- job_metadata=JobMetadata(job_name=cast("str", request.node.originalname)), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
),
)
@@ -130,7 +125,7 @@ class TestPipeConditionComplex:
assert isinstance(final_result.content, TextContent)
assert "FINANCE_BUSINESS_PROCESSED" in final_result.content.text
- async def test_legal_complex_routing(self, request: FixtureRequest, pipe_run_mode: PipeRunMode, load_test_library: Callable[[list[Path]], None]):
+ async def test_legal_complex_routing(self, pipe_run_mode: PipeRunMode, load_test_library: Callable[[list[Path]], None]):
"""Test complex legal document routing."""
load_test_library([Path("tests/integration/pipelex/pipes/controller/pipe_condition")])
doc_request = DocumentRequest(document_type="legal", priority="normal", language="spanish", complexity="high")
@@ -164,7 +159,7 @@ class TestPipeConditionComplex:
pipe=get_required_pipe(pipe_code="complex_document_processor"),
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
working_memory=working_memory,
- job_metadata=JobMetadata(job_name=cast("str", request.node.originalname)), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
),
)
@@ -176,9 +171,7 @@ class TestPipeConditionComplex:
assert isinstance(final_result.content, TextContent)
assert "COMPLEX_LEGAL_PROCESSED" in final_result.content.text
- async def test_technical_expert_high_complexity_routing(
- self, request: FixtureRequest, pipe_run_mode: PipeRunMode, load_test_library: Callable[[list[Path]], None]
- ):
+ async def test_technical_expert_high_complexity_routing(self, pipe_run_mode: PipeRunMode, load_test_library: Callable[[list[Path]], None]):
"""Test technical document with expert user and high complexity."""
load_test_library([Path("tests/integration/pipelex/pipes/controller/pipe_condition")])
doc_request = DocumentRequest(
@@ -220,7 +213,7 @@ class TestPipeConditionComplex:
pipe=get_required_pipe(pipe_code="complex_document_processor"),
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
working_memory=working_memory,
- job_metadata=JobMetadata(job_name=cast("str", request.node.originalname)), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
),
)
@@ -233,7 +226,7 @@ class TestPipeConditionComplex:
assert "EXPERT_TECHNICAL_PROCESSED" in final_result.content.text
# DRY RUN TESTS
- async def test_complex_pipeline_dry_run_success(self, request: FixtureRequest, load_test_library: Callable[[list[Path]], None]):
+ async def test_complex_pipeline_dry_run_success(self, load_test_library: Callable[[list[Path]], None]):
"""Test complex pipeline dry run with valid inputs - should succeed."""
load_test_library([Path("tests/integration/pipelex/pipes/controller/pipe_condition")])
doc_request = DocumentRequest(document_type="business", priority="urgent", language="english", complexity="low")
@@ -267,7 +260,7 @@ class TestPipeConditionComplex:
pipe=get_required_pipe(pipe_code="complex_document_processor"),
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=PipeRunMode.DRY),
working_memory=working_memory,
- job_metadata=JobMetadata(job_name=cast("str", request.node.originalname)), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
),
)
@@ -276,7 +269,7 @@ class TestPipeConditionComplex:
assert pipe_output is not None
assert pipe_output.working_memory is not None
- async def test_complex_pipeline_dry_run_missing_inputs(self, request: FixtureRequest, load_test_library: Callable[[list[Path]], None]):
+ async def test_complex_pipeline_dry_run_missing_inputs(self, load_test_library: Callable[[list[Path]], None]):
"""Test complex pipeline dry run with missing inputs - should fail with PipeRouterError."""
load_test_library([Path("tests/integration/pipelex/pipes/controller/pipe_condition")])
doc_request = DocumentRequest(document_type="technical", priority="urgent", language="english", complexity="high")
@@ -300,7 +293,7 @@ class TestPipeConditionComplex:
pipe=get_required_pipe(pipe_code="complex_document_processor"),
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=PipeRunMode.DRY),
working_memory=working_memory,
- job_metadata=JobMetadata(job_name=cast("str", request.node.originalname)), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
),
)
@@ -334,7 +327,6 @@ class TestPipeConditionComplex:
complexity: Literal["low", "medium", "high"],
language: Literal["english", "spanish", "french", "german", "chinese"],
expected_output_contains: str,
- request: FixtureRequest,
pipe_run_mode: PipeRunMode,
load_test_library: Callable[[list[Path]], None],
):
@@ -378,7 +370,7 @@ class TestPipeConditionComplex:
pipe=get_required_pipe(pipe_code="complex_document_processor"),
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
working_memory=working_memory,
- job_metadata=JobMetadata(job_name=cast("str", request.node.originalname)), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
),
)
diff --git a/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_simple.py b/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_simple.py
index 3962a34e7..7acbe3202 100644
--- a/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_simple.py
+++ b/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_simple.py
@@ -1,8 +1,7 @@
from pathlib import Path
-from typing import Callable, cast
+from typing import Callable
import pytest
-from pytest import FixtureRequest
from pipelex import pretty_print
from pipelex.core.concepts.concept_factory import ConceptFactory
@@ -28,9 +27,7 @@ from tests.integration.pipelex.pipes.controller.pipe_condition.pipe_condition im
@pytest.mark.inference
@pytest.mark.asyncio(loop_scope="class")
class TestPipeConditionSimple:
- async def test_condition_long_text_processing(
- self, request: FixtureRequest, pipe_run_mode: PipeRunMode, load_test_library: Callable[[list[Path]], None]
- ):
+ async def test_condition_long_text_processing(self, pipe_run_mode: PipeRunMode, load_test_library: Callable[[list[Path]], None]):
"""Test PipeCondition with long text that should trigger capitalize_long_text pipe."""
load_test_library([Path("tests/integration/pipelex/pipes/controller/pipe_condition")])
pipe_condition_blueprint = PipeConditionBlueprint(
@@ -65,7 +62,7 @@ class TestPipeConditionSimple:
assert input_text.content.text == "hello world"
pipe_output = await pipe_condition.run_pipe(
- job_metadata=JobMetadata(job_name=cast("str", request.node.originalname)), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
working_memory=working_memory,
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
)
@@ -100,9 +97,7 @@ class TestPipeConditionSimple:
assert final_result_in_memory.content.text == "LONG: HELLO WORLD"
assert f"{final_result_in_memory.concept.domain}.{final_result_in_memory.concept.code}" == f"{SpecialDomain.NATIVE}.{NativeConceptCode.TEXT}"
- async def test_condition_short_text_processing(
- self, request: FixtureRequest, pipe_run_mode: PipeRunMode, load_test_library: Callable[[list[Path]], None]
- ):
+ async def test_condition_short_text_processing(self, pipe_run_mode: PipeRunMode, load_test_library: Callable[[list[Path]], None]):
"""Test PipeCondition with short text that should trigger add_prefix_short_text pipe."""
load_test_library([Path("tests/integration/pipelex/pipes/controller/pipe_condition")])
# Create PipeCondition instance - pipes are loaded from PLX files
@@ -138,7 +133,7 @@ class TestPipeConditionSimple:
# Actually run the PipeCondition pipe
pipe_output = await pipe_condition.run_pipe(
- job_metadata=JobMetadata(job_name=cast("str", request.node.originalname)), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
working_memory=working_memory,
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
)
@@ -173,7 +168,7 @@ class TestPipeConditionSimple:
assert final_result_in_memory.content.text == "SHORT: hi"
assert f"{final_result_in_memory.concept.domain}.{final_result_in_memory.concept.code}" == f"{SpecialDomain.NATIVE}.{NativeConceptCode.TEXT}"
- async def test_condition_dry_run_success(self, request: FixtureRequest, load_test_library: Callable[[list[Path]], None]):
+ async def test_condition_dry_run_success(self, load_test_library: Callable[[list[Path]], None]):
"""Test PipeCondition dry run with valid inputs using real pipe - should succeed."""
load_test_library([Path("tests/integration/pipelex/pipes/controller/pipe_condition")])
# Create test data using CategoryInput for the real pipe basic_condition_by_category_2
@@ -197,7 +192,7 @@ class TestPipeConditionSimple:
pipe=get_required_pipe(pipe_code="basic_condition_by_category_2"),
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=PipeRunMode.DRY),
working_memory=working_memory,
- job_metadata=JobMetadata(job_name=cast("str", request.node.originalname)), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
),
)
pretty_print(pipe_output)
@@ -220,7 +215,7 @@ class TestPipeConditionSimple:
assert isinstance(original_input.content, CategoryInput)
assert original_input.content.category == "small"
- async def test_condition_dry_run_missing_inputs_failure(self, request: FixtureRequest, load_test_library: Callable[[list[Path]], None]):
+ async def test_condition_dry_run_missing_inputs_failure(self, load_test_library: Callable[[list[Path]], None]):
"""Test PipeCondition dry run with missing inputs using real pipe - should fail with PipeRouterError."""
load_test_library([Path("tests/integration/pipelex/pipes/controller/pipe_condition")])
# Create empty working memory - missing required input
@@ -233,7 +228,7 @@ class TestPipeConditionSimple:
pipe=get_required_pipe(pipe_code="basic_condition_by_category_2"),
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=PipeRunMode.DRY),
working_memory=empty_working_memory,
- job_metadata=JobMetadata(job_name=cast("str", request.node.originalname)), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
),
)
@@ -244,7 +239,7 @@ class TestPipeConditionSimple:
assert "input_data" in error.missing_inputs
assert "Missing required inputs" in str(error)
- async def test_condition_dry_run_medium_category_validation(self, request: FixtureRequest, load_test_library: Callable[[list[Path]], None]):
+ async def test_condition_dry_run_medium_category_validation(self, load_test_library: Callable[[list[Path]], None]):
"""Test PipeCondition dry run with medium category - should validate the 'medium' branch."""
load_test_library([Path("tests/integration/pipelex/pipes/controller/pipe_condition")])
# Create test data using CategoryInput for the medium category
@@ -268,7 +263,7 @@ class TestPipeConditionSimple:
pipe=get_required_pipe(pipe_code="basic_condition_by_category_2"),
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=PipeRunMode.DRY),
working_memory=working_memory,
- job_metadata=JobMetadata(job_name=cast("str", request.node.originalname)), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
),
)
diff --git a/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_simple.py b/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_simple.py
index 500a54db7..8a4af75b8 100644
--- a/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_simple.py
+++ b/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_simple.py
@@ -1,8 +1,7 @@
from pathlib import Path
-from typing import Callable, cast
+from typing import Callable
import pytest
-from pytest import FixtureRequest
from pipelex.core.concepts.concept_factory import ConceptFactory
from pipelex.core.concepts.native.concept_native import NativeConceptCode
@@ -23,7 +22,7 @@ from pipelex.pipeline.job_metadata import JobMetadata
@pytest.mark.inference
@pytest.mark.asyncio(loop_scope="class")
class TestPipeParallelSimple:
- async def test_parallel_text_analysis(self, request: FixtureRequest, pipe_run_mode: PipeRunMode, load_test_library: Callable[[list[Path]], None]):
+ async def test_parallel_text_analysis(self, pipe_run_mode: PipeRunMode, load_test_library: Callable[[list[Path]], None]):
"""Test PipeParallel running three text analysis pipes in parallel."""
load_test_library([Path("tests/integration/pipelex/pipes/controller/pipe_parallel")])
# Create PipeParallel instance - pipes are loaded from PLX files
@@ -78,7 +77,7 @@ class TestPipeParallelSimple:
# Actually run the PipeParallel pipe
pipe_output = await pipe_parallel.run_pipe(
- job_metadata=JobMetadata(job_name=cast("str", request.node.originalname)), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
working_memory=working_memory,
output_name="parallel_results",
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
@@ -140,9 +139,7 @@ class TestPipeParallelSimple:
assert isinstance(final_result.content, TextContent)
assert final_result.content.text == "The weather is beautiful today. I love sunny days and outdoor activities."
- async def test_parallel_short_text_analysis(
- self, request: FixtureRequest, pipe_run_mode: PipeRunMode, load_test_library: Callable[[list[Path]], None]
- ):
+ async def test_parallel_short_text_analysis(self, pipe_run_mode: PipeRunMode, load_test_library: Callable[[list[Path]], None]):
"""Test PipeParallel with shorter text to verify consistent behavior."""
load_test_library([Path("tests/integration/pipelex/pipes/controller/pipe_parallel")])
# Create PipeParallel instance
@@ -175,7 +172,7 @@ class TestPipeParallelSimple:
# Actually run the PipeParallel pipe
pipe_output = await pipe_parallel.run_pipe(
- job_metadata=JobMetadata(job_name=cast("str", request.node.originalname)), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
working_memory=working_memory,
output_name="parallel_results",
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
diff --git a/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_dry_run.py b/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_dry_run.py
index 06299143e..196c1b6e2 100644
--- a/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_dry_run.py
+++ b/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_dry_run.py
@@ -2,7 +2,6 @@ from pathlib import Path
from typing import TYPE_CHECKING, Callable
import pytest
-from pytest import FixtureRequest
from pipelex import log, pretty_print
from pipelex.core.concepts.concept_factory import ConceptFactory
@@ -29,7 +28,6 @@ if TYPE_CHECKING:
class TestPipeSequenceDryRun:
async def test_discord_newsletter_dry_run_working_memory(
self,
- request: FixtureRequest,
pipe_run_mode: PipeRunMode,
load_test_library: Callable[[list[Path]], None],
) -> None:
@@ -63,7 +61,7 @@ class TestPipeSequenceDryRun:
pipe=get_required_pipe(pipe_code="write_discord_newsletter"),
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
working_memory=working_memory,
- job_metadata=JobMetadata(job_name=request.node.originalname), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
),
)
diff --git a/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_simple.py b/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_simple.py
index 59f2640d1..8c362daaa 100644
--- a/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_simple.py
+++ b/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_simple.py
@@ -1,8 +1,7 @@
from pathlib import Path
-from typing import Callable, cast
+from typing import Callable
import pytest
-from pytest import FixtureRequest
from pipelex import pretty_print
from pipelex.core.concepts.concept_blueprint import ConceptBlueprint
@@ -27,9 +26,7 @@ from pipelex.pipeline.job_metadata import JobMetadata
class TestPipeSequenceSimple:
"""Simple integration test for PipeSequence controller."""
- async def test_simple_sequence_processing(
- self, request: FixtureRequest, pipe_run_mode: PipeRunMode, load_test_library: Callable[[list[Path]], None]
- ):
+ async def test_simple_sequence_processing(self, pipe_run_mode: PipeRunMode, load_test_library: Callable[[list[Path]], None]):
"""Test PipeSequence with a simple 2-step text transformation scenario."""
load_test_library([Path("tests/integration/pipelex/pipes/controller/pipe_sequence")])
domain = "test_integration"
@@ -91,7 +88,7 @@ class TestPipeSequenceSimple:
# Actually run the PipeSequence pipe
pipe_output = await pipe_sequence.run_pipe(
- job_metadata=JobMetadata(job_name=cast("str", request.node.originalname)), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
working_memory=working_memory,
output_name="sequence_result",
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
diff --git a/tests/integration/pipelex/pipes/test_image_inputs.py b/tests/integration/pipelex/pipes/test_image_inputs.py
index 98f49d684..29eb3ac4d 100644
--- a/tests/integration/pipelex/pipes/test_image_inputs.py
+++ b/tests/integration/pipelex/pipes/test_image_inputs.py
@@ -2,7 +2,6 @@ from pathlib import Path
from typing import Callable
import pytest
-from pytest import FixtureRequest
from pipelex.core.concepts.concept_factory import ConceptFactory
from pipelex.core.concepts.native.concept_native import NativeConceptCode
@@ -33,7 +32,6 @@ class TestImageInputs:
async def test_extract_article_from_image(
self,
- request: FixtureRequest,
pipe_run_mode: PipeRunMode,
load_test_library: Callable[[list[Path]], None],
) -> None:
@@ -41,7 +39,7 @@ class TestImageInputs:
working_memory = WorkingMemoryFactory.make_from_single_stuff(
stuff=StuffFactory.make_stuff(
concept=get_native_concept(NativeConceptCode.IMAGE),
- content=ImageContent(url=ImageTestCases.IMAGE_FILE_PATH_PNG),
+ content=ImageContent(url=ImageTestCases.IMAGE_FILE_PATH_PNG_1),
name="image",
),
)
@@ -51,7 +49,7 @@ class TestImageInputs:
pipe=get_required_pipe(pipe_code="extract_article_from_image"),
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
working_memory=working_memory,
- job_metadata=JobMetadata(job_name=request.node.originalname), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
),
)
if pipe_run_mode != PipeRunMode.DRY:
@@ -67,11 +65,11 @@ class TestImageInputs:
assert pipe_output.working_memory is not None
assert pipe_output.main_stuff is not None
- async def test_describe_page(self, request: FixtureRequest, pipe_run_mode: PipeRunMode, load_test_library: Callable[[list[Path]], None]) -> None:
+ async def test_describe_page(self, pipe_run_mode: PipeRunMode, load_test_library: Callable[[list[Path]], None]) -> None:
load_test_library([Path("tests/integration/pipelex/pipes/pipelines")])
# Create the page content
# image_content = ImageContent(url=ImageTestCases.IMAGE_FILE_PATH_PNG)
- image_content = ImageContent(url=f"file://{ImageTestCases.IMAGE_FILE_PATH_PNG}")
+ image_content = ImageContent(url=f"file://{ImageTestCases.IMAGE_FILE_PATH_PNG_1}")
text_and_images = TextAndImagesContent(text=TextContent(text="It was designed by Slartibartfast, a famous designer"), images=[])
page_content = PageContent(text_and_images=text_and_images, page_view=image_content)
@@ -91,7 +89,7 @@ class TestImageInputs:
pipe=get_required_pipe(pipe_code="describe_page"),
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
working_memory=working_memory,
- job_metadata=JobMetadata(job_name=request.node.originalname), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
),
)
diff --git a/tests/integration/pipelex/pipes/test_pipe_running_variants.py b/tests/integration/pipelex/pipes/test_pipe_running_variants.py
index 4ee7c5546..3ef537d63 100644
--- a/tests/integration/pipelex/pipes/test_pipe_running_variants.py
+++ b/tests/integration/pipelex/pipes/test_pipe_running_variants.py
@@ -2,7 +2,6 @@ from pathlib import Path
from typing import Callable
import pytest
-from pytest import FixtureRequest
from pipelex import log, pretty_print
from pipelex.core.memory.working_memory_factory import WorkingMemoryFactory
@@ -27,7 +26,6 @@ class TestPipeRunningVariants:
async def test_pipe_from_stuff(
self,
pipe_run_mode: PipeRunMode,
- request: FixtureRequest,
topic: str,
stuff: Stuff,
pipe_code: str,
@@ -41,7 +39,7 @@ class TestPipeRunningVariants:
pipe=get_required_pipe(pipe_code=pipe_code),
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
working_memory=working_memory,
- job_metadata=JobMetadata(job_name=request.node.originalname), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
),
)
@@ -49,7 +47,6 @@ class TestPipeRunningVariants:
async def test_pipe_no_input(
self,
pipe_run_mode: PipeRunMode,
- request: FixtureRequest,
topic: str,
pipe_code: str,
load_test_library: Callable[[list[Path]], None],
@@ -61,7 +58,7 @@ class TestPipeRunningVariants:
pipe=get_required_pipe(pipe_code=pipe_code),
pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),
working_memory=WorkingMemoryFactory.make_empty(),
- job_metadata=JobMetadata(job_name=request.node.originalname), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
),
)
@@ -74,7 +71,6 @@ class TestPipeRunningVariants:
async def test_pipe_batch_no_input(
self,
pipe_run_mode: PipeRunMode,
- request: FixtureRequest,
topic: str,
pipe_code: str,
output_multiplicity: VariableMultiplicity | None,
@@ -89,7 +85,7 @@ class TestPipeRunningVariants:
pipe_run_mode=pipe_run_mode,
output_multiplicity=output_multiplicity,
),
- job_metadata=JobMetadata(job_name=request.node.originalname), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
working_memory=WorkingMemoryFactory.make_empty(),
),
)
@@ -103,7 +99,6 @@ class TestPipeRunningVariants:
async def test_pipe_infinite_loop(
self,
pipe_run_mode: PipeRunMode,
- request: FixtureRequest,
pipe_code: str,
exception: type[Exception],
expected_error_message: str,
@@ -119,7 +114,7 @@ class TestPipeRunningVariants:
pipe_stack_limit=6,
pipe_run_mode=pipe_run_mode,
),
- job_metadata=JobMetadata(job_name=request.node.originalname), # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
+ job_metadata=JobMetadata(),
),
)
pretty_print(exc.value, title="exception")
diff --git a/tests/integration/pipelex/plugins/test_external_plugin.py b/tests/integration/pipelex/plugins/test_external_plugin.py
index de1242213..de2426434 100644
--- a/tests/integration/pipelex/plugins/test_external_plugin.py
+++ b/tests/integration/pipelex/plugins/test_external_plugin.py
@@ -79,6 +79,7 @@ class TestExternalPlugin:
llm_job_params=LLMJobParams(
temperature=0.5,
max_tokens=None,
+ image_detail=None,
seed=None,
),
)
diff --git a/tests/integration/pipelex/plugins/test_openai_image_gen.py b/tests/integration/pipelex/plugins/test_openai_image_gen.py
index 539c9a5d1..335585d72 100644
--- a/tests/integration/pipelex/plugins/test_openai_image_gen.py
+++ b/tests/integration/pipelex/plugins/test_openai_image_gen.py
@@ -2,7 +2,7 @@ import pytest
from pipelex.cogt.exceptions import ImgGenGenerationError
from pipelex.hub import get_models_manager
-from pipelex.plugins.openai.openai_factory import OpenAIFactory
+from pipelex.plugins.openai.openai_client_factory import OpenAIClientFactory
from pipelex.plugins.plugin_sdk_registry import Plugin
from pipelex.tools.misc.base_64_utils import save_base_64_str_to_binary_file
from pipelex.tools.misc.file_utils import ensure_path, get_incremental_file_path
@@ -20,7 +20,7 @@ class TestImgGenByOpenAIGpt:
if not is_backend_available("openai"):
pytest.skip("Backend 'openai' is not available or enabled")
backend = get_models_manager().get_required_inference_backend("openai")
- client = OpenAIFactory.make_openai_client(
+ client = OpenAIClientFactory.make_openai_client(
Plugin(sdk="openai", backend="openai"),
backend=backend,
)
diff --git a/tests/integration/pipelex/test_data.py b/tests/integration/pipelex/test_data.py
index 8018cd127..2389d8c6b 100644
--- a/tests/integration/pipelex/test_data.py
+++ b/tests/integration/pipelex/test_data.py
@@ -41,7 +41,7 @@ class PipeTestCases:
The moon is white.
"""
MULTI_IMG_DESC_PROMPT = "If there is one image, describe it. If there are multiple images, compare them."
- URL_IMG_GANTT_1 = "https://storage.googleapis.com/public_test_files_7fa6_4277_9ab/diagrams/gantt_tree_house.png" # AI generated
+ URL_IMG_GANTT_PNG = "https://pipelex-web.s3.amazonaws.com/tests/gantt_tree_house.png" # AI generated
URL_IMG_FASHION_PHOTO_1 = "https://storage.googleapis.com/public_test_files_7fa6_4277_9ab/fashion/fashion_photo_1.jpg" # AI generated
URL_IMG_FASHION_PHOTO_2 = "https://storage.googleapis.com/public_test_files_7fa6_4277_9ab/fashion/fashion_photo_2.png" # AI generated
@@ -67,7 +67,7 @@ class PipeTestCases:
content=ListContent(
items=[
TextContent(text="The quick brown fox jumps over the lazy dog"),
- ImageContent(url=URL_IMG_GANTT_1),
+ ImageContent(url=URL_IMG_GANTT_PNG),
],
),
)
@@ -156,7 +156,7 @@ class PipeTestCases:
class PipeExtractTestCases:
PIPE_OCR_IMAGE_TEST_CASES: ClassVar[list[str]] = [
- ImageTestCases.IMAGE_FILE_PATH_PNG,
+ ImageTestCases.IMAGE_FILE_PATH_PNG_1,
ImageTestCases.IMAGE_URL_PNG,
]
PIPE_OCR_PDF_TEST_CASES: ClassVar[list[str]] = PDFTestCases.DOCUMENT_FILE_PATHS + PDFTestCases.DOCUMENT_URLS
diff --git a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_extract/test_data.py b/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_extract/test_data.py
index 05caa098f..efc56086c 100644
--- a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_extract/test_data.py
+++ b/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_extract/test_data.py
@@ -12,14 +12,14 @@ class PipeExtractTestCases:
description="Extract text from image",
inputs={"image": "Image"},
output="Page",
- extract_skill=ExtractSkill.EXTRACT_TEXT_FROM_VISUALS,
+ extract_skill=ExtractSkill.PDF_TEXT_EXTRACTOR,
),
PipeExtractBlueprint(
source=None,
description="Extract text from image",
inputs={"image": "Image"},
output="Page[]",
- model=ExtractSkill.EXTRACT_TEXT_FROM_VISUALS,
+ model=ExtractSkill.PDF_TEXT_EXTRACTOR,
),
)
@@ -30,7 +30,7 @@ class PipeExtractTestCases:
description="Extract with page options",
inputs={"document": "PDF"},
output="Page[]",
- extract_skill=ExtractSkill.EXTRACT_TEXT_FROM_PDF,
+ extract_skill=ExtractSkill.PDF_TEXT_EXTRACTOR,
page_images=True,
page_image_captions=True,
page_views=True,
@@ -40,7 +40,7 @@ class PipeExtractTestCases:
description="Extract with page options",
inputs={"document": "PDF"},
output="Page[]",
- model=ExtractSkill.EXTRACT_TEXT_FROM_PDF,
+ model=ExtractSkill.PDF_TEXT_EXTRACTOR,
page_images=True,
page_image_captions=True,
page_views=True,
diff --git a/tests/unit/pipelex/system/pipelex_service/__init__.py b/tests/unit/pipelex/system/pipelex_service/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/unit/pipelex/system/pipelex_service/conftest.py b/tests/unit/pipelex/system/pipelex_service/conftest.py
new file mode 100644
index 000000000..f0ef9fb92
--- /dev/null
+++ b/tests/unit/pipelex/system/pipelex_service/conftest.py
@@ -0,0 +1,25 @@
+"""Conftest for pipelex_service unit tests.
+
+These tests are pure unit tests that don't need Pipelex initialization.
+We override the autouse fixture from the root conftest to disable it.
+"""
+
+import pytest
+from pytest_mock import MockerFixture
+
+
[email protected](scope="module", autouse=True)
+def reset_pipelex_config_fixture():
+ """Override the root conftest fixture to disable Pipelex initialization for these tests.
+
+ We mock the log module to avoid needing full Pipelex setup.
+ """
+ return
+
+
[email protected](autouse=True)
+def mock_log(mocker: MockerFixture):
+ """Mock the log module for all tests in this package."""
+ mock_logger = mocker.MagicMock()
+ mocker.patch("pipelex.system.pipelex_service.gateway_config_merger.log", mock_logger)
+ return mock_logger
diff --git a/tests/unit/pipelex/system/pipelex_service/test_gateway_config_merger.py b/tests/unit/pipelex/system/pipelex_service/test_gateway_config_merger.py
new file mode 100644
index 000000000..69f622507
--- /dev/null
+++ b/tests/unit/pipelex/system/pipelex_service/test_gateway_config_merger.py
@@ -0,0 +1,166 @@
+"""Unit tests for GatewayConfigMerger."""
+
+import warnings
+from typing import Any
+
+import pytest
+
+from pipelex.system.pipelex_service.exceptions import GatewayConfigMergeError, GatewayOverrideWarning
+from pipelex.system.pipelex_service.gateway_config_merger import (
+ ALLOWED_OVERRIDE_KEYS,
+ GatewayConfigMerger,
+)
+
+
+class TestGatewayConfigMerger:
+ """Tests for GatewayConfigMerger."""
+
+ def test_merge_no_overrides(self) -> None:
+ """Test merging with empty local overrides returns copy of remote config."""
+ remote_config: dict[str, Any] = {
+ "defaults": {"sdk": "gateway_completions"},
+ "gpt-4o": {"model_id": "gpt-4o-2024-11-20", "sdk": "gateway_responses"},
+ }
+ local_overrides: dict[str, Any] = {}
+
+ result = GatewayConfigMerger.merge(remote_config, local_overrides)
+
+ assert result == remote_config
+ # Verify it's a copy, not the same object
+ assert result is not remote_config
+
+ def test_merge_allowed_override_applied(self) -> None:
+ """Test that allowed keys (sdk, structure_method) are applied."""
+ remote_config: dict[str, Any] = {
+ "gpt-4o": {
+ "model_id": "gpt-4o-2024-11-20",
+ "sdk": "gateway_completions",
+ "structure_method": "instructor/openai_tools",
+ },
+ }
+ local_overrides: dict[str, Any] = {
+ "gpt-4o": {
+ "sdk": "gateway_responses",
+ "structure_method": "instructor/openai_responses_tools",
+ },
+ }
+
+ with warnings.catch_warnings(record=True) as caught_warnings:
+ warnings.simplefilter("always")
+ result = GatewayConfigMerger.merge(remote_config, local_overrides)
+
+ assert result["gpt-4o"]["sdk"] == "gateway_responses"
+ assert result["gpt-4o"]["structure_method"] == "instructor/openai_responses_tools"
+ # Original model_id should be preserved
+ assert result["gpt-4o"]["model_id"] == "gpt-4o-2024-11-20"
+ # Check warning was issued
+ assert any(issubclass(warning.category, GatewayOverrideWarning) for warning in caught_warnings)
+
+ def test_merge_disallowed_override_ignored(self) -> None:
+ """Test that non-allowed keys are ignored."""
+ remote_config: dict[str, Any] = {
+ "gpt-4o": {
+ "model_id": "gpt-4o-2024-11-20",
+ "costs": {"input": 2.5, "output": 10.0},
+ },
+ }
+ local_overrides: dict[str, Any] = {
+ "gpt-4o": {
+ "model_id": "hacked-model", # Should be ignored
+ "costs": {"input": 0, "output": 0}, # Should be ignored
+ },
+ }
+
+ result = GatewayConfigMerger.merge(remote_config, local_overrides)
+
+ # Original values should be preserved
+ assert result["gpt-4o"]["model_id"] == "gpt-4o-2024-11-20"
+ assert result["gpt-4o"]["costs"] == {"input": 2.5, "output": 10.0}
+
+ def test_merge_unknown_model_override_ignored(self) -> None:
+ """Test that overrides for unknown models are ignored."""
+ remote_config: dict[str, Any] = {
+ "gpt-4o": {"model_id": "gpt-4o-2024-11-20"},
+ }
+ local_overrides: dict[str, Any] = {
+ "unknown-model": {"sdk": "gateway_responses"},
+ }
+
+ result = GatewayConfigMerger.merge(remote_config, local_overrides)
+
+ # Unknown model should not be added
+ assert "unknown-model" not in result
+
+ def test_merge_defaults_override_ignored(self) -> None:
+ """Test that defaults section overrides are ignored (only per-model overrides allowed)."""
+ remote_config: dict[str, Any] = {
+ "defaults": {
+ "sdk": "gateway_completions",
+ "structure_method": "instructor/openai_tools",
+ },
+ }
+ local_overrides: dict[str, Any] = {
+ "defaults": {
+ "sdk": "gateway_responses", # Should be ignored
+ },
+ }
+
+ result = GatewayConfigMerger.merge(remote_config, local_overrides)
+
+ # Defaults override should be ignored - original values preserved
+ assert result["defaults"]["sdk"] == "gateway_completions"
+ assert result["defaults"]["structure_method"] == "instructor/openai_tools"
+
+ def test_deep_copy_preserves_nested_dicts(self) -> None:
+ """Test that deep copy properly copies nested dictionaries."""
+ remote_config: dict[str, Any] = {
+ "gpt-4o": {
+ "model_id": "gpt-4o",
+ "costs": {"input": 2.5, "output": 10.0},
+ "inputs": ["text", "images"],
+ },
+ }
+
+ result = GatewayConfigMerger.merge(remote_config, {})
+
+ # Modify the result
+ result["gpt-4o"]["costs"]["input"] = 999
+
+ # Original should be unchanged
+ assert remote_config["gpt-4o"]["costs"]["input"] == 2.5
+
+ def test_allowed_override_keys_contains_expected(self) -> None:
+ """Test that ALLOWED_OVERRIDE_KEYS contains the expected keys."""
+ assert "sdk" in ALLOWED_OVERRIDE_KEYS
+ assert "structure_method" in ALLOWED_OVERRIDE_KEYS
+ assert len(ALLOWED_OVERRIDE_KEYS) == 2
+
+ def test_merge_with_non_dict_local_override_raises(self) -> None:
+ """Test that non-dict local override values raise GatewayConfigMergeError."""
+ remote_config: dict[str, Any] = {
+ "gpt-4o": {"model_id": "gpt-4o-2024-11-20"},
+ }
+ local_overrides: dict[str, Any] = {
+ "gpt-4o": "not-a-dict",
+ }
+
+ with pytest.raises(GatewayConfigMergeError) as exc_info:
+ GatewayConfigMerger.merge(remote_config, local_overrides)
+
+ assert "gpt-4o" in str(exc_info.value)
+ assert "must be a dictionary" in str(exc_info.value)
+
+ def test_merge_with_non_dict_remote_config_raises(self) -> None:
+ """Test that non-dict remote config values raise GatewayConfigMergeError."""
+ remote_config: dict[str, Any] = {
+ "gpt-4o": "not-a-dict",
+ }
+ local_overrides: dict[str, Any] = {
+ "gpt-4o": {"sdk": "gateway_responses"},
+ }
+
+ with pytest.raises(GatewayConfigMergeError) as exc_info:
+ GatewayConfigMerger.merge(remote_config, local_overrides)
+
+ assert "gpt-4o" in str(exc_info.value)
+ assert "must be a dictionary" in str(exc_info.value)
diff --git a/tests/unit/pipelex/system/pipelex_service/test_pipelex_service_config.py b/tests/unit/pipelex/system/pipelex_service/test_pipelex_service_config.py
new file mode 100644
index 000000000..1f60b90bd
--- /dev/null
+++ b/tests/unit/pipelex/system/pipelex_service/test_pipelex_service_config.py
@@ -0,0 +1,50 @@
+"""Unit tests for PipelexServiceConfig."""
+
+import os
+import pathlib
+import tempfile
+
+from pipelex.system.pipelex_service.pipelex_service_config import (
+ PIPELEX_SERVICE_CONFIG_FILE_NAME,
+ PipelexServiceAgreement,
+ PipelexServiceConfig,
+ load_pipelex_service_config_if_exists,
+)
+
+
+class TestPipelexServiceConfig:
+ """Tests for PipelexServiceConfig and related functions."""
+
+ def test_gateway_config_default_terms_not_accepted(self) -> None:
+ """Test that gateway terms_accepted defaults to False."""
+ config = PipelexServiceAgreement()
+ assert config.terms_accepted is False
+
+ def test_gateway_config_terms_accepted(self) -> None:
+ """Test gateway config with terms_accepted = True."""
+ config = PipelexServiceAgreement(terms_accepted=True)
+ assert config.terms_accepted is True
+
+ def test_pipelex_service_config_with_gateway(self) -> None:
+ """Test PipelexServiceConfig with custom gateway config."""
+ config = PipelexServiceConfig(agreement=PipelexServiceAgreement(terms_accepted=True))
+ assert config.agreement.terms_accepted is True
+
+ def test_load_pipelex_service_config_if_exists_returns_none(self) -> None:
+ """Test load_pipelex_service_config_if_exists returns None when file doesn't exist."""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ config = load_pipelex_service_config_if_exists(config_dir=temp_dir)
+ assert config is None
+
+ def test_load_pipelex_service_config_if_exists_returns_config(self) -> None:
+ """Test load_pipelex_service_config_if_exists returns config when file exists."""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ config_content = """[agreement]
+terms_accepted = false
+"""
+ config_path = os.path.join(temp_dir, PIPELEX_SERVICE_CONFIG_FILE_NAME)
+ pathlib.Path(config_path).write_text(config_content, encoding="utf-8")
+
+ config = load_pipelex_service_config_if_exists(config_dir=temp_dir)
+ assert config is not None
+ assert config.agreement.terms_accepted is False
diff --git a/tests/unit/pipelex/system/pipelex_service/test_remote_config_provider.py b/tests/unit/pipelex/system/pipelex_service/test_remote_config_provider.py
new file mode 100644
index 000000000..e3b4f1ecb
--- /dev/null
+++ b/tests/unit/pipelex/system/pipelex_service/test_remote_config_provider.py
@@ -0,0 +1,69 @@
+"""Unit tests for remote config provider."""
+
+import hashlib
+
+import pytest
+from pydantic import ValidationError
+
+from pipelex.system.pipelex_service.remote_config import RemoteConfig
+
+
+class TestGatewayRemoteConfig:
+ """Tests for GatewayRemoteConfig model."""
+
+ def test_gateway_remote_config_valid(self) -> None:
+ """Test creating a valid GatewayRemoteConfig."""
+ payload = {
+ "backend_model_specs": {
+ "defaults": {"sdk": "gateway_completions"},
+ "gpt-4o": {"model_id": "gpt-4o-2024-11-20"},
+ }
+ }
+ config = RemoteConfig.model_validate(payload)
+ assert "defaults" in config.backend_model_specs
+ assert "gpt-4o" in config.backend_model_specs
+
+ def test_gateway_remote_config_missing_backend_fails(self) -> None:
+ """Test that missing backend key raises validation error."""
+ payload = {"other_key": "value"}
+ with pytest.raises(ValidationError):
+ RemoteConfig.model_validate(payload)
+
+ def test_gateway_remote_config_empty_backend(self) -> None:
+ """Test GatewayRemoteConfig with empty backend dict."""
+ payload: dict[str, dict[str, str]] = {"backend_model_specs": {}}
+ config = RemoteConfig.model_validate(payload)
+ assert config.backend_model_specs == {}
+
+
+class TestApiKeyHashing:
+ """Tests for API key hashing functionality.
+
+ The hash is used as distinct_id for Pipelex PostHog telemetry.
+ """
+
+ @staticmethod
+ def _hash_api_key(api_key: str) -> str:
+ """Hash the API key using truncated SHA256 - same logic as hash_gateway_api_key."""
+ return hashlib.sha256(api_key.encode("utf-8")).hexdigest()[:16]
+
+ def test_hash_api_key_deterministic(self) -> None:
+ """Test that API key hashing is deterministic."""
+ api_key = "test-api-key-123"
+ hash1 = self._hash_api_key(api_key)
+ hash2 = self._hash_api_key(api_key)
+ assert hash1 == hash2
+
+ def test_hash_api_key_different_keys(self) -> None:
+ """Test that different API keys produce different hashes."""
+ hash1 = self._hash_api_key("key1")
+ hash2 = self._hash_api_key("key2")
+ assert hash1 != hash2
+
+ def test_hash_api_key_is_truncated_sha256(self) -> None:
+ """Test that hash is 16 characters (truncated SHA256 hex)."""
+ api_key = "test-key"
+ hashed = self._hash_api_key(api_key)
+ assert len(hashed) == 16
+ # Verify it's a valid hex string
+ int(hashed, 16)
diff --git a/tests/unit/pipelex/system/telemetry/__init__.py b/tests/unit/pipelex/system/telemetry/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/unit/pipelex/system/telemetry/test_otel_factory.py b/tests/unit/pipelex/system/telemetry/test_otel_factory.py
new file mode 100644
index 000000000..a2a02c027
--- /dev/null
+++ b/tests/unit/pipelex/system/telemetry/test_otel_factory.py
@@ -0,0 +1,97 @@
+"""Unit tests for OTel utility functions."""
+
+import pytest
+
+from pipelex.system.telemetry.otel_factory import OtelFactory
+
+
+class TestOtelFactory:
+ """Test OTel factory utilities."""
+
+ # --- make_truncated_content tests ---
+
+ def test_make_truncated_content_no_truncation_when_within_limit(self) -> None:
+ """Test that content within limit is returned unchanged."""
+ content = "short content"
+ result = OtelFactory.make_truncated_content(content, max_length=100)
+ assert result == content
+
+ def test_make_truncated_content_truncates_when_exceeds_limit(self) -> None:
+ """Test that content exceeding limit is truncated with suffix."""
+ content = "a" * 50
+ result = OtelFactory.make_truncated_content(content, max_length=20)
+ assert result.endswith("... [truncated]")
+ assert len(result) <= 20
+
+ def test_make_truncated_content_no_limit_when_max_length_is_none(self) -> None:
+ """Test that None max_length means no truncation."""
+ content = "a" * 10000
+ result = OtelFactory.make_truncated_content(content, max_length=None)
+ assert result == content
+
+ # --- make_trace_id tests ---
+
+ def test_pipeline_run_id_to_trace_id_is_deterministic(self) -> None:
+ """Test that pipeline_run_id_to_trace_id produces consistent trace IDs."""
+ pipeline_run_id = "my_pipe_abc123xyz"
+
+ trace_id_1 = OtelFactory.make_trace_id(pipeline_run_id)
+ trace_id_2 = OtelFactory.make_trace_id(pipeline_run_id)
+
+ assert trace_id_1 == trace_id_2
+
+ def test_pipeline_run_id_to_trace_id_produces_128_bit_int(self) -> None:
+ """Test that pipeline_run_id_to_trace_id produces a valid 128-bit integer."""
+ pipeline_run_id = "test_pipeline_run_id"
+
+ trace_id = OtelFactory.make_trace_id(pipeline_run_id)
+
+ # Should be a positive integer that fits in 128 bits
+ assert isinstance(trace_id, int)
+ assert trace_id > 0
+ assert trace_id.bit_length() <= 128
+
+ def test_pipeline_run_id_to_trace_id_different_inputs_produce_different_outputs(self) -> None:
+ """Test that different pipeline_run_ids produce different trace IDs."""
+ trace_id_1 = OtelFactory.make_trace_id("pipeline_a")
+ trace_id_2 = OtelFactory.make_trace_id("pipeline_b")
+
+ assert trace_id_1 != trace_id_2
+
+ @pytest.mark.parametrize(
+ "pipeline_run_id",
+ [
+ "simple_id",
+ "pipe_with_numbers_123",
+ "UPPERCASE_ID",
+ "mixed_Case_Id",
+ "id-with-dashes",
+ "id.with.dots",
+ "a", # Very short
+ "a" * 1000, # Very long
+ ],
+ )
+ def test_pipeline_run_id_to_trace_id_handles_various_formats(self, pipeline_run_id: str) -> None:
+ """Test that pipeline_run_id_to_trace_id handles various input formats."""
+ trace_id = OtelFactory.make_trace_id(pipeline_run_id)
+
+ assert isinstance(trace_id, int)
+ assert trace_id > 0
+ assert trace_id.bit_length() <= 128
+
+ # --- make_trace_names tests ---
+
+ def test_make_trace_names_returns_full_and_redacted(self) -> None:
+ """Test that make_trace_names returns both full and redacted trace names."""
+ trace_name, trace_name_redacted = OtelFactory.make_trace_names("run_123", "my_pipe")
+
+ # Full trace name should include pipe code
+ assert trace_name.startswith("my_pipe_")
+ assert len(trace_name) == len("my_pipe_") + 8 # pipe_code + underscore + 8-char hash
+
+ # Redacted trace name should just be the hash
+ assert "my_pipe" not in trace_name_redacted
+ assert len(trace_name_redacted) == 8 # just the 8-char hash
+
+ # Both should share the same hash suffix
+ assert trace_name.endswith(trace_name_redacted)
diff --git a/tests/unit/pipelex/system/telemetry/test_redaction.py b/tests/unit/pipelex/system/telemetry/test_redaction.py
new file mode 100644
index 000000000..47f796ee2
--- /dev/null
+++ b/tests/unit/pipelex/system/telemetry/test_redaction.py
@@ -0,0 +1,47 @@
+"""Unit tests for telemetry redaction."""
+
+from pytest_mock import MockerFixture
+
+from pipelex.system.telemetry.telemetry_manager_abstract import TelemetryManagerAbstract
+
+
+class TestIsCapturePipeCodesEnabled:
+ """Tests for TelemetryManagerAbstract.is_capture_pipe_codes_enabled."""
+
+ def test_returns_false_when_no_telemetry_manager(self) -> None:
+ """Test that it returns False when no telemetry manager is configured."""
+ TelemetryManagerAbstract.clear_instance()
+
+ result = TelemetryManagerAbstract.is_capture_pipe_codes_enabled()
+
+ assert result is False
+
+ def test_returns_property_value_when_true(self, mocker: MockerFixture) -> None:
+ """Test that it returns True when capture_pipe_codes_enabled property is True."""
+ mock_instance = mocker.MagicMock()
+ mock_instance.capture_pipe_codes_enabled = True
+
+ mocker.patch.object(
+ TelemetryManagerAbstract,
+ "get_instance",
+ return_value=mock_instance,
+ )
+
+ result = TelemetryManagerAbstract.is_capture_pipe_codes_enabled()
+
+ assert result is True
+
+ def test_returns_property_value_when_false(self, mocker: MockerFixture) -> None:
+ """Test that it returns False when capture_pipe_codes_enabled property is False."""
+ mock_instance = mocker.MagicMock()
+ mock_instance.capture_pipe_codes_enabled = False
+
+ mocker.patch.object(
+ TelemetryManagerAbstract,
+ "get_instance",
+ return_value=mock_instance,
+ )
+
+ result = TelemetryManagerAbstract.is_capture_pipe_codes_enabled()
+
+ assert result is False
diff --git a/tests/unit/pipelex/tools/misc/test_data.py b/tests/unit/pipelex/tools/misc/test_data.py
index 7ca651d3b..5b57513b0 100644
--- a/tests/unit/pipelex/tools/misc/test_data.py
+++ b/tests/unit/pipelex/tools/misc/test_data.py
@@ -21,3 +21,11 @@ class ComplexUser(BaseModel):
addresses: list[Address]
preferences: UserPreferences
metadata: dict[str, str | int | bool] = Field(default_factory=dict)
+
+
+class ImageData(BaseModel):
+ """Model with base64 image data for testing truncation."""
+
+ name: str
+ base_64: str
+ url: str | None = None
diff --git a/tests/unit/pipelex/tools/misc/test_pretty.py b/tests/unit/pipelex/tools/misc/test_pretty.py
index 025075c9e..a4a63deab 100644
--- a/tests/unit/pipelex/tools/misc/test_pretty.py
+++ b/tests/unit/pipelex/tools/misc/test_pretty.py
@@ -4,8 +4,10 @@ import textwrap
import pytest
from pytest import CaptureFixture
+from pipelex.tools.misc.attribute_utils import AttributePolisher
from pipelex.tools.misc.pretty import pretty_print
from tests.unit.pipelex.tools.misc.conftest import ComplexUser
+from tests.unit.pipelex.tools.misc.test_data import ImageData
def remove_ansi_escape_codes(text: str) -> str:
@@ -16,7 +18,7 @@ def remove_ansi_escape_codes(text: str) -> str:
@pytest.fixture
def widths() -> tuple[int, int]:
"""Return tuple of (width, console_width) for pretty print tests."""
- return (180, 200)
+ return (60, 80)
class TestPrettyPrint:
@@ -172,34 +174,114 @@ class TestPrettyPrint:
assert output == expected_output, f"Output did not match expected:\n{output}"
def test_pretty_print_pydantic_object(self, complex_user: ComplexUser, widths: tuple[int, int], capsys: CaptureFixture[str]):
- width, console_width = widths
+ """Test that BaseModel objects are rendered with Rich's Pretty formatting.
+ Note: BaseModel objects are wrapped with make_truncated_wrapper to provide
+ truncation of long values while preserving the original class name.
+ """
+ width, console_width = widths
pretty_print(content=complex_user, title="Complex User", width=width, console_width=console_width)
captured = capsys.readouterr()
output = remove_ansi_escape_codes(captured.out)
- expected_output = textwrap.dedent("""
- ╭─ Complex User ──────────────────────────────────────────────────────────────────────────────────╮
- │ │
- │ ComplexUser( │
- │ name='John Doe', │
- │ age=30, │
- │ email='[email protected]', │
- │ addresses=[ │
- │ Address(street='123 Main St', city='Springfield', country='USA', postal_code='12345'), │
- │ Address(street='456 Side St', city='Brooklyn', country='USA', postal_code=None) │
- │ ], │
- │ preferences=UserPreferences( │
- │ theme='light', │
- │ notifications=False, │
- │ tags=['python', 'coding'] │
- │ ), │
- │ metadata={'last_login': '2024-03-20', 'login_count': 42, 'is_active': True} │
- │ ) │
- │ │
- ╰─────────────────────────────────────────────────────────────────────────────────────────────────╯
+ expected_output = textwrap.dedent("""\
+
+ ╭─ Complex User ──────────────────────╮
+ │ │
+ │ ComplexUser( │
+ │ name='John Doe', │
+ │ age=30, │
+ │ email='[email protected]', │
+ │ addresses=[ │
+ │ Address( │
+ │ street='123 Main St', │
+ │ city='Springfield', │
+ │ country='USA', │
+ │ postal_code='12345' │
+ │ ), │
+ │ Address( │
+ │ street='456 Side St', │
+ │ city='Brooklyn', │
+ │ country='USA', │
+ │ postal_code=None │
+ │ ) │
+ │ ], │
+ │ preferences=UserPreferences( │
+ │ theme='light', │
+ │ notifications=False, │
+ │ tags=['python', 'coding'] │
+ │ ), │
+ │ metadata={ │
+ │ 'last_login': '2024-03-20', │
+ │ 'login_count': 42, │
+ │ 'is_active': True │
+ │ } │
+ │ ) │
+ │ │
+ ╰─────────────────────────────────────╯
""")
- assert output == expected_output, f"Make sure you enable pytest '-s' option. Output did not match expected:\n{output}"
+ assert output == expected_output, f"Output did not match expected:\n{output}"
+
+ def test_pretty_print_pydantic_with_base64_truncation(self, widths: tuple[int, int], capsys: CaptureFixture[str]):
+ """Test that long base64 strings are truncated in pretty print output."""
+ # Create a long base64 string (typical for images)
+ long_base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==" * 100
+ image_data = ImageData(
+ name="test_image.png",
+ base_64=long_base64,
+ url="data:image/png;base64," + long_base64,
+ )
+
+ width, console_width = widths
+ pretty_print(content=image_data, title="Image Data", width=width, console_width=console_width)
+
+ captured = capsys.readouterr()
+ output = remove_ansi_escape_codes(captured.out)
+
+ # Verify the full long strings are NOT in output (truncation worked)
+ assert long_base64 not in output
+ # Verify the output contains the data URL prefix (url field is present)
+ assert "data:image/png;base64," in output
+ # Verify the output is reasonably sized (not megabytes of base64)
+ assert len(output) < 2000 # Should be much smaller than original
+
+ def test_pretty_print_dict_with_base64_truncation(self, widths: tuple[int, int], capsys: CaptureFixture[str]):
+ """Test that long base64 strings in dicts are also truncated."""
+ long_base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" * 50
+ data = {
+ "name": "test",
+ "base_64": long_base64,
+ "url": "data:image/jpeg;base64," + long_base64,
+ }
+
+ width, console_width = widths
+ pretty_print(content=data, title="Dict with Base64", width=width, console_width=console_width)
+
+ captured = capsys.readouterr()
+ output = remove_ansi_escape_codes(captured.out)
+
+ # Verify the base_64 field is truncated (field name triggers truncation)
+ assert long_base64 not in output
+ # Verify the output is reasonably sized
+ assert len(output) < 2000
+
+ def test_attribute_polisher_should_truncate_any_long_string(self):
+ """Test the base64 detection logic for long strings."""
+ # Pure base64 string should be detected
+ base64_str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" * 20
+ assert AttributePolisher.should_truncate_any_long_string(base64_str)
+
+ # Normal text should not be detected even if long
+ normal_text = "This is a normal text with spaces and punctuation! " * 20
+ assert not AttributePolisher.should_truncate_any_long_string(normal_text)
+
+ # Data URL should be detected
+ data_url = "data:image/png;base64," + base64_str
+ assert AttributePolisher.should_truncate_any_long_string(data_url)
+
+ # Short strings should not be truncated
+ short_base64 = "iVBORw0KGgoAAAANSUhEUg=="
+ assert not AttributePolisher.should_truncate_any_long_string(short_base64)
diff --git a/uv.lock b/uv.lock
index 78aa023e9..927c5f3b8 100644
--- a/uv.lock
+++ b/uv.lock
@@ -345,6 +345,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/70/2d/3b71d25da85e10700287d90bd5c525821985d80b55895d81f7d0683e4e07/botocore_stubs-1.40.76-py3-none-any.whl", hash = "sha256:84c9a24c2a38a59dd173f2655afacf7b6484c05f3d61cf198b59bb54a6efebc5", size = 66542, upload-time = "2025-11-18T20:30:26.596Z" },
]
+[[package]]
+name = "cached-property"
+version = "2.0.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/76/4b/3d870836119dbe9a5e3c9a61af8cc1a8b69d75aea564572e385882d5aefb/cached_property-2.0.1.tar.gz", hash = "sha256:484d617105e3ee0e4f1f58725e72a8ef9e93deee462222dbd51cd91230897641", size = 10574, upload-time = "2024-10-25T15:43:55.667Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/11/0e/7d8225aab3bc1a0f5811f8e1b557aa034ac04bdf641925b30d3caf586b28/cached_property-2.0.1-py3-none-any.whl", hash = "sha256:f617d70ab1100b7bcf6e42228f9ddcb78c676ffa167278d9f730d1c2fba69ccb", size = 7428, upload-time = "2024-10-25T15:43:54.711Z" },
+]
+
[[package]]
name = "cachetools"
version = "6.2.2"
@@ -809,6 +818,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/c6/28/0185dcda66f1994171067cfdb0e44a166450239d5b11b3a8a281dd2da459/google_genai-1.51.0-py3-none-any.whl", hash = "sha256:bfb7d0c6ba48ba9bda539f0d5e69dad827d8735a8b1e4703bafa0a2945d293e1", size = 260483, upload-time = "2025-11-18T05:32:45.938Z" },
]
+[[package]]
+name = "googleapis-common-protos"
+version = "1.72.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "protobuf" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/e5/7b/adfd75544c415c487b33061fe7ae526165241c1ea133f9a9125a56b39fd8/googleapis_common_protos-1.72.0.tar.gz", hash = "sha256:e55a601c1b32b52d7a3e65f43563e2aa61bcd737998ee672ac9b951cd49319f5", size = 147433, upload-time = "2025-11-06T18:29:24.087Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c4/ab/09169d5a4612a5f92490806649ac8d41e3ec9129c636754575b3553f4ea4/googleapis_common_protos-1.72.0-py3-none-any.whl", hash = "sha256:4299c5a82d5ae1a9702ada957347726b167f9f8d1fc352477702a1e851ff4038", size = 297515, upload-time = "2025-11-06T18:29:13.14Z" },
+]
+
[[package]]
name = "h11"
version = "0.16.0"
@@ -873,6 +894,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/0e/61/66938bbb5fc52dbdf84594873d5b51fb1f7c7794e9c0f5bd885f30bc507b/idna-3.11-py3-none-any.whl", hash = "sha256:771a87f49d9defaf64091e6e6fe9c18d4833f140bd19464795bc32d966ca37ea", size = 71008, upload-time = "2025-10-12T14:55:18.883Z" },
]
+[[package]]
+name = "importlib-metadata"
+version = "8.7.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "zipp" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/76/66/650a33bd90f786193e4de4b3ad86ea60b53c89b669a5c7be931fac31cdb0/importlib_metadata-8.7.0.tar.gz", hash = "sha256:d13b81ad223b890aa16c5471f2ac3056cf76c5f10f82d6f9292f0b415f389000", size = 56641, upload-time = "2025-04-27T15:29:01.736Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/20/b0/36bd937216ec521246249be3bf9855081de4c5e06a0c9b4219dbeda50373/importlib_metadata-8.7.0-py3-none-any.whl", hash = "sha256:e5dd1551894c77868a30651cef00984d50e1002d06942a7101d34870c5f02afd", size = 27656, upload-time = "2025-04-27T15:29:00.214Z" },
+]
+
[[package]]
name = "iniconfig"
version = "2.3.0"
@@ -1610,6 +1643,88 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/55/4f/dbc0c124c40cb390508a82770fb9f6e3ed162560181a85089191a851c59a/openai-2.8.1-py3-none-any.whl", hash = "sha256:c6c3b5a04994734386e8dad3c00a393f56d3b68a27cd2e8acae91a59e4122463", size = 1022688, upload-time = "2025-11-17T22:39:57.675Z" },
]
+[[package]]
+name = "opentelemetry-api"
+version = "1.39.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "importlib-metadata" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/c0/0b/e5428c009d4d9af0515b0a8371a8aaae695371af291f45e702f7969dce6b/opentelemetry_api-1.39.0.tar.gz", hash = "sha256:6130644268c5ac6bdffaf660ce878f10906b3e789f7e2daa5e169b047a2933b9", size = 65763, upload-time = "2025-12-03T13:19:56.378Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/05/85/d831a9bc0a9e0e1a304ff3d12c1489a5fbc9bf6690a15dcbdae372bbca45/opentelemetry_api-1.39.0-py3-none-any.whl", hash = "sha256:3c3b3ca5c5687b1b5b37e5c5027ff68eacea8675241b29f13110a8ffbb8f0459", size = 66357, upload-time = "2025-12-03T13:19:33.043Z" },
+]
+
+[[package]]
+name = "opentelemetry-exporter-otlp-proto-common"
+version = "1.39.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "opentelemetry-proto" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/11/cb/3a29ce606b10c76d413d6edd42d25a654af03e73e50696611e757d2602f3/opentelemetry_exporter_otlp_proto_common-1.39.0.tar.gz", hash = "sha256:a135fceed1a6d767f75be65bd2845da344dd8b9258eeed6bc48509d02b184409", size = 20407, upload-time = "2025-12-03T13:19:59.003Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ef/c6/215edba62d13a3948c718b289539f70e40965bc37fc82ecd55bb0b749c1a/opentelemetry_exporter_otlp_proto_common-1.39.0-py3-none-any.whl", hash = "sha256:3d77be7c4bdf90f1a76666c934368b8abed730b5c6f0547a2ec57feb115849ac", size = 18367, upload-time = "2025-12-03T13:19:36.906Z" },
+]
+
+[[package]]
+name = "opentelemetry-exporter-otlp-proto-http"
+version = "1.39.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "googleapis-common-protos" },
+ { name = "opentelemetry-api" },
+ { name = "opentelemetry-exporter-otlp-proto-common" },
+ { name = "opentelemetry-proto" },
+ { name = "opentelemetry-sdk" },
+ { name = "requests" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/81/dc/1e9bf3f6a28e29eba516bc0266e052996d02bc7e92675f3cd38169607609/opentelemetry_exporter_otlp_proto_http-1.39.0.tar.gz", hash = "sha256:28d78fc0eb82d5a71ae552263d5012fa3ebad18dfd189bf8d8095ba0e65ee1ed", size = 17287, upload-time = "2025-12-03T13:20:01.134Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/bc/46/e4a102e17205bb05a50dbf24ef0e92b66b648cd67db9a68865af06a242fd/opentelemetry_exporter_otlp_proto_http-1.39.0-py3-none-any.whl", hash = "sha256:5789cb1375a8b82653328c0ce13a054d285f774099faf9d068032a49de4c7862", size = 19639, upload-time = "2025-12-03T13:19:39.536Z" },
+]
+
+[[package]]
+name = "opentelemetry-proto"
+version = "1.39.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "protobuf" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/48/b5/64d2f8c3393cd13ea2092106118f7b98461ba09333d40179a31444c6f176/opentelemetry_proto-1.39.0.tar.gz", hash = "sha256:c1fa48678ad1a1624258698e59be73f990b7fc1f39e73e16a9d08eef65dd838c", size = 46153, upload-time = "2025-12-03T13:20:08.729Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e3/4d/d500e1862beed68318705732d1976c390f4a72ca8009c4983ff627acff20/opentelemetry_proto-1.39.0-py3-none-any.whl", hash = "sha256:1e086552ac79acb501485ff0ce75533f70f3382d43d0a30728eeee594f7bf818", size = 72534, upload-time = "2025-12-03T13:19:50.251Z" },
+]
+
+[[package]]
+name = "opentelemetry-sdk"
+version = "1.39.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "opentelemetry-api" },
+ { name = "opentelemetry-semantic-conventions" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/51/e3/7cd989003e7cde72e0becfe830abff0df55c69d237ee7961a541e0167833/opentelemetry_sdk-1.39.0.tar.gz", hash = "sha256:c22204f12a0529e07aa4d985f1bca9d6b0e7b29fe7f03e923548ae52e0e15dde", size = 171322, upload-time = "2025-12-03T13:20:09.651Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a4/b4/2adc8bc83eb1055ecb592708efb6f0c520cc2eb68970b02b0f6ecda149cf/opentelemetry_sdk-1.39.0-py3-none-any.whl", hash = "sha256:90cfb07600dfc0d2de26120cebc0c8f27e69bf77cd80ef96645232372709a514", size = 132413, upload-time = "2025-12-03T13:19:51.364Z" },
+]
+
+[[package]]
+name = "opentelemetry-semantic-conventions"
+version = "0.60b0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "opentelemetry-api" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/71/0e/176a7844fe4e3cb5de604212094dffaed4e18b32f1c56b5258bcbcba85c2/opentelemetry_semantic_conventions-0.60b0.tar.gz", hash = "sha256:227d7aa73cbb8a2e418029d6b6465553aa01cf7e78ec9d0bc3255c7b3ac5bf8f", size = 137935, upload-time = "2025-12-03T13:20:12.395Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d0/56/af0306666f91bae47db14d620775604688361f0f76a872e0005277311131/opentelemetry_semantic_conventions-0.60b0-py3-none-any.whl", hash = "sha256:069530852691136018087b52688857d97bba61cd641d0f8628d2d92788c4f78a", size = 219981, upload-time = "2025-12-03T13:19:53.585Z" },
+]
+
[[package]]
name = "packaging"
version = "25.0"
@@ -1727,8 +1842,13 @@ dependencies = [
{ name = "networkx", version = "3.4.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
{ name = "networkx", version = "3.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
{ name = "openai" },
+ { name = "opentelemetry-api" },
+ { name = "opentelemetry-exporter-otlp-proto-http" },
+ { name = "opentelemetry-sdk" },
+ { name = "opentelemetry-semantic-conventions" },
{ name = "pillow" },
{ name = "polyfactory" },
+ { name = "portkey-ai" },
{ name = "posthog" },
{ name = "pydantic" },
{ name = "pypdfium2" },
@@ -1816,8 +1936,13 @@ requires-dist = [
{ name = "mypy", marker = "extra == 'dev'", specifier = ">=1.11.2" },
{ name = "networkx", specifier = ">=3.4.2" },
{ name = "openai", specifier = ">=1.108.1" },
+ { name = "opentelemetry-api" },
+ { name = "opentelemetry-exporter-otlp-proto-http" },
+ { name = "opentelemetry-sdk" },
+ { name = "opentelemetry-semantic-conventions" },
{ name = "pillow", specifier = ">=11.2.1" },
{ name = "polyfactory", specifier = ">=2.21.0" },
+ { name = "portkey-ai", specifier = ">=2.1.0" },
{ name = "posthog", specifier = ">=6.7.0" },
{ name = "pydantic", specifier = ">=2.10.6,<3.0.0" },
{ name = "pylint", marker = "extra == 'dev'", specifier = ">=3.3.8" },
@@ -1878,6 +2003,27 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/54/86/742c4eb237cdb5e7e6dfb1474f5f0dac967896185f832c012dff4d7bdce2/polyfactory-3.0.0-py3-none-any.whl", hash = "sha256:ad9ba3b3f04c292d30673587946e1c5d18e249074368b09abb7c9455288cfc37", size = 61237, upload-time = "2025-11-15T11:23:00.524Z" },
]
+[[package]]
+name = "portkey-ai"
+version = "2.1.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "anyio" },
+ { name = "cached-property" },
+ { name = "distro" },
+ { name = "httpx" },
+ { name = "jiter" },
+ { name = "pydantic" },
+ { name = "sniffio" },
+ { name = "tqdm" },
+ { name = "types-requests" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/d4/8a/f5bbaab806ad61d9959cb7c88c639200feacac1b2ba7b455b97a2f216e7c/portkey_ai-2.1.0.tar.gz", hash = "sha256:c2558041c568eef8528737978089301cb9be056f166a683251831cbfa6a623cb", size = 567417, upload-time = "2025-11-25T20:32:43.102Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b7/11/c585b90ac842027e5f4f7f7cee72d3197f58ff24b6d7c5f1243aa8fa96be/portkey_ai-2.1.0-py3-none-any.whl", hash = "sha256:2166033f8e198745947fee5321d0bbcfb005afc35468bd5a948fa83dc16b6767", size = 1181622, upload-time = "2025-11-25T20:32:41.185Z" },
+]
+
[[package]]
name = "posthog"
version = "7.0.1"
@@ -1995,6 +2141,21 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/5b/5a/bc7b4a4ef808fa59a816c17b20c4bef6884daebbdf627ff2a161da67da19/propcache-0.4.1-py3-none-any.whl", hash = "sha256:af2a6052aeb6cf17d3e46ee169099044fd8224cbaf75c76a2ef596e8163e2237", size = 13305, upload-time = "2025-10-08T19:49:00.792Z" },
]
+[[package]]
+name = "protobuf"
+version = "6.33.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/0a/03/a1440979a3f74f16cab3b75b0da1a1a7f922d56a8ddea96092391998edc0/protobuf-6.33.1.tar.gz", hash = "sha256:97f65757e8d09870de6fd973aeddb92f85435607235d20b2dfed93405d00c85b", size = 443432, upload-time = "2025-11-13T16:44:18.895Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/06/f1/446a9bbd2c60772ca36556bac8bfde40eceb28d9cc7838755bc41e001d8f/protobuf-6.33.1-cp310-abi3-win32.whl", hash = "sha256:f8d3fdbc966aaab1d05046d0240dd94d40f2a8c62856d41eaa141ff64a79de6b", size = 425593, upload-time = "2025-11-13T16:44:06.275Z" },
+ { url = "https://files.pythonhosted.org/packages/a6/79/8780a378c650e3df849b73de8b13cf5412f521ca2ff9b78a45c247029440/protobuf-6.33.1-cp310-abi3-win_amd64.whl", hash = "sha256:923aa6d27a92bf44394f6abf7ea0500f38769d4b07f4be41cb52bd8b1123b9ed", size = 436883, upload-time = "2025-11-13T16:44:09.222Z" },
+ { url = "https://files.pythonhosted.org/packages/cd/93/26213ff72b103ae55bb0d73e7fb91ea570ef407c3ab4fd2f1f27cac16044/protobuf-6.33.1-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:fe34575f2bdde76ac429ec7b570235bf0c788883e70aee90068e9981806f2490", size = 427522, upload-time = "2025-11-13T16:44:10.475Z" },
+ { url = "https://files.pythonhosted.org/packages/c2/32/df4a35247923393aa6b887c3b3244a8c941c32a25681775f96e2b418f90e/protobuf-6.33.1-cp39-abi3-manylinux2014_aarch64.whl", hash = "sha256:f8adba2e44cde2d7618996b3fc02341f03f5bc3f2748be72dc7b063319276178", size = 324445, upload-time = "2025-11-13T16:44:11.869Z" },
+ { url = "https://files.pythonhosted.org/packages/8e/d0/d796e419e2ec93d2f3fa44888861c3f88f722cde02b7c3488fcc6a166820/protobuf-6.33.1-cp39-abi3-manylinux2014_s390x.whl", hash = "sha256:0f4cf01222c0d959c2b399142deb526de420be8236f22c71356e2a544e153c53", size = 339161, upload-time = "2025-11-13T16:44:12.778Z" },
+ { url = "https://files.pythonhosted.org/packages/1d/2a/3c5f05a4af06649547027d288747f68525755de692a26a7720dced3652c0/protobuf-6.33.1-cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:8fd7d5e0eb08cd5b87fd3df49bc193f5cfd778701f47e11d127d0afc6c39f1d1", size = 323171, upload-time = "2025-11-13T16:44:14.035Z" },
+ { url = "https://files.pythonhosted.org/packages/08/b4/46310463b4f6ceef310f8348786f3cff181cea671578e3d9743ba61a459e/protobuf-6.33.1-py3-none-any.whl", hash = "sha256:d595a9fd694fdeb061a62fbe10eb039cc1e444df81ec9bb70c7fc59ebcb1eafa", size = 170477, upload-time = "2025-11-13T16:44:17.633Z" },
+]
+
[[package]]
name = "pyasn1"
version = "0.6.1"
@@ -2706,6 +2867,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/bd/e0/1eed384f02555dde685fff1a1ac805c1c7dcb6dd019c916fe659b1c1f9ec/types_pyyaml-6.0.12.20250915-py3-none-any.whl", hash = "sha256:e7d4d9e064e89a3b3cae120b4990cd370874d2bf12fa5f46c97018dd5d3c9ab6", size = 20338, upload-time = "2025-09-15T03:00:59.218Z" },
]
+[[package]]
+name = "types-requests"
+version = "2.32.4.20250913"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "urllib3" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/36/27/489922f4505975b11de2b5ad07b4fe1dca0bca9be81a703f26c5f3acfce5/types_requests-2.32.4.20250913.tar.gz", hash = "sha256:abd6d4f9ce3a9383f269775a9835a4c24e5cd6b9f647d64f88aa4613c33def5d", size = 23113, upload-time = "2025-09-13T02:40:02.309Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2a/20/9a227ea57c1285986c4cf78400d0a91615d25b24e257fd9e2969606bdfae/types_requests-2.32.4.20250913-py3-none-any.whl", hash = "sha256:78c9c1fffebbe0fa487a418e0fa5252017e9c60d1a2da394077f1780f655d7e1", size = 20658, upload-time = "2025-09-13T02:40:01.115Z" },
+]
+
[[package]]
name = "types-s3transfer"
version = "0.14.0"
@@ -3021,3 +3194,12 @@ name = "yattag"
version = "1.16.1"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/1c/1a/d3b2a2b8f843f5e7138471c4a5c9172ef62bb41239aa4371784b7448110c/yattag-1.16.1.tar.gz", hash = "sha256:baa8f254e7ea5d3e0618281ad2ff5610e0e5360b3608e695c29bfb3b29d051f4", size = 29069, upload-time = "2024-11-02T22:38:30.443Z" }
+
+[[package]]
+name = "zipp"
+version = "3.23.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/e3/02/0f2892c661036d50ede074e376733dca2ae7c6eb617489437771209d4180/zipp-3.23.0.tar.gz", hash = "sha256:a07157588a12518c9d4034df3fbbee09c814741a33ff63c05fa29d26a2404166", size = 25547, upload-time = "2025-06-08T17:06:39.4Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2e/54/647ade08bf0db230bfea292f893923872fd20be6ac6f53b2b936ba839d75/zipp-3.23.0-py3-none-any.whl", hash = "sha256:071652d6115ed432f5ce1d34c336c0adfd6a884660d1e9712a256d3d3bd4b14e", size = 10276, upload-time = "2025-06-08T17:06:38.034Z" },
+]