Skip to content

Move the tutorial to the current Python AI SDK (launchdarkly-ai-server 1.1.0) - #29

Open
sattensil wants to merge 31 commits into
mainfrom
sdk-roll-forward-1x
Open

sattensil wants to merge 31 commits into
mainfrom
sdk-roll-forward-1x

Conversation

@sattensil

@sattensil sattensil commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Moves main (Parts 1 and 3 of the multi-agent tutorial series) to the current Python AI SDK, launchdarkly-ai-server 1.1.0.

What changed

  • SDK: launchdarkly-ai-server>=1.1.0 and launchdarkly-server-sdk>=9.18.4, Python 3.12 or later. Agents evaluate configs with inspect_config and run model calls through create_handler and execute_and_track.
  • Models: claude-haiku-5-5, claude-sonnet-5-5, claude-opus-5-5, gpt-6.2-sol, gpt-6.1-terra, and gpt-6-luna. Hardcoded temperature arguments are removed.
  • AgentControl naming: README and the tutorial docs use the AgentControl name and the current UI labels.
  • Academic search: Semantic Scholar is replaced by the official OpenAlex MCP server (openalex_search). Sign in once with uv run python tools_impl/openalex_auth.py. Without a sign-in, the app runs and skips openalex_search.
  • Simplification: a pass over the whole codebase removes unused code and duplicate paths while keeping the tutorial structure.
  • Fixes:
    • Each variation's max_tool_calls is enforced, and a reached limit comes back as an answer.
    • The support agent never sees raw PII. Empty or failed redaction, or a failed security agent, withholds the input.
    • Conversation history keeps the redacted text of earlier turns, not the raw input.
    • If LaunchDarkly is unreachable or a config isn't served, the app answers from .ai_config_defaults.json.
    • Concurrent requests share one OpenAlex token refresh.
  • Unit tests: 24 tests under tests/ cover the tool limit, the PII boundary, fallback, tracking, OpenAlex tokens, bootstrap payloads, and Bedrock model IDs. Run them with uv run pytest.
  • CI workflow: unchanged from main.

How it was tested

From a fresh clone in a clean shell, against a throwaway LaunchDarkly project: uv sync, uv run pytest, bootstrap, segment targeting (4 of 4), Part 1 end to end including openalex_search, the Streamlit UI with feedback, the Part 3 traffic generator, fallback, and monitoring under the variation keys that served each request.

Known issues

  • The strict-security variation uses Mistral. When Mistral rate-limits, the security agent fails closed as designed.
  • LaunchDarkly's built-in cost metric reports 0 for these models, so the custom ai_cost_per_request event stays.

Replace LDAIClient with launchdarkly-ai-server across the supervisor, security,
and support agents. There is no tracker object any more, so every call that used
to be wrapped in create_tracker()/track_* now runs inside a create_handler()
passed to execute_and_track(), which emits the $ld:ai:* duration, token, and
success/error events itself.

The runtime fallback stays. .ai_config_defaults.json is committed here and is
the worked example of ld-aic-cicd's runtime-defaults feature, but the SDK
dropped the `default=` parameter that used to apply it. So ConfigManager applies
it instead: inspect_config() never raises and reports enabled=False on any
failure, which gives one clean branch between a served config and the local
defaults. The defaults are validated with the SDK's own parse_ai_config rather
than trusted, so a stale or corrupt file now fails loudly with the ld-aic
command needed to regenerate it.

The fallback file also had a shape bug. LaunchDarkly serves tools inside
model.parameters.tools with no top-level `tools` key, which was confirmed by
reading the raw support-agent variation. ld-aic reads them from there but writes
them to the top level, so the fallback did not match what the app receives. That
broke twice over: this app reads its tools from model.parameters, so the agents
would have had no tools at all whenever the fallback was used, and the SDK
validates a top-level `tools` key as an object, so the array failed parsing for
a key the live payload never sends. _normalize_tools moves it, and the fallback
now behaves exactly like a served config. Drop the shim once ld-aic writes tools
under model.parameters.

Metrics attribution improved in three places. get_config was being called twice
per request, once to build the agent and once for tracking, which cost an extra
evaluation and could attribute metrics to a different variation than the one
that ran; the served config is now reused. Cost events carry the track_data
returned by the tracked call, so a cost ties to its generation by runId. And the
variation key comes from public variation metadata instead of the private
tracker._variation_key, which was read behind a hasattr guard that would have
silently logged "VARIATION NOT FOUND" if it were ever renamed.

Two things deliberately do not emit events. Hitting the configured tool ceiling
is caught inside the handler, because letting MaxToolCallsExceeded escape would
record a generation:error for what the code calls expected behaviour. And the
supervisor no longer records an error when a child agent fails, since the child
already records one against its own config.

Feedback is emitted directly through client.track. The SDK has no feedback API,
so the legacy $ld:ai:feedback:user:* event keys are kept byte-identical to avoid
breaking the existing metrics.

Fixed along the way: flush_metrics() called close(), which is now a coroutine
and would have built one without flushing anything; clear_cache() ran at startup
before the lazily-initialized client existed; and utils/metrics.py was deleted
rather than ported, because nothing imported it and every function called a
ConfigManager.track_metrics that never existed.

Verified offline by importing all seven changed modules and evaluating all three
configs against an invalid SDK key, which exercises the fallback path end to end
and confirms support-agent's three tools land under model.parameters.

Requires Python 3.12+, the launchdarkly-ai-server floor; .python-version pinned
3.11 and blocked the lock.


Pinned to launchdarkly-ai-server 0.2.4, the current release. Nothing this
migration relies on changed in it, and parse_usage still reports zero for a
provider native token spelling, so the explicit key renaming is still needed.

The AI Config validation workflow was still installing launchdarkly-server-sdk-ai
and pinning the validator at scarlett_ai_configs_ci_cd- 02cb9b1, which is that
repo's pre-migration commit. Both would have failed against this branch: the
legacy package does not provide launchdarkly_ai_server, and the old validator
reads configs as objects. The workflow now installs launchdarkly-ai-server 0.2.4
and pins the validator at 12c5509.

That pin means ld-aic-cicd has to be pushed before this branch's CI can pass.
get_config never returns a disabled config: anything LaunchDarkly doesn't
serve comes from .ai_config_defaults.json instead. The security agent's
branch would also have passed the raw message on as the redacted text.
…chDarkly Trace and Monitoring links, and increase search_v2 snippet size

@jeffdupont jeffdupont left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this. The move to launchdarkly-ai-server 1.1.0 is right: I checked every SDK import, call and return shape against the 1.1.0 release, and they match (init_client, inspect_config, execute_and_track, create_handler, parse_ai_config). No old SDK names are left, and the README and tutorials match the code.

Two things to fix before merge:

  1. CI still installs the old SDK. .github/workflows/ai-config-validation.yml (lines 59, 166 and 403) still installs launchdarkly-server-sdk-ai and semanticscholar, which this PR removes, never installs launchdarkly-ai-server[otel], and still clones the Semantic Scholar MCP server (line 202). Installs probably pass because nothing imports the old packages, but CI no longer tests what a real install gets. Could it install from pyproject.toml (or list launchdarkly-ai-server[otel]) and drop the Semantic Scholar clone?
  2. A private SDK function (inline).

Small ones: AGENTS.md line 17 still says there is no unit-test suite and tests/ is gitignored, but this PR adds the tests and wires up pytest. And a note on #30: it changes many of the same files with a different approach (graph resolution and a hand-built tracker, configs as plain dicts, and no [otel] extra), so whichever merges second needs a full rebase. Worth choosing one direction first.

Comment thread config_manager.py Outdated
text_message,
to_ld_context,
)
from launchdarkly_ai_server.lifecycle import _flush_tracer_provider

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_flush_tracer_provider is private to the SDK: it is not exported from launchdarkly_ai_server, only defined in lifecycle.py. With >=1.1.0 unbounded, a minor release can rename it and flush_traces() / flush_metrics() would break. Could this pin an upper bound, guard it with getattr, or use a public flush instead?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replaced _flush_tracer_provider in 9e0bb9a with a guarded call to the public OpenTelemetry trace.get_tracer_provider().force_flush() (getattr(..., "force_flush", None)), covered by test_flush_traces_uses_public_otel_provider.

Comment thread bootstrap/create_configs.py Outdated
print(f" 🔧 Using modelConfigKey: {model_config_key}")
else:
payload["modelName"] = model_id
payload["provider"] = {"name": model_config["provider"].title()}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: .title() turns openai into Openai here. It only runs for models missing from the key map, but an explicit provider-name map would avoid it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replaced .title() with an explicit provider_name_map ("openai" -> "OpenAI", "xai" -> "xAI", etc.) in 9e0bb9a, covered by test_unmapped_provider_fallback_uses_canonical_provider_casing.

Co-authored-by: Cursor <cursoragent@cursor.com>
@sattensil

Copy link
Copy Markdown
Collaborator Author

Addressed all four review items in 9e0bb9a:

  1. CI workflow (.github/workflows/ai-config-validation.yml): Switched all three jobs to uv sync --frozen || uv sync so CI installs directly from pyproject.toml (including launchdarkly-ai-server[otel]>=1.1.0, without launchdarkly-server-sdk-ai or semanticscholar), moved ld-aic into an isolated uv tool install environment, added uv run pytest to validate-configs, and dropped the Semantic Scholar MCP server clone.
  2. Span flush (config_manager.py): Removed the private _flush_tracer_provider import and switched flush_traces() / flush_metrics() to the public OpenTelemetry trace.get_tracer_provider().force_flush() guarded with getattr.
  3. Provider fallback casing (bootstrap/create_configs.py): Replaced .title() with an explicit canonical provider_name_map ("openai" -> "OpenAI", etc.).
  4. AGENTS.md: Updated the Verification section to document the offline tests/ suite (uv run pytest) alongside the end-to-end check and CI workflow.

@sattensil
sattensil requested a review from jeffdupont November 20, 2026 17:27

@jeffdupont jeffdupont left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update. All four of my earlier points are fixed: CI now installs the project's locked launchdarkly-ai-server[otel] with uv sync (the old SDK stays only in the isolated ld-aic tool), the tracer flush goes through the public provider's force_flush(), AGENTS.md describes the new test suite, and provider names use the canonical mapping with a regression test.

One should-fix left, plus two small nits, inline.

Comment thread tests/test_config_and_tracking.py Outdated


async def test_sdk_tool_handlers_emit_tool_call_events_and_render_templates(monkeypatch):
from launchdarkly_ai_server.lifecycle import _reset_for_testing, _set_client_for_testing

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should fix: _reset_for_testing and _set_client_for_testing are private helpers of the SDK, and launchdarkly-ai-server[otel]>=1.1.0 is unbounded, so a later release can drop them and break CI. The public API covers this: await init_client(client=fake_ld) to inject the fake client, and await shutdown() to reset afterwards (both in the 1.1.0 public API).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 393f954 — replaced private _set_client_for_testing/_reset_for_testing (and submodule tracking.parse_usage) in tests/test_config_and_tracking.py with public await init_client(client=fake_ld), await shutdown(), and launchdarkly_ai_server.parse_usage.

Comment thread README.md Outdated

**PII Detection Test:**
"My email is john.doe@example.com and I need help"
Click **▶ Security Check**, or paste:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the README names the buttons with a ▶ prefix here and at :564, but the buttons in ui/chat_interface.py:402-415 (and the new screenshot) have no arrow.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 393f954 — removed the ▶ prefix on Security Check and Basic Search in README.md (and on OpenAlex Research in tutorial_2.md) to match ui/chat_interface.py.

Comment thread ui/chat_interface.py Outdated

.example-queries-container {
padding: 0.25rem 0;
.header-title {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this mobile rule can't win over .slide h1.header-title { font-size: 2.35rem; } at lines 141-149, which has a more specific selector, so the smaller mobile title never applies. Using .slide h1.header-title in the media query fixes it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 393f954 — updated the @media (max-width: 768px) selector to .slide h1.header-title so it overrides the desktop rule.

…tton/mobile styles

Co-authored-by: Cursor <cursoragent@cursor.com>

@jeffdupont jeffdupont left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, all three of my round-2 items are fixed: the tests now use the public init_client(client=...) and shutdown(), the README button names match the UI, and the mobile title rule now wins on specificity.

One optional nit inline.

Comment thread config_manager.py Outdated
text_message,
to_ld_context,
)
from launchdarkly_ai_server.tracking import make_track_data

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: make_track_data is exported from the package root, so from launchdarkly_ai_server import make_track_data avoids importing from the internal tracking module (same as the matching change in #30).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in edbc79e — switched ServedConfig.track_data() to the public root make_track_data(GraphNode(...), ...) export (popping empty graphKey) and removed the launchdarkly_ai_server.tracking submodule import.

Co-authored-by: Cursor <cursoragent@cursor.com>
…and refresh docs wording

Co-authored-by: Cursor <cursoragent@cursor.com>
…s links

Co-authored-by: Cursor <cursoragent@cursor.com>

This branch is waiting to be deployed

1 waiting deployment
ci — d462765e Waiting Nov 24, 2026 by sattensil via Evaluate AI Configs with Judge #138
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants