Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(traces): share text-only conversation prompts across parsers (#1809) (#1848)
Nurkhan Esenbek08125a0102b0
diff --git a/changelog.d/0.76.0/1848.fixed.md b/changelog.d/0.76.0/1848.fixed.mdnew file mode 100644index 00000000..cc7cdfb1--- /dev/null+++ b/changelog.d/0.76.0/1848.fixed.md@@ -0,0 +1 @@+- Share text-only conversation prompt extraction across trace and ingest parsers, retaining context through the last user turn so unrelated answers do not form preference pairs; keep system-plus-one-user prompts as plain user text, use role/content JSON only when an earlier user or assistant turn exists, normalize LangChain human/ai/system message types, omit blank context turns and non-text content parts, and select assistant output explicitly. (#1809 by @kok-o in #1848)diff --git a/docs/data.md b/docs/data.mdindex 1fdd18c5..2178528c 100644--- a/docs/data.md+++ b/docs/data.md@@ -375,6 +375,8 @@ soup ingest --source openai-stored --logs ./oai-stored-completions.jsonlWith `--logs` the CLI never makes a network call — operators export from their SaaS dashboard or vendor API, then point `soup ingest` at the local file. Auth env vars (`LANGFUSE_PUBLIC_KEY` + `LANGFUSE_SECRET_KEY` / `LANGSMITH_API_KEY` / `HELICONE_API_KEY` / `OPENPIPE_API_KEY` / `OPENAI_API_KEY` / `OTEL_EXPORTER_OTLP_HEADERS`) are advisory on that path — Soup surfaces which ones authenticate the source. A PII reminder fires on every ingest run (matches v0.26.0 Trace-to-Preference policy).+**Conversation prompts.** `soup ingest` and the OpenAI/LangChain `soup data from-traces` parsers use the same rule for message lists: retain context through the last user turn and omit later messages. If no user or assistant turn precedes the last user, the prompt stays as that user's plain text, including system-plus-one-user requests. Only requests with an earlier user or assistant turn are rendered as compact JSON of `role`/`content` objects through the last user, preserving message boundaries and roles. System-only requests and last user turns without text are skipped. Content-part lists join text parts with newlines and discard non-text parts, including image URLs and base64 data. Bare lists and `{"messages": [...]}` envelopes are equivalent. LangChain message `type` values `human`, `ai` and `system` map to `user`, `assistant` and `system`; an explicit string `role` takes precedence. Blank-content turns are omitted from multi-turn JSON. Output message lists select the final assistant response and flatten its text parts. Plain string prompts and outputs remain unchanged. This changes grouping for multi-turn logs: regenerate trace exports and preference pairs rather than mixing the previous first-turn prompts with the new conversation prompts.+### Live pull from Langfuse (`--pull`, #204)Langfuse is the one source Soup can fetch directly, so there is no export step:@@ -386,7 +388,7 @@ export LANGFUSE_HOST=https://us.cloud.langfuse.com # optional: default is httpsoup ingest --source langfuse --pull --since 7d --output traces.jsonl```-- **What one row is.** One output row per `GENERATION` observation in the window — the unit that carries a model, the exact input it was given and the output it produced — read from Langfuse's Observations API v2 (`/api/public/traces` is removed from Langfuse Cloud on 2026-11-16) and checked again on each observation, so a server that ignores the `type` filter cannot turn spans or tool calls into rows — they are counted as skipped in the summary. A row's `trace_id` is the observation id. The API returns plain-text input and output as-is but structured values (chat message lists, objects) as JSON inside a string; those are decoded, and a chat message list becomes a `prompt` of every message's content joined by newlines (system prompt included), the same flattening `parse_langfuse` applies to a `{"messages": [...]}` export. An agent trace therefore yields one row per LLM call it made; its spans and tool calls yield none. Generations with no input or no output are skipped and counted in the summary line, so a pull that matched nothing usable says so instead of writing an empty file silently.+- **What one row is.** One output row per `GENERATION` observation in the window — the unit that carries a model, the exact input it was given and the output it produced — read from Langfuse's Observations API v2 (`/api/public/traces` is removed from Langfuse Cloud on 2026-11-16) and checked again on each observation, so a server that ignores the `type` filter cannot turn spans or tool calls into rows — they are counted as skipped in the summary. A row's `trace_id` is the observation id. The API returns plain-text input and output as-is but structured values (chat message lists, objects) as JSON inside a string; those are decoded, and a chat message list follows the conversation prompt rule above: plain last-user text without an earlier user or assistant turn, otherwise compact role/content JSON through the last user. `parse_langfuse` applies the same rule to a `{"messages": [...]}` export. An agent trace therefore yields one row per LLM call it made; its spans and tool calls yield none. Generations with no input or no output are skipped and counted in the summary line, so a pull that matched nothing usable says so instead of writing an empty file silently.- **Credentials.** Read from the environment only, never from a flag, so they never reach the audit log's argv. `LANGFUSE_BASE_URL` is honoured before `LANGFUSE_HOST`, the same precedence as the Langfuse SDK. The key pair is not written to the output, the console, debug logs or error messages.- **Host checks.** HTTPS only. The host goes through the same SSRF validator as `--slack-url`; a private, link-local, shared (`100.64.0.0/10`), site-local (`fec0::/10`) or loopback address (self-hosted Langfuse) additionally needs `--allow-private-host`. Redirects are refused rather than followed with credentials attached.- **Bounds.** `--since` accepts `30m` / `24h` / `7d` up to `365d` (default `7d`). Each request is bounded by a 30 s wall-clock deadline covering the connect and the whole response — a server that drip-feeds bytes cannot outlast it — and a response is capped at 64 MiB. Pages hold 100 generations; if results are still pending after `--max-pages` pages (default 100, max 10 000), the command stops with exit 1 and writes nothing — the output streams to a staging file, so an earlier file at `--output` is left untouched. HTTP 429 is retried up to 5 times, honouring `Retry-After` with a 60 s ceiling, and a pagination cursor the server repeats stops the pull instead of spending the rest of the page budget.diff --git a/src/soup_cli/data/traces/messages.py b/src/soup_cli/data/traces/messages.pynew file mode 100644index 00000000..d0fe9ab6--- /dev/null+++ b/src/soup_cli/data/traces/messages.py@@ -0,0 +1,71 @@+"""Shared, text-only rendering for trace and ingest message payloads."""++from __future__ import annotations++import json+from typing import Any+++def _message_role(message: dict[str, Any]) -> str | None:+ """Prefer explicit roles, accepting LangChain's serialized message types."""+ role = message.get("role")+ if isinstance(role, str):+ return role+ message_type = message.get("type")+ if isinstance(message_type, str):+ return {"human": "user", "ai": "assistant", "system": "system"}.get(message_type)+ return None+++def content_text(value: Any) -> str:+ """Join text parts with newlines, omitting images, audio and other non-text parts."""+ if isinstance(value, str):+ return value+ if not isinstance(value, list):+ return ""+ return "\n".join(+ part["text"] for part in value+ if isinstance(part, dict)+ and part.get("type", "text") in ("text", "input_text", "output_text")+ and isinstance(part.get("text"), str)+ )+++def conversation_prompt(messages: Any) -> str:+ """Render context through the last user turn, never a trailing response.++ Without an earlier user or assistant turn, keep the last user's plain text,+ including system-plus-user requests. Otherwise use compact role/content JSON+ through that user turn. System-only requests and last user turns without+ text are omitted, not relabelled.+ """+ if not isinstance(messages, list):+ return ""+ turns = []+ for message in messages:+ if isinstance(message, dict):+ role = _message_role(message)+ if role is not None:+ turns.append({"role": role, "content": content_text(message.get("content"))})+ last_user = next((idx for idx in range(len(turns) - 1, -1, -1)+ if turns[idx]["role"] == "user"), None)+ if last_user is None or not turns[last_user]["content"].strip():+ return ""+ if not any(turn["role"] in ("user", "assistant") for turn in turns[:last_user]):+ return turns[last_user]["content"]+ context = [turn for turn in turns[:last_user + 1] if turn["content"].strip()]+ return json.dumps(context, ensure_ascii=False, separators=(",", ":"))+++def message_list_text(messages: list[Any], *, prompt: bool = True) -> str:+ """Distinguish message lists from content-part lists and extract text."""+ if any(isinstance(message, dict) and ("role" in message or _message_role(message) is not None)+ for message in messages):+ if prompt:+ return conversation_prompt(messages)+ # Output envelopes may include several turns; choose the final assistant.+ for message in reversed(messages):+ if isinstance(message, dict) and _message_role(message) == "assistant":+ return content_text(message.get("content"))+ return ""+ return content_text(messages)diff --git a/src/soup_cli/data/traces/parsers.py b/src/soup_cli/data/traces/parsers.pyindex e591eeac..80d65c48 100644--- a/src/soup_cli/data/traces/parsers.py+++ b/src/soup_cli/data/traces/parsers.py@@ -7,6 +7,8 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Iterable, Iterator, Optional+from soup_cli.data.traces.messages import content_text, conversation_prompt+SUPPORTED_FORMATS: tuple[str, ...] = ("langchain", "openai", "soup-serve")# The per-trace signal vocabulary a producer may write. Distinct from@@ -40,16 +42,13 @@ class Trace:def _langchain_prompt(inputs: Any) -> str:"""Flatten LangChain ``inputs`` into a string prompt."""+ if isinstance(inputs, list):+ return conversation_prompt(inputs)if not isinstance(inputs, dict):return ""messages = inputs.get("messages")if isinstance(messages, list):- parts: list[str] = []- for msg in messages:- if isinstance(msg, dict):- content = msg.get("content") or ""- parts.append(str(content))- return "\n".join(parts).strip()+ return conversation_prompt(messages)for key in ("prompt", "input", "query"):value = inputs.get(key)if isinstance(value, str):@@ -70,11 +69,11 @@ def _langchain_output(outputs: Any) -> str:item = firstif isinstance(item, dict):text = item.get("text") or item.get("content") or ""- return str(text)+ return content_text(text)for key in ("output", "response", "text", "content"):value = outputs.get(key)- if isinstance(value, str):- return value+ if isinstance(value, (str, list)):+ return content_text(value)return ""@@ -118,12 +117,7 @@ def parse_langchain(events: Iterable[Any]) -> Iterator[Trace]:def _openai_prompt(messages: Any) -> str:- if not isinstance(messages, list):- return ""- for msg in messages:- if isinstance(msg, dict) and msg.get("role") == "user":- return str(msg.get("content") or "")- return ""+ return conversation_prompt(messages)def _openai_output(choices: Any) -> str:@@ -134,8 +128,8 @@ def _openai_output(choices: Any) -> str:return ""msg = first.get("message")if isinstance(msg, dict):- return str(msg.get("content") or "")- return str(first.get("text") or "")+ return content_text(msg.get("content"))+ return content_text(first.get("text"))def _openai_signal(feedback: Any) -> str:diff --git a/src/soup_cli/utils/ingest_sources.py b/src/soup_cli/utils/ingest_sources.pyindex bd2de34e..67ad6124 100644--- a/src/soup_cli/utils/ingest_sources.py+++ b/src/soup_cli/utils/ingest_sources.py@@ -30,6 +30,7 @@ from dataclasses import dataclass, fieldfrom types import MappingProxyTypefrom typing import Any, Dict, Iterable, Iterator, Mapping, Optional+from soup_cli.data.traces.messages import content_text, conversation_prompt, message_list_textfrom soup_cli.utils.paths import is_under_cwd# ---------------------------------------------------------------------------@@ -156,7 +157,7 @@ def resolve_auth_env(name: object) -> Optional[str]:# ----------------------------------------------------------------------------def _coerce_str(value: Any) -> str:+def _coerce_str(value: Any, *, prompt: bool = True) -> str:"""Best-effort string extraction for messy SaaS payloads."""if isinstance(value, str):return value@@ -164,39 +165,15 @@ def _coerce_str(value: Any) -> str:# Common shapes: {messages: [...]}, {content: "..."}, {text: "..."}messages = value.get("messages")if isinstance(messages, list):- parts: list[str] = []- for msg in messages:- if isinstance(msg, dict):- content = msg.get("content")- if isinstance(content, str):- parts.append(content)- elif isinstance(content, list):- for chunk in content:- if isinstance(chunk, dict):- text = chunk.get("text")- if isinstance(text, str):- parts.append(text)- joined = "\n".join(parts).strip()- if joined:- return joined+ return message_list_text(messages, prompt=prompt)for key in ("content", "text", "prompt", "response", "output", "input"):sub = value.get(key)if isinstance(sub, str):return subif isinstance(sub, list):- # OpenAI Stored Completions style: input/output as list of msgs- for msg in sub:- if isinstance(msg, dict):- c = msg.get("content")- if isinstance(c, str):- return c+ return message_list_text(sub, prompt=prompt)if isinstance(value, list):- # OpenAI Stored Completions: list of role/content turns- for msg in value:- if isinstance(msg, dict):- c = msg.get("content")- if isinstance(c, str):- return c+ return message_list_text(value, prompt=prompt)return ""@@ -228,7 +205,7 @@ def parse_langfuse(events: Iterable[Any]) -> Iterator[TraceRecord]:if not isinstance(event, dict):continueprompt = _coerce_str(event.get("input"))- output = _coerce_str(event.get("output"))+ output = _coerce_str(event.get("output"), prompt=False)if not prompt or not output:continuetrace_id = str(event.get("id") or f"langfuse-{idx}")@@ -270,10 +247,9 @@ def parse_langsmith(events: Iterable[Any]) -> Iterator[TraceRecord]:item = firstif isinstance(item, dict):text = item.get("text") or item.get("content")- if isinstance(text, str):- output = text+ output = content_text(text)if not output:- output = _coerce_str(outputs)+ output = _coerce_str(outputs, prompt=False)if not prompt or not output:continuetrace_id = str(event.get("id") or f"langsmith-{idx}")@@ -320,14 +296,13 @@ def parse_helicone(events: Iterable[Any]) -> Iterator[TraceRecord]:msg = first.get("message")if isinstance(msg, dict):content = msg.get("content")- if isinstance(content, str):- output = content+ output = content_text(content)if not output:- output = _coerce_str(first.get("text"))+ output = _coerce_str(first.get("text"), prompt=False)if not output:- output = _coerce_str(body)+ output = _coerce_str(body, prompt=False)else:- output = _coerce_str(resp)+ output = _coerce_str(resp, prompt=False)if not prompt or not output:continuetrace_id = str(event.get("request_id") or event.get("id") or f"helicone-{idx}")@@ -350,17 +325,10 @@ def parse_openpipe(events: Iterable[Any]) -> Iterator[TraceRecord]:if not isinstance(event, dict):continuemessages = event.get("messages")- prompt = ""- if isinstance(messages, list):- user_msgs = [- str(m.get("content") or "")- for m in messages- if isinstance(m, dict) and m.get("role") == "user"- ]- prompt = "\n".join(p for p in user_msgs if p).strip()+ prompt = conversation_prompt(messages)if not prompt:prompt = _coerce_str(event.get("prompt"))- output = _coerce_str(event.get("response") or event.get("output"))+ output = _coerce_str(event.get("response") or event.get("output"), prompt=False)if not prompt or not output:continuetrace_id = str(event.get("id") or f"openpipe-{idx}")@@ -417,7 +385,7 @@ def parse_openai_stored(events: Iterable[Any]) -> Iterator[TraceRecord]:if not isinstance(event, dict):continueprompt = _coerce_str(event.get("input"))- output = _coerce_str(event.get("output"))+ output = _coerce_str(event.get("output"), prompt=False)if not prompt or not output:continuetrace_id = str(event.get("id") or f"openai-stored-{idx}")diff --git a/tests/test_issue204_langfuse_pull.py b/tests/test_issue204_langfuse_pull.pyindex 8ff62ea6..73ea4e92 100644--- a/tests/test_issue204_langfuse_pull.py+++ b/tests/test_issue204_langfuse_pull.py@@ -1007,7 +1007,7 @@ class TestRecordedRealResponse:assert trace_of["44d5516f74ed7738"] == trace_of["09c25553e670e9a1"]model = {"model": "gpt-4o-mini"}assert records == [ # API order: newest startTime first- {"trace_id": "44d5516f74ed7738", "prompt": "How tall is the Eiffel Tower?\n330 m",+ {"trace_id": "44d5516f74ed7738", "prompt": "How tall is the Eiffel Tower?","output": "The Eiffel Tower is 330 m tall.", "source": "langfuse", "signal": "none","metadata": model},{"trace_id": "09c25553e670e9a1",@@ -1017,7 +1017,7 @@ class TestRecordedRealResponse:{"trace_id": "e83a0c5fd3d47039", "prompt": "Translate 'hello' to Spanish.","output": "hola", "source": "langfuse", "signal": "none", "metadata": model},{"trace_id": "8dd24f84d2bf7735",- "prompt": "You are terse.\nWhat is the capital of France?",+ "prompt": "What is the capital of France?","output": "Paris.", "source": "langfuse", "signal": "none", "metadata": model},]@@ -1040,9 +1040,8 @@ class TestRecordedRealResponse:assert raw["8dd24f84d2bf7735"].prompt.startswith('[{"role": "system"')- def test_control_a_bare_message_list_would_keep_only_the_system_prompt(self):- """CONTROL for the ``{"messages": [...]}`` hand-off: ``_coerce_str`` keeps- only the first message of a bare list."""+ def test_bare_and_enveloped_message_lists_keep_the_user_question(self):+ """Both Langfuse input shapes use the same conversation rule (#1809)."""from soup_cli.utils.ingest_sources import parse_langfusepage = json.loads(_RECORDED_PAGE.read_text(encoding="utf-8"))["data"]@@ -1053,7 +1052,10 @@ class TestRecordedRealResponse:"output": json.loads(chat["output"]),}- assert next(parse_langfuse([bare])).prompt == "You are terse."+ prompt = next(parse_langfuse([bare])).prompt+ assert prompt == "What is the capital of France?"+ wrapped = dict(bare, input={"messages": bare["input"]})+ assert next(parse_langfuse([wrapped])).prompt == prompt# ============================================================diff --git a/tests/test_trace_conversations.py b/tests/test_trace_conversations.pynew file mode 100644index 00000000..2a40e208--- /dev/null+++ b/tests/test_trace_conversations.py@@ -0,0 +1,315 @@+"""Trace and ingest prompts retain conversation identity without binary parts."""++import json++import pytest+from typer.testing import CliRunner++from soup_cli.cli import app+from soup_cli.data.traces import build_pairs, parse_langchain, parse_openai+from soup_cli.utils.ingest_sources import (+ _coerce_str,+ parse_helicone,+ parse_langfuse,+ parse_langsmith,+ parse_openai_stored,+ parse_openpipe,+)+++def _messages(question="Q2"):+ return [+ {"role": "system", "content": "Be helpful."},+ {"role": "user", "content": "Q1"},+ {"role": "assistant", "content": "A1"},+ {"role": "user", "content": question},+ ]+++def _event(messages, rating="up", output="A2"):+ return {"messages": messages, "choices": [{"message": {"content": output}}],+ "feedback": {"rating": rating}}+++def _output_messages() -> list[dict[str, str]]:+ return [+ {"role": "user", "content": "Response context"},+ {"role": "assistant", "content": "Earlier answer"},+ {"role": "assistant", "content": "Final answer"},+ {"role": "user", "content": "Trailing user is not the answer"},+ ]+++def test_two_turns_cannot_form_a_false_preference_pair() -> None:+ first = _event(_messages()[:2], "down", "A1")+ second = _event(_messages())+ traces = list(parse_openai([first, second]))+ assert len(traces) == 2+ assert traces[0].prompt != traces[1].prompt+ assert list(build_pairs(traces, signal="thumbs_up")) == []+++def test_shared_opening_does_not_merge_different_conversations() -> None:+ traces = list(parse_openai([_event(_messages("2+2?"), "down"),+ _event(_messages("Capital of France?"))]))+ assert len({trace.prompt for trace in traces}) == 2+ assert list(build_pairs(traces, signal="thumbs_up")) == []+++def test_context_is_role_preserving_and_stops_at_last_user() -> None:+ messages = _messages()+ request = messages + [{"role": "assistant", "content": "leak"}]+ prompt = next(parse_openai([_event(request)])).prompt+ assert json.loads(prompt) == messages+ assert "leak" not in prompt++[email protected]("parser", [parse_langfuse, parse_langsmith, parse_openai_stored])[email protected]("envelope", [False, True])+def test_system_plus_one_user_keeps_plain_prompt_across_ingest(parser, envelope) -> None:+ messages = _messages()[:2] + [{"role": "assistant", "content": "Trailing answer"}]+ source = {"messages": messages} if envelope else messages+ event = {"input": source, "inputs": source, "output": "A1",+ "outputs": {"generations": [[{"text": "A1"}]]}}+ trace = next(parser([event]))+ assert trace.prompt == "Q1"+ assert trace.output == "A1"+++def test_system_plus_one_user_keeps_plain_prompt_across_trace_sources() -> None:+ messages = _messages()[:2] + [{"role": "assistant", "content": "Trailing answer"}]+ traces = [+ next(parse_openai([_event(messages, output="A1")])),+ next(parse_langchain([{"inputs": {"messages": messages}, "outputs": {"output": "A1"}}])),+ next(parse_helicone([{"request": {"body": {"messages": messages}},+ "response": {"body": {"choices": [{"message": {+ "content": "A1"}}]}}}])),+ next(parse_openpipe([{"messages": messages, "response": "A1"}])),+ ]+ assert all(trace.prompt == "Q1" and trace.output == "A1" for trace in traces)++[email protected]("role", ["user", "assistant"])+def test_either_earlier_conversation_role_requires_json(role: str) -> None:+ messages = [{"role": "system", "content": "Be helpful."},+ {"role": role, "content": "Earlier turn"},+ {"role": "user", "content": "Question"}]+ assert json.loads(next(parse_openai([_event(messages)])).prompt) == messages++[email protected]("parser", [parse_langfuse, parse_langsmith, parse_openai_stored])[email protected]("envelope", [False, True])+def test_ingest_parsers_share_prompt_rule(parser, envelope) -> None:+ messages = _messages()+ source = {"messages": messages} if envelope else messages+ event = {"input": source, "inputs": source, "output": [{"role": "assistant", "content": "A2"}],+ "outputs": {"generations": [[{"text": "A2"}]]}}+ trace = next(parser([event]))+ assert trace.prompt == next(parse_openai([_event(messages)])).prompt+ assert trace.output == "A2"++[email protected]("envelope", [None, "messages", "input", "content", "prompt", "output"])+def test_coercion_uses_same_rule_in_every_list_branch(envelope) -> None:+ messages = _messages()+ value = {envelope: messages} if envelope else messages+ assert _coerce_str(value) == next(parse_openai([_event(messages)])).prompt+++def test_langchain_and_other_ingest_sources_share_conversation_identity() -> None:+ messages = _messages()+ expected = next(parse_openai([_event(messages)])).prompt+ lc = next(parse_langchain([{"inputs": {"messages": messages},+ "outputs": {"generations": [[{"text": "A2"}]]}}]))+ helicone = next(parse_helicone([{"request": {"body": {"messages": messages}},+ "response": {"body": {"choices": [{"message": {+ "content": "A2"}}]}}}]))+ openpipe = next(parse_openpipe([{"messages": messages, "response": "A2"}]))+ assert lc.prompt == helicone.prompt == openpipe.prompt == expected+++def test_langchain_bare_list_input_preserves_context_through_last_user() -> None:+ messages = _messages() + [{"role": "assistant", "content": "Trailing answer"}]+ trace = next(parse_langchain([{"inputs": messages, "outputs": {"output": "A2"}}]))+ assert trace.prompt == (+ '[{"role":"system","content":"Be helpful."},{"role":"user","content":"Q1"},'+ '{"role":"assistant","content":"A1"},{"role":"user","content":"Q2"}]'+ )+ assert trace.output == "A2"++[email protected]("envelope", [False, True])[email protected]("multi_turn", [False, True])+def test_langchain_type_keyed_messages_follow_conversation_rule(envelope, multi_turn) -> None:+ expected = _messages() if multi_turn else _messages()[:2]+ types = {"system": "system", "user": "human", "assistant": "ai"}+ messages = [{"type": types[turn["role"]], "content": turn["content"]} for turn in expected]+ messages.append({"type": "ai", "content": "Trailing answer"})+ inputs = {"messages": messages} if envelope else messages+ traces = list(parse_langchain([{"inputs": inputs, "outputs": {"output": "Answer"}}]))+ assert len(traces) == 1+ assert traces[0].output == "Answer"+ if multi_turn:+ assert json.loads(traces[0].prompt) == expected+ else:+ assert traces[0].prompt == "Q1"+ assert _coerce_str(inputs) == traces[0].prompt+++def test_type_keyed_output_messages_select_last_assistant() -> None:+ messages = [{"type": "ai", "content": "Earlier answer"},+ {"type": "ai", "content": "Final answer"},+ {"type": "human", "content": "Trailing user"}]+ assert _coerce_str(messages, prompt=False) == "Final answer"+++def test_explicit_role_takes_precedence_over_langchain_type() -> None:+ messages = [{"role": "user", "type": "ai", "content": "Question"}]+ assert _coerce_str(messages) == "Question"++[email protected]("invalid_type", [None, [], {}])+def test_invalid_message_type_is_ignored(invalid_type) -> None:+ messages = [{"type": invalid_type, "content": "Ignored"},+ {"role": "user", "content": "Question"}]+ assert _coerce_str(messages) == "Question"++[email protected]("invalid_role", [None, [], {}])+def test_invalid_role_message_does_not_become_a_content_part(invalid_role) -> None:+ assert _coerce_str([{"role": invalid_role, "text": "Not message content"}]) == ""++[email protected]("parser", [parse_openai, parse_langchain])[email protected]("role", ["system", "user", "assistant"])[email protected]("blank", ["", " \t\n "])+def test_blank_context_turn_is_omitted_from_multi_turn_json(parser, role, blank) -> None:+ messages = _messages()+ messages.insert(2, {"role": role, "content": blank})+ event = (_event(messages) if parser is parse_openai else+ {"inputs": {"messages": messages}, "outputs": {"output": "A2"}})+ assert json.loads(next(parser([event])).prompt) == _messages()++[email protected]("output_key", ["output", "response"])+def test_langchain_output_keys_flatten_content_parts(output_key: str) -> None:+ parts = [{"type": "text", "text": "First line"},+ {"type": "output_text", "text": "Second line"},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,SECRET"}}]+ trace = next(parse_langchain([{"inputs": [{"role": "user", "content": "Question"}],+ "outputs": {output_key: parts}}]))+ assert trace.prompt == "Question"+ assert trace.output == "First line\nSecond line"++[email protected]("output_path", ["response", "body", "text"])+def test_helicone_message_output_fallbacks_choose_final_assistant(output_path: str) -> None:+ messages = _output_messages()+ responses = {+ "response": messages,+ "body": {"body": messages},+ "text": {"body": {"choices": [{"text": messages}]}},+ }+ event = {"request": {"body": {"messages": [{"role": "user", "content": "Question"}]}},+ "response": responses[output_path]}+ trace = next(parse_helicone([event]))+ assert trace.prompt == "Question"+ assert trace.output == "Final answer"+++def test_helicone_message_content_flattens_content_parts() -> None:+ parts = [{"type": "text", "text": "First line"},+ {"type": "output_text", "text": "Second line"},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,SECRET"}}]+ event = {"request": {"body": {"messages": [{"role": "user", "content": "Question"}]}},+ "response": {"body": {"choices": [{"message": {"content": parts}}]}}}+ trace = next(parse_helicone([event]))+ assert trace.prompt == "Question"+ assert trace.output == "First line\nSecond line"++[email protected]("content_key", ["text", "content"])+def test_langsmith_generations_flatten_content_parts(content_key: str) -> None:+ parts = [{"type": "text", "text": "First line"},+ {"type": "output_text", "text": "Second line"},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,SECRET"}}]+ event = {"inputs": {"messages": [{"role": "user", "content": "Question"}]},+ "outputs": {"generations": [[{content_key: parts}]]}}+ trace = next(parse_langsmith([event]))+ assert trace.prompt == "Question"+ assert trace.output == "First line\nSecond line"+++def test_langsmith_output_fallback_selects_final_assistant() -> None:+ event = {"inputs": {"messages": [{"role": "user", "content": "Question"}]},+ "outputs": {"messages": _output_messages()}}+ trace = next(parse_langsmith([event]))+ assert trace.prompt == "Question"+ assert trace.output == "Final answer"+++def test_output_message_lists_select_final_assistant_before_trailing_user() -> None:+ event = {"input": [{"role": "user", "content": "Question"}],+ "output": _output_messages()}+ trace = next(parse_openai_stored([event]))+ assert trace.prompt == "Question"+ assert trace.output == "Final answer"+++def test_conversation_json_keeps_non_ascii_text_literal() -> None:+ messages = [{"role": "system", "content": "Қазақша жауап бер."},+ {"role": "user", "content": "Алдыңғы сұрақ"},+ {"role": "assistant", "content": "Алдыңғы жауап"},+ {"role": "user", "content": "Сәлем 👋"}]+ trace = next(parse_openai([_event(messages, output="Жауап")]))+ assert trace.prompt == (+ '[{"role":"system","content":"Қазақша жауап бер."},'+ '{"role":"user","content":"Алдыңғы сұрақ"},'+ '{"role":"assistant","content":"Алдыңғы жауап"},'+ '{"role":"user","content":"Сәлем 👋"}]'+ )+ assert trace.output == "Жауап"+++def test_text_parts_are_flattened_and_binary_parts_dropped_everywhere() -> None:+ parts = [{"type": "text", "text": "Hi"},+ {"type": "image_url", "text": "Not a text part",+ "image_url": {"url": "data:image/png;base64,SECRET"}}]+ messages = [{"role": "user", "content": parts}]+ oai = next(parse_openai([{"messages": messages, "choices": [{"message": {"content": parts}}]}]))+ lc = next(parse_langchain([{"inputs": {"messages": messages},+ "outputs": {"generations": [[{"text": parts}]]}}]))+ stored = next(parse_openai_stored([{"input": messages,+ "output": [{"role": "assistant", "content": parts}]}]))+ for trace in (oai, lc, stored):+ assert trace.prompt == "Hi"+ assert trace.output == "Hi"+ assert _coerce_str(parts) == "Hi"++[email protected]("messages", [[], [{"role": "system", "content": "System only"}],+ [{"role": "user", "content": [{"type": "image_url"}]}]])+def test_no_text_user_turn_does_not_become_a_training_prompt(messages) -> None:+ assert list(parse_openai([_event(messages)])) == []+ assert _coerce_str(messages) == ""+++def test_same_conversation_still_forms_a_real_preference_pair() -> None:+ traces = list(parse_openai([_event(_messages(), "down", "Bad"),+ _event(_messages(), "up", "Good")]))+ pairs = list(build_pairs(traces, signal="thumbs_up"))+ assert len(pairs) == 1+ assert pairs[0].prompt == traces[0].prompt+ assert (pairs[0].chosen, pairs[0].rejected) == ("Good", "Bad")+++def test_ingest_cli_preserves_the_user_question(tmp_path, monkeypatch) -> None:+ monkeypatch.chdir(tmp_path)+ event = {"input": _messages(), "output": [{"role": "assistant", "content": "A2"}]}+ (tmp_path / "logs.jsonl").write_text(json.dumps(event) + "\n", encoding="utf-8")+ result = CliRunner().invoke(app, ["ingest", "--source", "openai-stored", "--logs", "logs.jsonl",+ "--output", "traces.jsonl"])+ assert result.exit_code == 0, result.output+ row = json.loads((tmp_path / "traces.jsonl").read_text(encoding="utf-8"))+ assert json.loads(row["prompt"]) == _messages()+ assert row["output"] == "A2"