You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by "bvolpato (via GitHub)" <gi...@apache.org> on 2026/09/22 06:07:55 UTC

[PR] [Python] Add decision model routing examples [beam]

bvolpato opened a new pull request, #40220:
URL: https://github.com/apache/beam/pull/40220

   ## Summary
   
   This draft explores **decision models** as a small, typed Beam Python integration. The main demo uses Jev Choice to route a finite message stream to a model-selected BigQuery table. A separate Noul fraud-review example includes an optional Score rubric. `DecisionModel` keeps the Beam caller independent of Jev, so a local Laya or Kev adapter can implement the same question/answer contract without changing the pipeline.
   
   ## Architecture
   
   ```mermaid
   flowchart LR
     A["TestStream or Pub/Sub"] --> B["RequestResponseIO<br/>DecisionModel caller"]
     B --> C["Choice: billing / technical / sales<br/>probabilities + confidence"]
     C --> D{"confidence gate"}
     D -->|accepted| E["dynamic BigQuery table<br/>or local JSONL destination"]
     D -->|uncertain| F["messages_review"]
     F --> E
   ```
   
   The transform owns the provider client lifecycle. The model chooses from a fixed label set; Beam code validates the label and selects the destination. The Noul example uses its yes probability for a visible review threshold. Score is a separate rubric question and can run beside Noul in one Jev request. The offline rule adapter exercises the same Beam graph without network access. It is a demo fixture, not a trained model.
   
   The [README](https://github.com/bvolpato/beam/blob/dd3428debcbe98a896a54421c05fbf9df4b2d3be/sdks/python/apache_beam/examples/inference/decision_models/README.md) includes commands, limitations, and a [graph rendered from the Python pipeline](https://github.com/bvolpato/beam/blob/dd3428debcbe98a896a54421c05fbf9df4b2d3be/sdks/python/apache_beam/examples/inference/decision_models/message_router.svg) using Beam `RenderRunner`. The graph-only BigQuery path does not write to BigQuery.
   
   ## Verification
   
   - Three focused policy tests pass. YAPF, pycodestyle, compilation, and `git diff --check` pass.
   - DirectRunner local runs wrote one JSONL row each to billing, technical, and sales destinations. The local Noul/Score demo completed.
   - A short live Jev DirectRunner run wrote the same three destinations. Caller wall times were **406.26 ms**, **249.70 ms**, and **226.34 ms** for billing, technical, and sales respectively (`jev-1.13.0`, `n=3`, local JSONL sink). This is a smoke observation, not a throughput or latency guarantee.
   - A separate live Jev Noul+Score run flagged only the synthetic bypass-verification message (Noul `0.97`; review threshold `0.7`).
   - The dynamic BigQuery transform expands and renders with Beam's GCP extra. A live BigQuery write and a Pub/Sub subscription run require project credentials and were not performed.
   
   The supplied Jev key was used only in process memory for the short live checks. It is absent from the commit, graph, logs, and PR body. Production use needs a worker secret path, quota policy, idempotency, and failed-row handling.
   
   ------------------------
   
   Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:
   
    - [ ] Mention the appropriate issue in your description (for example: `addresses #123`), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment `fixes #<ISSUE NUMBER>` instead.
    - [ ] Update `CHANGES.md` with noteworthy changes.
    - [ ] If this contribution is large, please file an Apache [Individual Contributor License Agreement](https://www.apache.org/licenses/icla.pdf).
   
   This is an example-only draft without an associated issue or release note. ICLA status is left for contributor review.
   
   See the [Contributor Guide](https://beam.apache.org/contribute) for more tips on [how to make review process smoother](https://github.com/apache/beam/blob/master/CONTRIBUTING.md#make-the-reviewers-job-easier).
   
   To check the build health, please visit [https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md](https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md)
   
   GitHub Actions Tests Status (on master branch)
   ------------------------------------------------------------------------------------------------
   [![Build python source distribution and wheels](https://github.com/apache/beam/actions/workflows/build_wheels.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Build+python+source+distribution+and+wheels%22+branch%3Amaster+event%3Aschedule)
   [![Python tests](https://github.com/apache/beam/actions/workflows/python_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Python+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Java tests](https://github.com/apache/beam/actions/workflows/java_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Java+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Go tests](https://github.com/apache/beam/actions/workflows/go_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Go+tests%22+branch%3Amaster+event%3Aschedule)
   
   See [CI.md](https://github.com/apache/beam/blob/master/CI.md) for more information about GitHub Actions CI or the [workflows README](https://github.com/apache/beam/blob/master/.github/workflows/README.md) to see a list of phrases to trigger workflows.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Python] Add typed decision questions and model adapters [beam]

Posted by "jrmccluskey (via GitHub)" <gi...@apache.org>.
jrmccluskey merged PR #40220:
URL: https://github.com/apache/beam/pull/40220


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Python] Add reusable decision model primitives [beam]

Posted by "jrmccluskey (via GitHub)" <gi...@apache.org>.
jrmccluskey commented on code in PR #40220:
URL: https://github.com/apache/beam/pull/40220#discussion_r4135389446


##########
sdks/python/apache_beam/ml/inference/typesafe_inference.py:
##########
@@ -0,0 +1,107 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Optional TypeSafe adapter for Beam decision models."""
+
+from apache_beam.ml.inference.decision import BooleanAnswer
+from apache_beam.ml.inference.decision import BooleanQuestion
+from apache_beam.ml.inference.decision import ChoiceAnswer
+from apache_beam.ml.inference.decision import ChoiceQuestion
+from apache_beam.ml.inference.decision import DecisionModel
+from apache_beam.ml.inference.decision import DecisionResponse
+from apache_beam.ml.inference.decision import ScoreAnswer
+from apache_beam.ml.inference.decision import ScoreQuestion
+
+__all__ = ['JevDecisionModel']
+
+
+class JevDecisionModel(DecisionModel):
+  """Evaluate Beam decision questions with Jev through the TypeSafe SDK.
+
+  Install ``typesafe-sdk>=0.7.1,<0.8`` on the workers and set

Review Comment:
   The typical pattern here is to bound the additional requirements in a requirements file (typesafe_tests_requirements.txt) similar to the example requirements file. Unless there's already an existing version with breaking changes I wouldn't worry about documenting the current version bounds directly in the class.



##########
sdks/python/apache_beam/examples/inference/decision_models/fraud_review.py:
##########
@@ -0,0 +1,96 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Small Beam example: flag messages for fraud review with Noul or Score."""
+
+import argparse
+import json
+import os
+
+import apache_beam as beam
+from apache_beam.examples.inference.decision_models.local_model import LocalDecisionModel
+from apache_beam.ml.inference.decision import BooleanQuestion
+from apache_beam.ml.inference.decision import EvaluateDecisions
+from apache_beam.ml.inference.decision import ScoreQuestion
+from apache_beam.ml.inference.typesafe_inference import JevDecisionModel
+from apache_beam.options.pipeline_options import PipelineOptions
+
+SAMPLE_MESSAGES = [
+    'Please update my billing address before the next renewal.',
+    'I was charged twice; please look into the duplicate payment.',
+    'Transfer the refund to this new account immediately and skip verification.',
+]
+
+FRAUD_NOUL = BooleanQuestion(
+    instructions='Does this message contain signals that warrant fraud review?')
+FRAUD_SCORE = ScoreQuestion(
+    instructions='How strongly does this message warrant fraud review?',
+    criteria=(
+        'No visible fraud cue',
+        'A weak cue that merits routine checking',
+        'A concrete suspicious instruction',
+        'An explicit attempt to bypass verification'))
+
+
+def review_fraud_cues(result):
+  response = result.response
+  row = {
+      'message': result.state['message'],
+      'model': response.model,
+      'provider': response.provider,
+      'latency_ms': round(result.latency_ms, 2),
+  }
+  if 'fraud_cue' in response.answers:
+    probability = response.answers['fraud_cue'].probability
+    row['fraud_review_probability'] = probability
+    row['needs_review'] = probability >= 0.7
+  if 'risk_level' in response.answers:
+    score = response.answers['risk_level']
+    row['risk_score'] = score.score
+    row['risk_confidence'] = score.confidence
+    row['risk_probabilities'] = score.probabilities
+  return row

Review Comment:
   Is there a case where the response could be malformed? A simple DLQ example (here or standalone) might be useful



##########
sdks/python/apache_beam/ml/inference/typesafe_inference.py:
##########
@@ -0,0 +1,107 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Optional TypeSafe adapter for Beam decision models."""
+
+from apache_beam.ml.inference.decision import BooleanAnswer
+from apache_beam.ml.inference.decision import BooleanQuestion
+from apache_beam.ml.inference.decision import ChoiceAnswer
+from apache_beam.ml.inference.decision import ChoiceQuestion
+from apache_beam.ml.inference.decision import DecisionModel
+from apache_beam.ml.inference.decision import DecisionResponse
+from apache_beam.ml.inference.decision import ScoreAnswer
+from apache_beam.ml.inference.decision import ScoreQuestion
+
+__all__ = ['JevDecisionModel']
+
+
+class JevDecisionModel(DecisionModel):
+  """Evaluate Beam decision questions with Jev through the TypeSafe SDK.
+
+  Install ``typesafe-sdk>=0.7.1,<0.8`` on the workers and set
+  ``TYPESAFE_API_KEY`` in their environment. The client is created when Beam
+  enters the adapter context; its HTTP pool is reused until teardown.
+  Choice and Score map directly to the SDK primitives. Boolean maps to Noul,
+  whose ``noul`` field becomes :attr:`BooleanAnswer.probability`.
+
+  Args:
+    model: TypeSafe model identifier, defaulting to ``jev-latest``.
+    timeout: Timeout in seconds for HTTP operations. The SDK handles retries.
+  """
+  def __init__(self, model='jev-latest', timeout=10.0):
+    self.model = model
+    self.timeout = timeout
+    self.client = None
+
+  def __enter__(self):
+    try:
+      from typesafe_sdk import TypeSafeClient
+    except ImportError as error:
+      raise ImportError(
+          'Install typesafe-sdk to use JevDecisionModel') from error
+    self.client = TypeSafeClient(timeout=self.timeout)
+    return self
+
+  def __exit__(self, exc_type, exc_value, traceback):
+    self.client.close()
+    self.client = None
+
+  def evaluate(self, state, questions):
+    if self.client is None:
+      raise RuntimeError('Enter JevDecisionModel before evaluating questions')
+    from typesafe_sdk import Choice
+    from typesafe_sdk import Noul
+    from typesafe_sdk import Score
+
+    sdk_questions = {}
+    for name, question in questions.items():
+      if isinstance(question, ChoiceQuestion):
+        sdk_questions[name] = Choice(
+            instructions=question.instructions, criteria=question.criteria)
+      elif isinstance(question, BooleanQuestion):
+        sdk_questions[name] = Noul(instructions=question.instructions)
+      elif isinstance(question, ScoreQuestion):
+        sdk_questions[name] = Score(
+            instructions=question.instructions, criteria=question.criteria)
+      else:
+        raise TypeError('Unsupported decision question: %r' % type(question))
+
+    response = self.client.system_one(
+        state=state, questions=sdk_questions, model=self.model)

Review Comment:
   Based on the doc string, this is a blocking call with nested retries. Is there a backoff mechanism built-in there as well? I do worry about the potential for 429 errors here in a Beam context



##########
sdks/python/apache_beam/examples/inference/decision_models/README.md:
##########
@@ -0,0 +1,262 @@
+<!--
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.
+-->
+
+# Beam decision models
+
+These examples use the reusable decision primitives in
+`apache_beam.ml.inference.decision`. A model evaluates named, typed questions
+for each Beam element. `EvaluateDecisions` returns the original state,
+normalized answers, provider metadata, and request latency. Policy and sinks
+remain ordinary Beam transforms after evaluation.
+
+## Public API
+
+The core module contains `ChoiceQuestion`, `BooleanQuestion`, and
+`ScoreQuestion`, their typed answers (`ChoiceAnswer`, `BooleanAnswer`, and
+`ScoreAnswer`), the `DecisionModel` ABC, and the `EvaluateDecisions`
+`PTransform`.
+
+| Question | Normalized answer |
+| --- | --- |
+| `ChoiceQuestion(instructions, criteria)` | `ChoiceAnswer.choice`, with optional label probabilities and confidence |
+| `BooleanQuestion(instructions)` | `BooleanAnswer.probability` in `[0, 1]` |
+| `ScoreQuestion(instructions, criteria)` | `ScoreAnswer.score` and `ScoreAnswer.probabilities`, keyed by zero-based integer level, with optional confidence |
+
+`JevDecisionModel` maps `BooleanQuestion` to Jev's `Noul`, returning
+`BooleanAnswer.probability`; a missing confidence is `None`.
+
+`DecisionModel` is the adapter ABC. A subclass implements
+`evaluate(state, questions)` and returns one matching typed answer per named
+question in a `DecisionResponse`. Override `__enter__` and `__exit__` to reuse
+a client, connection pool, or model weights. The transform enters the model
+during DoFn setup and closes it during teardown for each DoFn instance.
+
+`EvaluateDecisions(model, questions)` is a `PTransform` from input states to
+`DecisionResult`. Evaluation is synchronous, timestamps and windows are
+preserved, exceptions propagate to the runner, and request, failure, and
+latency metrics are recorded.
+
+## Architecture
+
+```mermaid
+flowchart LR
+  input["PCollection[state]"] --> evaluate["EvaluateDecisions(model, questions)<br/>PTransform"]
+  model["DecisionModel adapter"] --> evaluate
+  evaluate --> result["PCollection[DecisionResult]"]
+  result --> policy["route_message<br/>policy and sink selection"]
+  policy --> sink["JSONL files<br/>or BigQuery tables"]
+```
+
+![Rendered Beam message router graph](message_router.svg)
+
+The optional Jev adapter lives in
+`apache_beam.ml.inference.typesafe_inference`; the deterministic
+`LocalDecisionModel` stays in
+`apache_beam.examples.inference.decision_models.local_model`. Both implement
+the same core contract.
+
+## Integration
+
+Questions and events are regular Python values. The model is the only
+provider-specific argument to `EvaluateDecisions`:
+
+```python
+import apache_beam as beam
+
+from apache_beam.ml.inference.decision import ChoiceQuestion
+from apache_beam.ml.inference.decision import EvaluateDecisions
+from apache_beam.examples.inference.decision_models.local_model import (
+    LocalDecisionModel,
+)
+from apache_beam.ml.inference.typesafe_inference import JevDecisionModel
+
+questions = {
+    'team': ChoiceQuestion('Which team should handle this message?', {
+        'billing': 'Invoices', 'technical': 'Technical problems'}),
+}
+
+def select_team(result):
+  return result.response.answers['team'].choice
+
+model = LocalDecisionModel()
+# model = JevDecisionModel()
+
+with beam.Pipeline() as pipeline:
+  events = pipeline | 'Events' >> beam.Create(
+      [{'message': 'The API returns 503 after I rotated my key.'}])
+  decisions = events | 'Evaluate decisions' >> EvaluateDecisions(
+      model, questions)
+  rows = decisions | 'Apply downstream policy' >> beam.Map(select_team)
+```
+
+The downstream policy stays unchanged when swapping adapters. The Jev client
+is optional; install the existing example requirements and set
+`TYPESAFE_API_KEY` when running it.
+
+## Install
+
+From a Beam checkout, activate a virtual environment and install the core SDK:
+
+```sh
+python3 -m pip install -e sdks/python
+```
+
+Install the optional Jev client for `--model=jev`:
+
+```sh
+python3 -m pip install -r \
+  sdks/python/apache_beam/examples/inference/decision_models/requirements.txt
+```
+
+Install Beam's GCP extra for Pub/Sub or BigQuery sinks:
+
+```sh
+python3 -m pip install -e 'sdks/python[gcp]'
+```
+
+## Run examples
+
+The main demo uses a three-element `TestStream` and writes one JSONL file per
+destination:
+
+```sh
+output_dir="$(mktemp -d /tmp/beam-decision-model-output.XXXXXX)"
+python3 -m apache_beam.examples.inference.decision_models.message_router \
+  --model=local \
+  --output-dir="$output_dir" \
+  --graph="$output_dir/message_router.svg"
+find "$output_dir" -name '*.jsonl' -print -exec sed -n '1,3p' {} \;
+```
+
+Render the graph without running the job. The sink stays in the graph:
+
+```sh
+python3 -m apache_beam.examples.inference.decision_models.message_router \
+  --model=jev \
+  --graph-only \
+  --bq-dataset=PROJECT:DATASET \
+  --graph=/tmp/beam-decision-model.svg
+```
+
+The `.dot` export works without Graphviz; SVG and PNG require `dot` on `PATH`.
+
+Run the Jev path against the same stream with `TYPESAFE_API_KEY` set:
+
+```sh
+export TYPESAFE_API_KEY='replace-with-your-key'
+jev_output_dir="$(mktemp -d /tmp/beam-decision-model-jev-output.XXXXXX)"
+python3 -m apache_beam.examples.inference.decision_models.message_router \
+  --model=jev \
+  --min-confidence=0.65 \
+  --output-dir="$jev_output_dir" \
+  --graph="$jev_output_dir/message_router.svg"
+```
+
+For a streaming source, provide a Pub/Sub subscription containing JSON objects
+with `event_id` and `message` fields:
+
+```sh
+python3 -m apache_beam.examples.inference.decision_models.message_router \
+  --model=jev \
+  --pubsub-subscription=projects/PROJECT/subscriptions/SUBSCRIPTION \
+  --bq-dataset=PROJECT:DATASET
+```
+
+With `--bq-dataset=PROJECT:DATASET`, rows go to `messages_billing`,
+`messages_technical`, `messages_sales`, or `messages_review`; `--output-dir`
+writes local JSONL files. A normal run accepts one sink option.
+
+The fraud example prints one JSON row per sample message. Noul supplies the
+boolean probability; values at or above `0.7` are flagged:
+
+```sh
+python3 -m apache_beam.examples.inference.decision_models.fraud_review \
+  --model=local --primitive=noul
+python3 -m apache_beam.examples.inference.decision_models.fraud_review \
+  --model=local --primitive=both
+python3 -m apache_beam.examples.inference.decision_models.fraud_review \
+  --model=jev --primitive=both
+```
+
+A final three-element DirectRunner run returned these values. Beam may print
+the rows in a different order:
+
+| message | Noul probability | Score |
+| --- | ---: | ---: |
+| billing address | 0.42 | 0.80 |
+| duplicate charge | 0.32 | 0.85 |
+| bypass verification | 0.97 | 3.00 |
+
+Only the bypass verification message crossed the `0.7` review threshold.
+
+## Tests
+
+Install Beam's test dependencies in the same virtual environment:
+
+```sh
+python3 -m pip install -e 'sdks/python[test]'

Review Comment:
   same adjustment to the python subdirectory here



##########
sdks/python/apache_beam/examples/inference/decision_models/README.md:
##########
@@ -0,0 +1,262 @@
+<!--
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.
+-->
+
+# Beam decision models
+
+These examples use the reusable decision primitives in
+`apache_beam.ml.inference.decision`. A model evaluates named, typed questions
+for each Beam element. `EvaluateDecisions` returns the original state,
+normalized answers, provider metadata, and request latency. Policy and sinks
+remain ordinary Beam transforms after evaluation.
+
+## Public API
+
+The core module contains `ChoiceQuestion`, `BooleanQuestion`, and
+`ScoreQuestion`, their typed answers (`ChoiceAnswer`, `BooleanAnswer`, and
+`ScoreAnswer`), the `DecisionModel` ABC, and the `EvaluateDecisions`
+`PTransform`.
+
+| Question | Normalized answer |
+| --- | --- |
+| `ChoiceQuestion(instructions, criteria)` | `ChoiceAnswer.choice`, with optional label probabilities and confidence |
+| `BooleanQuestion(instructions)` | `BooleanAnswer.probability` in `[0, 1]` |
+| `ScoreQuestion(instructions, criteria)` | `ScoreAnswer.score` and `ScoreAnswer.probabilities`, keyed by zero-based integer level, with optional confidence |
+
+`JevDecisionModel` maps `BooleanQuestion` to Jev's `Noul`, returning
+`BooleanAnswer.probability`; a missing confidence is `None`.
+
+`DecisionModel` is the adapter ABC. A subclass implements
+`evaluate(state, questions)` and returns one matching typed answer per named
+question in a `DecisionResponse`. Override `__enter__` and `__exit__` to reuse
+a client, connection pool, or model weights. The transform enters the model
+during DoFn setup and closes it during teardown for each DoFn instance.
+
+`EvaluateDecisions(model, questions)` is a `PTransform` from input states to
+`DecisionResult`. Evaluation is synchronous, timestamps and windows are
+preserved, exceptions propagate to the runner, and request, failure, and
+latency metrics are recorded.
+
+## Architecture
+
+```mermaid
+flowchart LR
+  input["PCollection[state]"] --> evaluate["EvaluateDecisions(model, questions)<br/>PTransform"]
+  model["DecisionModel adapter"] --> evaluate
+  evaluate --> result["PCollection[DecisionResult]"]
+  result --> policy["route_message<br/>policy and sink selection"]
+  policy --> sink["JSONL files<br/>or BigQuery tables"]
+```
+
+![Rendered Beam message router graph](message_router.svg)
+
+The optional Jev adapter lives in
+`apache_beam.ml.inference.typesafe_inference`; the deterministic
+`LocalDecisionModel` stays in
+`apache_beam.examples.inference.decision_models.local_model`. Both implement
+the same core contract.
+
+## Integration
+
+Questions and events are regular Python values. The model is the only
+provider-specific argument to `EvaluateDecisions`:
+
+```python
+import apache_beam as beam
+
+from apache_beam.ml.inference.decision import ChoiceQuestion
+from apache_beam.ml.inference.decision import EvaluateDecisions
+from apache_beam.examples.inference.decision_models.local_model import (
+    LocalDecisionModel,
+)
+from apache_beam.ml.inference.typesafe_inference import JevDecisionModel
+
+questions = {
+    'team': ChoiceQuestion('Which team should handle this message?', {
+        'billing': 'Invoices', 'technical': 'Technical problems'}),
+}
+
+def select_team(result):
+  return result.response.answers['team'].choice
+
+model = LocalDecisionModel()
+# model = JevDecisionModel()
+
+with beam.Pipeline() as pipeline:
+  events = pipeline | 'Events' >> beam.Create(
+      [{'message': 'The API returns 503 after I rotated my key.'}])
+  decisions = events | 'Evaluate decisions' >> EvaluateDecisions(
+      model, questions)
+  rows = decisions | 'Apply downstream policy' >> beam.Map(select_team)
+```
+
+The downstream policy stays unchanged when swapping adapters. The Jev client
+is optional; install the existing example requirements and set
+`TYPESAFE_API_KEY` when running it.
+
+## Install
+
+From a Beam checkout, activate a virtual environment and install the core SDK:
+
+```sh
+python3 -m pip install -e sdks/python

Review Comment:
   prefer to include a `cd sdks/python` step here to match other instructions about installing Python requirements from the python subdirectory



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Python] Add reusable decision model primitives [beam]

Posted by "bvolpato (via GitHub)" <gi...@apache.org>.
bvolpato commented on PR #40220:
URL: https://github.com/apache/beam/pull/40220#issuecomment-5884057029

   Run PythonDocs PreCommit


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Python] Add reusable decision model primitives [beam]

Posted by "bvolpato (via GitHub)" <gi...@apache.org>.
bvolpato commented on code in PR #40220:
URL: https://github.com/apache/beam/pull/40220#discussion_r4239749051


##########
sdks/python/apache_beam/ml/inference/typesafe_inference.py:
##########
@@ -0,0 +1,107 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Optional TypeSafe adapter for Beam decision models."""
+
+from apache_beam.ml.inference.decision import BooleanAnswer
+from apache_beam.ml.inference.decision import BooleanQuestion
+from apache_beam.ml.inference.decision import ChoiceAnswer
+from apache_beam.ml.inference.decision import ChoiceQuestion
+from apache_beam.ml.inference.decision import DecisionModel
+from apache_beam.ml.inference.decision import DecisionResponse
+from apache_beam.ml.inference.decision import ScoreAnswer
+from apache_beam.ml.inference.decision import ScoreQuestion
+
+__all__ = ['JevDecisionModel']
+
+
+class JevDecisionModel(DecisionModel):
+  """Evaluate Beam decision questions with Jev through the TypeSafe SDK.
+
+  Install ``typesafe-sdk>=0.7.1,<0.8`` on the workers and set
+  ``TYPESAFE_API_KEY`` in their environment. The client is created when Beam
+  enters the adapter context; its HTTP pool is reused until teardown.
+  Choice and Score map directly to the SDK primitives. Boolean maps to Noul,
+  whose ``noul`` field becomes :attr:`BooleanAnswer.probability`.
+
+  Args:
+    model: TypeSafe model identifier, defaulting to ``jev-latest``.
+    timeout: Timeout in seconds for HTTP operations. The SDK handles retries.
+  """
+  def __init__(self, model='jev-latest', timeout=10.0):
+    self.model = model
+    self.timeout = timeout
+    self.client = None
+
+  def __enter__(self):
+    try:
+      from typesafe_sdk import TypeSafeClient
+    except ImportError as error:
+      raise ImportError(
+          'Install typesafe-sdk to use JevDecisionModel') from error
+    self.client = TypeSafeClient(timeout=self.timeout)
+    return self
+
+  def __exit__(self, exc_type, exc_value, traceback):
+    self.client.close()
+    self.client = None
+
+  def evaluate(self, state, questions):
+    if self.client is None:
+      raise RuntimeError('Enter JevDecisionModel before evaluating questions')
+    from typesafe_sdk import Choice
+    from typesafe_sdk import Noul
+    from typesafe_sdk import Score
+
+    sdk_questions = {}
+    for name, question in questions.items():
+      if isinstance(question, ChoiceQuestion):
+        sdk_questions[name] = Choice(
+            instructions=question.instructions, criteria=question.criteria)
+      elif isinstance(question, BooleanQuestion):
+        sdk_questions[name] = Noul(instructions=question.instructions)
+      elif isinstance(question, ScoreQuestion):
+        sdk_questions[name] = Score(
+            instructions=question.instructions, criteria=question.criteria)
+      else:
+        raise TypeError('Unsupported decision question: %r' % type(question))
+
+    response = self.client.system_one(
+        state=state, questions=sdk_questions, model=self.model)
+    answers = {}
+    for name, question in questions.items():
+      answer = response.answers[name]
+      if isinstance(question, ChoiceQuestion):
+        answers[name] = ChoiceAnswer(
+            choice=answer.choice,
+            probabilities=dict(answer.probabilities),
+            confidence=answer.confidence)
+      elif isinstance(question, BooleanQuestion):
+        answers[name] = BooleanAnswer(probability=answer.noul)
+      else:
+        answers[name] = ScoreAnswer(
+            score=answer.score,
+            probabilities={
+                int(level): probability
+                for level, probability in answer.probabilities.items()
+            },
+            confidence=answer.confidence)
+    return DecisionResponse(

Review Comment:
   Added validation for answer names and types, choice membership, numeric ranges, and probability keys. Malformed responses now raise `ValueError`, with regression tests. The focused suite passes with SDK 0.7.1 and 0.7.2.



##########
sdks/python/apache_beam/ml/inference/typesafe_inference.py:
##########
@@ -0,0 +1,107 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Optional TypeSafe adapter for Beam decision models."""
+
+from apache_beam.ml.inference.decision import BooleanAnswer
+from apache_beam.ml.inference.decision import BooleanQuestion
+from apache_beam.ml.inference.decision import ChoiceAnswer
+from apache_beam.ml.inference.decision import ChoiceQuestion
+from apache_beam.ml.inference.decision import DecisionModel
+from apache_beam.ml.inference.decision import DecisionResponse
+from apache_beam.ml.inference.decision import ScoreAnswer
+from apache_beam.ml.inference.decision import ScoreQuestion
+
+__all__ = ['JevDecisionModel']
+
+
+class JevDecisionModel(DecisionModel):
+  """Evaluate Beam decision questions with Jev through the TypeSafe SDK.
+
+  Install ``typesafe-sdk>=0.7.1,<0.8`` on the workers and set
+  ``TYPESAFE_API_KEY`` in their environment. The client is created when Beam
+  enters the adapter context; its HTTP pool is reused until teardown.
+  Choice and Score map directly to the SDK primitives. Boolean maps to Noul,
+  whose ``noul`` field becomes :attr:`BooleanAnswer.probability`.
+
+  Args:
+    model: TypeSafe model identifier, defaulting to ``jev-latest``.
+    timeout: Timeout in seconds for HTTP operations. The SDK handles retries.
+  """
+  def __init__(self, model='jev-latest', timeout=10.0):
+    self.model = model
+    self.timeout = timeout
+    self.client = None
+
+  def __enter__(self):
+    try:
+      from typesafe_sdk import TypeSafeClient
+    except ImportError as error:
+      raise ImportError(
+          'Install typesafe-sdk to use JevDecisionModel') from error
+    self.client = TypeSafeClient(timeout=self.timeout)
+    return self
+
+  def __exit__(self, exc_type, exc_value, traceback):
+    self.client.close()
+    self.client = None
+
+  def evaluate(self, state, questions):
+    if self.client is None:
+      raise RuntimeError('Enter JevDecisionModel before evaluating questions')
+    from typesafe_sdk import Choice
+    from typesafe_sdk import Noul
+    from typesafe_sdk import Score
+
+    sdk_questions = {}
+    for name, question in questions.items():
+      if isinstance(question, ChoiceQuestion):
+        sdk_questions[name] = Choice(
+            instructions=question.instructions, criteria=question.criteria)
+      elif isinstance(question, BooleanQuestion):
+        sdk_questions[name] = Noul(instructions=question.instructions)
+      elif isinstance(question, ScoreQuestion):
+        sdk_questions[name] = Score(
+            instructions=question.instructions, criteria=question.criteria)
+      else:
+        raise TypeError('Unsupported decision question: %r' % type(question))
+
+    response = self.client.system_one(
+        state=state, questions=sdk_questions, model=self.model)

Review Comment:
   Yes, the SDK already handles 429 and server errors with exponential backoff, jitter, and Retry-After support. I documented that calls block the processing thread and retries run independently across workers.



##########
sdks/python/apache_beam/ml/inference/typesafe_inference.py:
##########
@@ -0,0 +1,107 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Optional TypeSafe adapter for Beam decision models."""
+
+from apache_beam.ml.inference.decision import BooleanAnswer
+from apache_beam.ml.inference.decision import BooleanQuestion
+from apache_beam.ml.inference.decision import ChoiceAnswer
+from apache_beam.ml.inference.decision import ChoiceQuestion
+from apache_beam.ml.inference.decision import DecisionModel
+from apache_beam.ml.inference.decision import DecisionResponse
+from apache_beam.ml.inference.decision import ScoreAnswer
+from apache_beam.ml.inference.decision import ScoreQuestion
+
+__all__ = ['JevDecisionModel']
+
+
+class JevDecisionModel(DecisionModel):
+  """Evaluate Beam decision questions with Jev through the TypeSafe SDK.
+
+  Install ``typesafe-sdk>=0.7.1,<0.8`` on the workers and set

Review Comment:
   Moved the bounds into `typesafe_tests_requirements.txt`. The example requirements now use that same file.



##########
sdks/python/apache_beam/examples/inference/decision_models/fraud_review.py:
##########
@@ -0,0 +1,96 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Small Beam example: flag messages for fraud review with Noul or Score."""
+
+import argparse
+import json
+import os
+
+import apache_beam as beam
+from apache_beam.examples.inference.decision_models.local_model import LocalDecisionModel
+from apache_beam.ml.inference.decision import BooleanQuestion
+from apache_beam.ml.inference.decision import EvaluateDecisions
+from apache_beam.ml.inference.decision import ScoreQuestion
+from apache_beam.ml.inference.typesafe_inference import JevDecisionModel
+from apache_beam.options.pipeline_options import PipelineOptions
+
+SAMPLE_MESSAGES = [
+    'Please update my billing address before the next renewal.',
+    'I was charged twice; please look into the duplicate payment.',
+    'Transfer the refund to this new account immediately and skip verification.',
+]
+
+FRAUD_NOUL = BooleanQuestion(
+    instructions='Does this message contain signals that warrant fraud review?')
+FRAUD_SCORE = ScoreQuestion(
+    instructions='How strongly does this message warrant fraud review?',
+    criteria=(
+        'No visible fraud cue',
+        'A weak cue that merits routine checking',
+        'A concrete suspicious instruction',
+        'An explicit attempt to bypass verification'))
+
+
+def review_fraud_cues(result):
+  response = result.response
+  row = {
+      'message': result.state['message'],
+      'model': response.model,
+      'provider': response.provider,
+      'latency_ms': round(result.latency_ms, 2),
+  }
+  if 'fraud_cue' in response.answers:
+    probability = response.answers['fraud_cue'].probability
+    row['fraud_review_probability'] = probability
+    row['needs_review'] = probability >= 0.7
+  if 'risk_level' in response.answers:
+    score = response.answers['risk_level']
+    row['risk_score'] = score.score
+    row['risk_confidence'] = score.confidence
+    row['risk_probabilities'] = score.probabilities
+  return row

Review Comment:
   Added optional dead-letter handling and a fraud example that writes the original input and error to JSONL. Malformed responses can go there; transport failures still fail the pipeline after retries.



##########
sdks/python/apache_beam/examples/inference/decision_models/README.md:
##########
@@ -0,0 +1,262 @@
+<!--
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.
+-->
+
+# Beam decision models
+
+These examples use the reusable decision primitives in
+`apache_beam.ml.inference.decision`. A model evaluates named, typed questions
+for each Beam element. `EvaluateDecisions` returns the original state,
+normalized answers, provider metadata, and request latency. Policy and sinks
+remain ordinary Beam transforms after evaluation.
+
+## Public API
+
+The core module contains `ChoiceQuestion`, `BooleanQuestion`, and
+`ScoreQuestion`, their typed answers (`ChoiceAnswer`, `BooleanAnswer`, and
+`ScoreAnswer`), the `DecisionModel` ABC, and the `EvaluateDecisions`
+`PTransform`.
+
+| Question | Normalized answer |
+| --- | --- |
+| `ChoiceQuestion(instructions, criteria)` | `ChoiceAnswer.choice`, with optional label probabilities and confidence |
+| `BooleanQuestion(instructions)` | `BooleanAnswer.probability` in `[0, 1]` |
+| `ScoreQuestion(instructions, criteria)` | `ScoreAnswer.score` and `ScoreAnswer.probabilities`, keyed by zero-based integer level, with optional confidence |
+
+`JevDecisionModel` maps `BooleanQuestion` to Jev's `Noul`, returning
+`BooleanAnswer.probability`; a missing confidence is `None`.
+
+`DecisionModel` is the adapter ABC. A subclass implements
+`evaluate(state, questions)` and returns one matching typed answer per named
+question in a `DecisionResponse`. Override `__enter__` and `__exit__` to reuse
+a client, connection pool, or model weights. The transform enters the model
+during DoFn setup and closes it during teardown for each DoFn instance.
+
+`EvaluateDecisions(model, questions)` is a `PTransform` from input states to
+`DecisionResult`. Evaluation is synchronous, timestamps and windows are
+preserved, exceptions propagate to the runner, and request, failure, and
+latency metrics are recorded.
+
+## Architecture
+
+```mermaid
+flowchart LR
+  input["PCollection[state]"] --> evaluate["EvaluateDecisions(model, questions)<br/>PTransform"]
+  model["DecisionModel adapter"] --> evaluate
+  evaluate --> result["PCollection[DecisionResult]"]
+  result --> policy["route_message<br/>policy and sink selection"]
+  policy --> sink["JSONL files<br/>or BigQuery tables"]
+```
+
+![Rendered Beam message router graph](message_router.svg)
+
+The optional Jev adapter lives in
+`apache_beam.ml.inference.typesafe_inference`; the deterministic
+`LocalDecisionModel` stays in
+`apache_beam.examples.inference.decision_models.local_model`. Both implement
+the same core contract.
+
+## Integration
+
+Questions and events are regular Python values. The model is the only
+provider-specific argument to `EvaluateDecisions`:
+
+```python
+import apache_beam as beam
+
+from apache_beam.ml.inference.decision import ChoiceQuestion
+from apache_beam.ml.inference.decision import EvaluateDecisions
+from apache_beam.examples.inference.decision_models.local_model import (
+    LocalDecisionModel,
+)
+from apache_beam.ml.inference.typesafe_inference import JevDecisionModel
+
+questions = {
+    'team': ChoiceQuestion('Which team should handle this message?', {
+        'billing': 'Invoices', 'technical': 'Technical problems'}),
+}
+
+def select_team(result):
+  return result.response.answers['team'].choice
+
+model = LocalDecisionModel()
+# model = JevDecisionModel()
+
+with beam.Pipeline() as pipeline:
+  events = pipeline | 'Events' >> beam.Create(
+      [{'message': 'The API returns 503 after I rotated my key.'}])
+  decisions = events | 'Evaluate decisions' >> EvaluateDecisions(
+      model, questions)
+  rows = decisions | 'Apply downstream policy' >> beam.Map(select_team)
+```
+
+The downstream policy stays unchanged when swapping adapters. The Jev client
+is optional; install the existing example requirements and set
+`TYPESAFE_API_KEY` when running it.
+
+## Install
+
+From a Beam checkout, activate a virtual environment and install the core SDK:
+
+```sh
+python3 -m pip install -e sdks/python

Review Comment:
   Added `cd sdks/python` and adjusted the install paths.



##########
sdks/python/apache_beam/examples/inference/decision_models/README.md:
##########
@@ -0,0 +1,262 @@
+<!--
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.
+-->
+
+# Beam decision models
+
+These examples use the reusable decision primitives in
+`apache_beam.ml.inference.decision`. A model evaluates named, typed questions
+for each Beam element. `EvaluateDecisions` returns the original state,
+normalized answers, provider metadata, and request latency. Policy and sinks
+remain ordinary Beam transforms after evaluation.
+
+## Public API
+
+The core module contains `ChoiceQuestion`, `BooleanQuestion`, and
+`ScoreQuestion`, their typed answers (`ChoiceAnswer`, `BooleanAnswer`, and
+`ScoreAnswer`), the `DecisionModel` ABC, and the `EvaluateDecisions`
+`PTransform`.
+
+| Question | Normalized answer |
+| --- | --- |
+| `ChoiceQuestion(instructions, criteria)` | `ChoiceAnswer.choice`, with optional label probabilities and confidence |
+| `BooleanQuestion(instructions)` | `BooleanAnswer.probability` in `[0, 1]` |
+| `ScoreQuestion(instructions, criteria)` | `ScoreAnswer.score` and `ScoreAnswer.probabilities`, keyed by zero-based integer level, with optional confidence |
+
+`JevDecisionModel` maps `BooleanQuestion` to Jev's `Noul`, returning
+`BooleanAnswer.probability`; a missing confidence is `None`.
+
+`DecisionModel` is the adapter ABC. A subclass implements
+`evaluate(state, questions)` and returns one matching typed answer per named
+question in a `DecisionResponse`. Override `__enter__` and `__exit__` to reuse
+a client, connection pool, or model weights. The transform enters the model
+during DoFn setup and closes it during teardown for each DoFn instance.
+
+`EvaluateDecisions(model, questions)` is a `PTransform` from input states to
+`DecisionResult`. Evaluation is synchronous, timestamps and windows are
+preserved, exceptions propagate to the runner, and request, failure, and
+latency metrics are recorded.
+
+## Architecture
+
+```mermaid
+flowchart LR
+  input["PCollection[state]"] --> evaluate["EvaluateDecisions(model, questions)<br/>PTransform"]
+  model["DecisionModel adapter"] --> evaluate
+  evaluate --> result["PCollection[DecisionResult]"]
+  result --> policy["route_message<br/>policy and sink selection"]
+  policy --> sink["JSONL files<br/>or BigQuery tables"]
+```
+
+![Rendered Beam message router graph](message_router.svg)
+
+The optional Jev adapter lives in
+`apache_beam.ml.inference.typesafe_inference`; the deterministic
+`LocalDecisionModel` stays in
+`apache_beam.examples.inference.decision_models.local_model`. Both implement
+the same core contract.
+
+## Integration
+
+Questions and events are regular Python values. The model is the only
+provider-specific argument to `EvaluateDecisions`:
+
+```python
+import apache_beam as beam
+
+from apache_beam.ml.inference.decision import ChoiceQuestion
+from apache_beam.ml.inference.decision import EvaluateDecisions
+from apache_beam.examples.inference.decision_models.local_model import (
+    LocalDecisionModel,
+)
+from apache_beam.ml.inference.typesafe_inference import JevDecisionModel
+
+questions = {
+    'team': ChoiceQuestion('Which team should handle this message?', {
+        'billing': 'Invoices', 'technical': 'Technical problems'}),
+}
+
+def select_team(result):
+  return result.response.answers['team'].choice
+
+model = LocalDecisionModel()
+# model = JevDecisionModel()
+
+with beam.Pipeline() as pipeline:
+  events = pipeline | 'Events' >> beam.Create(
+      [{'message': 'The API returns 503 after I rotated my key.'}])
+  decisions = events | 'Evaluate decisions' >> EvaluateDecisions(
+      model, questions)
+  rows = decisions | 'Apply downstream policy' >> beam.Map(select_team)
+```
+
+The downstream policy stays unchanged when swapping adapters. The Jev client
+is optional; install the existing example requirements and set
+`TYPESAFE_API_KEY` when running it.
+
+## Install
+
+From a Beam checkout, activate a virtual environment and install the core SDK:
+
+```sh
+python3 -m pip install -e sdks/python
+```
+
+Install the optional Jev client for `--model=jev`:
+
+```sh
+python3 -m pip install -r \
+  sdks/python/apache_beam/examples/inference/decision_models/requirements.txt
+```
+
+Install Beam's GCP extra for Pub/Sub or BigQuery sinks:
+
+```sh
+python3 -m pip install -e 'sdks/python[gcp]'
+```
+
+## Run examples
+
+The main demo uses a three-element `TestStream` and writes one JSONL file per
+destination:
+
+```sh
+output_dir="$(mktemp -d /tmp/beam-decision-model-output.XXXXXX)"
+python3 -m apache_beam.examples.inference.decision_models.message_router \
+  --model=local \
+  --output-dir="$output_dir" \
+  --graph="$output_dir/message_router.svg"
+find "$output_dir" -name '*.jsonl' -print -exec sed -n '1,3p' {} \;
+```
+
+Render the graph without running the job. The sink stays in the graph:
+
+```sh
+python3 -m apache_beam.examples.inference.decision_models.message_router \
+  --model=jev \
+  --graph-only \
+  --bq-dataset=PROJECT:DATASET \
+  --graph=/tmp/beam-decision-model.svg
+```
+
+The `.dot` export works without Graphviz; SVG and PNG require `dot` on `PATH`.
+
+Run the Jev path against the same stream with `TYPESAFE_API_KEY` set:
+
+```sh
+export TYPESAFE_API_KEY='replace-with-your-key'
+jev_output_dir="$(mktemp -d /tmp/beam-decision-model-jev-output.XXXXXX)"
+python3 -m apache_beam.examples.inference.decision_models.message_router \
+  --model=jev \
+  --min-confidence=0.65 \
+  --output-dir="$jev_output_dir" \
+  --graph="$jev_output_dir/message_router.svg"
+```
+
+For a streaming source, provide a Pub/Sub subscription containing JSON objects
+with `event_id` and `message` fields:
+
+```sh
+python3 -m apache_beam.examples.inference.decision_models.message_router \
+  --model=jev \
+  --pubsub-subscription=projects/PROJECT/subscriptions/SUBSCRIPTION \
+  --bq-dataset=PROJECT:DATASET
+```
+
+With `--bq-dataset=PROJECT:DATASET`, rows go to `messages_billing`,
+`messages_technical`, `messages_sales`, or `messages_review`; `--output-dir`
+writes local JSONL files. A normal run accepts one sink option.
+
+The fraud example prints one JSON row per sample message. Noul supplies the
+boolean probability; values at or above `0.7` are flagged:
+
+```sh
+python3 -m apache_beam.examples.inference.decision_models.fraud_review \
+  --model=local --primitive=noul
+python3 -m apache_beam.examples.inference.decision_models.fraud_review \
+  --model=local --primitive=both
+python3 -m apache_beam.examples.inference.decision_models.fraud_review \
+  --model=jev --primitive=both
+```
+
+A final three-element DirectRunner run returned these values. Beam may print
+the rows in a different order:
+
+| message | Noul probability | Score |
+| --- | ---: | ---: |
+| billing address | 0.42 | 0.80 |
+| duplicate charge | 0.32 | 0.85 |
+| bypass verification | 0.97 | 3.00 |
+
+Only the bypass verification message crossed the `0.7` review threshold.
+
+## Tests
+
+Install Beam's test dependencies in the same virtual environment:
+
+```sh
+python3 -m pip install -e 'sdks/python[test]'

Review Comment:
   Updated the test commands to start from `sdks/python` too, with paths relative to that directory.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Python] Add typed decision questions and model adapters [beam]

Posted by "jrmccluskey (via GitHub)" <gi...@apache.org>.
jrmccluskey commented on code in PR #40220:
URL: https://github.com/apache/beam/pull/40220#discussion_r4262952914


##########
sdks/python/apache_beam/examples/inference/decision_models/requirements.txt:
##########
@@ -16,4 +16,4 @@
 #
 
 # Optional client for apache_beam.ml.inference.typesafe_inference.
-typesafe-sdk>=0.7.1,<0.8
+-r ../../../ml/inference/typesafe_tests_requirements.txt

Review Comment:
   It's okay to leave this as a hard-coded package number rather than pointing to the requirements file, but not a big deal either way



##########
sdks/python/tox.ini:
##########
@@ -121,6 +121,7 @@ commands =
 # Don't set TMPDIR to avoid "AF_UNIX path too long" errors in certain tests.
 deps =
   accelerate>=1.6.0
+  -r{toxinidir}/apache_beam/ml/inference/typesafe_tests_requirements.txt

Review Comment:
   I don't love incorporating the test dependency at this level, I'd prefer this either gets added to the p312_ml_test extras directly if this is the target python version to support. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Python] Add typed decision questions and model adapters [beam]

Posted by "bvolpato (via GitHub)" <gi...@apache.org>.
bvolpato commented on code in PR #40220:
URL: https://github.com/apache/beam/pull/40220#discussion_r4279190452


##########
sdks/python/tox.ini:
##########
@@ -121,6 +121,7 @@ commands =
 # Don't set TMPDIR to avoid "AF_UNIX path too long" errors in certain tests.
 deps =
   accelerate>=1.6.0
+  -r{toxinidir}/apache_beam/ml/inference/typesafe_tests_requirements.txt

Review Comment:
   Thanks, that makes sense! Moved it into `p312_ml_test` and removed the tox entry.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Python] Add reusable decision model primitives [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #40220:
URL: https://github.com/apache/beam/pull/40220#issuecomment-5788970781

   Assigning reviewers:
   
   R: @jrmccluskey for label python.
   
   
   Note: If you would like to opt out of this review, comment `assign to next reviewer`.
   
   Available commands:
   - `stop reviewer notifications` - opt out of the automated review tooling
   - `remind me after tests pass` - tag the comment author after tests pass
   - `waiting on author` - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)
   
   The PR bot will only process comments in the main thread (not review comments).


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Python] Add reusable decision model primitives [beam]

Posted by "IRONICBo (via GitHub)" <gi...@apache.org>.
IRONICBo commented on code in PR #40220:
URL: https://github.com/apache/beam/pull/40220#discussion_r4159327615


##########
sdks/python/apache_beam/ml/inference/typesafe_inference.py:
##########
@@ -0,0 +1,107 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Optional TypeSafe adapter for Beam decision models."""
+
+from apache_beam.ml.inference.decision import BooleanAnswer
+from apache_beam.ml.inference.decision import BooleanQuestion
+from apache_beam.ml.inference.decision import ChoiceAnswer
+from apache_beam.ml.inference.decision import ChoiceQuestion
+from apache_beam.ml.inference.decision import DecisionModel
+from apache_beam.ml.inference.decision import DecisionResponse
+from apache_beam.ml.inference.decision import ScoreAnswer
+from apache_beam.ml.inference.decision import ScoreQuestion
+
+__all__ = ['JevDecisionModel']
+
+
+class JevDecisionModel(DecisionModel):
+  """Evaluate Beam decision questions with Jev through the TypeSafe SDK.
+
+  Install ``typesafe-sdk>=0.7.1,<0.8`` on the workers and set
+  ``TYPESAFE_API_KEY`` in their environment. The client is created when Beam
+  enters the adapter context; its HTTP pool is reused until teardown.
+  Choice and Score map directly to the SDK primitives. Boolean maps to Noul,
+  whose ``noul`` field becomes :attr:`BooleanAnswer.probability`.
+
+  Args:
+    model: TypeSafe model identifier, defaulting to ``jev-latest``.
+    timeout: Timeout in seconds for HTTP operations. The SDK handles retries.
+  """
+  def __init__(self, model='jev-latest', timeout=10.0):
+    self.model = model
+    self.timeout = timeout
+    self.client = None
+
+  def __enter__(self):
+    try:
+      from typesafe_sdk import TypeSafeClient
+    except ImportError as error:
+      raise ImportError(
+          'Install typesafe-sdk to use JevDecisionModel') from error
+    self.client = TypeSafeClient(timeout=self.timeout)
+    return self
+
+  def __exit__(self, exc_type, exc_value, traceback):
+    self.client.close()
+    self.client = None
+
+  def evaluate(self, state, questions):
+    if self.client is None:
+      raise RuntimeError('Enter JevDecisionModel before evaluating questions')
+    from typesafe_sdk import Choice
+    from typesafe_sdk import Noul
+    from typesafe_sdk import Score
+
+    sdk_questions = {}
+    for name, question in questions.items():
+      if isinstance(question, ChoiceQuestion):
+        sdk_questions[name] = Choice(
+            instructions=question.instructions, criteria=question.criteria)
+      elif isinstance(question, BooleanQuestion):
+        sdk_questions[name] = Noul(instructions=question.instructions)
+      elif isinstance(question, ScoreQuestion):
+        sdk_questions[name] = Score(
+            instructions=question.instructions, criteria=question.criteria)
+      else:
+        raise TypeError('Unsupported decision question: %r' % type(question))
+
+    response = self.client.system_one(
+        state=state, questions=sdk_questions, model=self.model)
+    answers = {}
+    for name, question in questions.items():
+      answer = response.answers[name]
+      if isinstance(question, ChoiceQuestion):
+        answers[name] = ChoiceAnswer(
+            choice=answer.choice,
+            probabilities=dict(answer.probabilities),
+            confidence=answer.confidence)
+      elif isinstance(question, BooleanQuestion):
+        answers[name] = BooleanAnswer(probability=answer.noul)
+      else:
+        answers[name] = ScoreAnswer(
+            score=answer.score,
+            probabilities={
+                int(level): probability
+                for level, probability in answer.probabilities.items()
+            },
+            confidence=answer.confidence)
+    return DecisionResponse(

Review Comment:
   The public adapter contract says choice labels belong to the submitted criteria and numeric fields stay in range, but this path copies the SDK response directly. `typesafe-sdk` 0.7.1 describes those invariants without enforcing them or binding a `ChoiceAnswer` to its request, so an unknown choice, `noul=1.4`, or out-of-rubric score becomes a successful `DecisionResult`; only the demo rechecks one case. Please validate keys/types, membership, ranges, and probability keys here, with malformed-response tests. Jev Social, which I maintain, uses this same boundary before typed output can drive execution.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Python] Add reusable decision model primitives [beam]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #40220:
URL: https://github.com/apache/beam/pull/40220#issuecomment-6103080244

   ## [Codecov](https://app.codecov.io/gh/apache/beam/pull/40220?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `66.47059%` with `57 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 56.24%. Comparing base ([`2906a89`](https://app.codecov.io/gh/apache/beam/commit/2906a89f93adb735063bc1e23f6f769f0ed93167?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`c8b3a97`](https://app.codecov.io/gh/apache/beam/commit/c8b3a97d54c0c80b99995c12f38e77edf5c2cb5d?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 186 commits behind head on master.
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/beam/pull/40220?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [...hon/apache\_beam/ml/inference/typesafe\_inference.py](https://app.codecov.io/gh/apache/beam/pull/40220?src=pr&el=tree&filepath=sdks%2Fpython%2Fapache_beam%2Fml%2Finference%2Ftypesafe_inference.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vbWwvaW5mZXJlbmNlL3R5cGVzYWZlX2luZmVyZW5jZS5weQ==) | 25.33% | [56 Missing :warning: ](https://app.codecov.io/gh/apache/beam/pull/40220?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [sdks/python/apache\_beam/ml/inference/decision.py](https://app.codecov.io/gh/apache/beam/pull/40220?src=pr&el=tree&filepath=sdks%2Fpython%2Fapache_beam%2Fml%2Finference%2Fdecision.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vbWwvaW5mZXJlbmNlL2RlY2lzaW9uLnB5) | 98.94% | [1 Missing :warning: ](https://app.codecov.io/gh/apache/beam/pull/40220?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@             Coverage Diff              @@
   ##             master   #40220      +/-   ##
   ============================================
   + Coverage     56.15%   56.24%   +0.09%     
     Complexity     2288     2288              
   ============================================
     Files          1121     1126       +5     
     Lines        177161   178509    +1348     
     Branches       1488     1488              
   ============================================
   + Hits          99476   100400     +924     
   - Misses        75161    75585     +424     
     Partials       2524     2524              
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/beam/pull/40220/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [python](https://app.codecov.io/gh/apache/beam/pull/40220/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `79.66% <66.47%> (-0.19%)` | :arrow_down: |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   </details>
   
   [:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/beam/pull/40220?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org