From cb174ca7f7be62b2321905c2d42387494e149313 Mon Sep 17 00:00:00 2001 From: Guido van Rossum Date: Mon, 22 Apr 2024 16:02:41 -0700 Subject: [PATCH 1/7] Proposed alternate prompting scheme --- python/src/typechat/_internal/translator.py | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/python/src/typechat/_internal/translator.py b/python/src/typechat/_internal/translator.py index 6c649c1e..63751a13 100644 --- a/python/src/typechat/_internal/translator.py +++ b/python/src/typechat/_internal/translator.py @@ -64,14 +64,14 @@ async def translate(self, input: str, *, prompt_preamble: str | list[PromptSecti messages: list[PromptSection] = [] - messages.append({"role": "user", "content": input}) + messages.append({"role": "system", "content": self._create_request_prompt(input)}) + if prompt_preamble: if isinstance(prompt_preamble, str): prompt_preamble = [{"role": "user", "content": prompt_preamble}] - else: - messages.extend(prompt_preamble) + messages.extend(prompt_preamble) - messages.append({"role": "user", "content": self._create_request_prompt(input)}) + messages.append({"role": "user", "content": input}) num_repairs_attempted = 0 while True: @@ -103,11 +103,7 @@ def _create_request_prompt(self, intent: str) -> str: ``` {self._schema_str} ``` -The following is a user request: -''' -{intent} -''' -The following is the user request translated into a JSON object with 2 spaces of indentation and no properties with the value undefined: +You translate each user request into a JSON object with 2 spaces of indentation and no properties with the value undefined. """ return prompt From 638fbad839280020013ae41594af6f9a71d948c7 Mon Sep 17 00:00:00 2001 From: Robert Gruen Date: Mon, 23 Nov 2026 17:46:53 -0800 Subject: [PATCH 2/7] Prepare Python 0.3.0 examples and migration guide Keep both calculator schemas in the math instructions, refresh the health clock per turn, and replay only validated assistant results as history. Cover the native examples and document the explicit pre-0.3 layout. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- python/README.md | 21 +++- python/examples/drawing/demo.py | 9 +- python/examples/healthData/README.md | 10 +- python/examples/healthData/translator.py | 54 +++++---- python/examples/math/README.md | 27 +++-- python/examples/math/program.py | 36 +++--- python/examples/multiSchema/router.py | 15 +-- python/package-lock.json | 4 +- python/package.json | 2 +- python/src/typechat/__about__.py | 2 +- python/tests/test_example_prompt_layouts.py | 123 ++++++++++++++++++++ site/src/docs/python/basic-usage.md | 64 ++++++++-- 12 files changed, 292 insertions(+), 75 deletions(-) create mode 100644 python/tests/test_example_prompt_layouts.py diff --git a/python/README.md b/python/README.md index 02765944..7e42dab3 100644 --- a/python/README.md +++ b/python/README.md @@ -54,6 +54,22 @@ To learn more about TypeChat, visit the [documentation](https://microsoft.github.io/TypeChat/docs/python/basic-usage/) which includes more information on TypeChat and how to get started. +## Translator prompts in 0.3 + +`await translator.translate(request)` sends the schema and JSON instructions as a +`system` message, then the verbatim request as a `user` message. For a follow-up, +pass earlier messages as `prompt_preamble`: they go between those two messages, +with their original roles and order. A nonempty string preamble is one `user` +message. The translator does not remember earlier turns for you. + +To keep the pre-0.3 combined user prompt, construct +`TypeChatJsonTranslator(model, validator, target_type, use_legacy_prompt=True)`. +This keyword-only option keeps existing `_create_request_prompt(self, intent)` +overrides in the **user** role. For the new default, customize +`_create_system_prompt(self)` with application-owned instructions only. See the +[migration guide](../site/src/docs/python/basic-usage.md#prompt-layout-and-migration) +and the [math](./examples/math/program.py) and [health-data](./examples/healthData/translator.py) examples. + ## Reusing model authentication For keyless Azure OpenAI requests, pass a synchronous or asynchronous bearer-token @@ -150,8 +166,9 @@ user/system text to `input_text`, assistant text to `output_text`, and images to `input_image` with a flat `image_url` string and optional `detail`, preserving order, references, and omitted detail. -`translate` still takes a string request. Its preamble stays before the generated -schema/request message, and image context is preserved during validation and repair. +`translate` still takes a string request. Image context stays in the preamble, +including during repair: the translator appends the raw assistant reply and a +user diagnostic without rewriting earlier messages. Successful model completions remain text-only. Authentication, HTTP controls, and configured-client ownership remain unchanged. diff --git a/python/examples/drawing/demo.py b/python/examples/drawing/demo.py index 0f499084..436988a6 100644 --- a/python/examples/drawing/demo.py +++ b/python/examples/drawing/demo.py @@ -10,6 +10,7 @@ from typechat import ( Success, Failure, + PromptSection, TypeChatJsonTranslator, TypeChatValidator, create_language_model, @@ -30,12 +31,14 @@ async def main(file_path: str | None): canvas.pack(padx=10, pady=10) canvas.bind("", lambda event: window.quit()) - history: list[str] = [] + history: list[PromptSection] = [ + {"role": "system", "content": "Return the complete drawing, applying all drawing requests in order."}, + ] async def request_handler(request: str): print("[Sending request...]") - history.append(request) - result: Success[schema.Drawing] | Failure = await translator.translate("\n".join(history)) + result: Success[schema.Drawing] | Failure = await translator.translate(request, prompt_preamble=history) + history.append({"role": "user", "content": request}) if isinstance(result, Failure): print("Failure:", result.message) else: diff --git a/python/examples/healthData/README.md b/python/examples/healthData/README.md index 6f41ef6a..b786b091 100644 --- a/python/examples/healthData/README.md +++ b/python/examples/healthData/README.md @@ -6,13 +6,21 @@ Demonstrates a ***strongly typed*** chat: a natural language interface for enter The Health Data Agent shows how strongly typed **agents with history** could interact with a user to collect information needed for one or more data types ("form filling"). +The [example translator](./translator.py) reads the current date and time once per +turn so relative dates use the current clock. In the default layout, the clock, +schema, and application instructions go in the system message. Only earlier +**validated results** are saved and replayed as assistant messages; failed turns, +repair diagnostics, and raw user input are not saved. Each new request goes in +its own user message. `use_legacy_prompt=True` instead uses the example's old +combined user prompt, including its serialized history. + ## Target models For best and consistent results, use **gpt-4**. ## Try the Health Data Agent -To run the Sentiment example, follow the instructions in the [examples README](../README.md#step-1-configure-your-development-environment). +To run the Health Data example, follow the instructions in the [examples README](../README.md#step-1-configure-your-development-environment). ## Usage diff --git a/python/examples/healthData/translator.py b/python/examples/healthData/translator.py index fa5749f2..661a307f 100644 --- a/python/examples/healthData/translator.py +++ b/python/examples/healthData/translator.py @@ -1,44 +1,55 @@ import json -from typing_extensions import TypeVar, Any, override, TypedDict, Literal +from datetime import datetime -from typechat import TypeChatValidator, TypeChatLanguageModel, TypeChatJsonTranslator, Result, Failure, PromptSection +from pydantic_core import to_jsonable_python +from typing_extensions import TypeVar, override -from datetime import datetime +from typechat import TypeChatValidator, TypeChatLanguageModel, TypeChatJsonTranslator, Result, Success, PromptSection T = TypeVar("T", covariant=True) -class ChatMessage(TypedDict): - source: Literal["system", "user", "assistant"] - body: Any +def _clock_instructions() -> str: + now = datetime.now() + return f"""Use precise date and times RELATIVE TO CURRENT DATE: {now:%A, %m %d, %Y} CURRENT TIME: {now:%H:%M:%S} +Also turn ranges like next week and next month into precise dates""" class TranslatorWithHistory(TypeChatJsonTranslator[T]): - _chat_history: list[ChatMessage] - _max_prompt_length: int - _additional_agent_instructions: str - def __init__( - self, model: TypeChatLanguageModel, validator: TypeChatValidator[T], target_type: type[T], additional_agent_instructions: str + self, model: TypeChatLanguageModel, validator: TypeChatValidator[T], target_type: type[T], + additional_agent_instructions: str, *, use_legacy_prompt: bool = False, ): - super().__init__(model=model, validator=validator, target_type=target_type) - self._chat_history = [] - self._max_prompt_length = 2048 + super().__init__(model, validator, target_type, use_legacy_prompt=use_legacy_prompt) + self._chat_history: list[object] = [] self._additional_agent_instructions = additional_agent_instructions @override async def translate(self, input: str, *, prompt_preamble: str | list[PromptSection] | None = None) -> Result[T]: + if not self._use_legacy_prompt and self._chat_history: + context: list[PromptSection] = [] + if isinstance(prompt_preamble, str): + if prompt_preamble: + context.append({"role": "user", "content": prompt_preamble}) + elif prompt_preamble: + context.extend(prompt_preamble) + for body in self._chat_history: + context.append({"role": "assistant", "content": json.dumps(body, indent=2, allow_nan=False)}) + prompt_preamble = context + result = await super().translate(input=input, prompt_preamble=prompt_preamble) - if not isinstance(result, Failure): - self._chat_history.append(ChatMessage(source="assistant", body=result.value)) + if isinstance(result, Success): + self._chat_history.append(to_jsonable_python(result.value)) return result @override - def _create_request_prompt(self, intent: str) -> str: - # TODO: drop history entries if we exceed the max_prompt_length - history_str = json.dumps(self._chat_history, indent=2, default=lambda o: None, allow_nan=False) + def _create_system_prompt(self) -> str: + return f"{super()._create_system_prompt()}\n{_clock_instructions()}\n\n{self._additional_agent_instructions}" - now = datetime.now() + @override + def _create_request_prompt(self, intent: str) -> str: + history = [{"source": "assistant", "body": body} for body in self._chat_history] + history_str = json.dumps(history, indent=2, allow_nan=False) prompt = F""" user: You are a service that translates user requests into JSON objects of type "{self.type_name}" according to the following TypeScript definitions: @@ -47,8 +58,7 @@ def _create_request_prompt(self, intent: str) -> str: ''' user: -Use precise date and times RELATIVE TO CURRENT DATE: {now.strftime('%A, %m %d, %Y')} CURRENT TIME: {now.strftime("%H:%M:%S")} -Also turn ranges like next week and next month into precise dates +{_clock_instructions()} user: {self._additional_agent_instructions} diff --git a/python/examples/math/README.md b/python/examples/math/README.md index 6ccf9cf9..db056458 100644 --- a/python/examples/math/README.md +++ b/python/examples/math/README.md @@ -1,6 +1,11 @@ # Math -The Math example shows how to use TypeChat for program generation based on an API schema with the `evaluateJsonProgram` function. This example translates calculations into simple programs given an [`API`](./schema.py) type that can perform the four basic mathematical operations. +The Math example translates calculations into JSON programs that call the functions in +[`MathAPI`](./schema.py). The [program translator](./program.py) puts **both** the +JSON program schema and the calculator API schema in its system message. The +calculation request is a separate user message. `use_legacy_prompt=True` keeps the +previous combined user prompt. In both layouts, `evaluate_json_program` evaluates +the validated program using the example's operations. # Try Math @@ -21,15 +26,15 @@ For example, we could use natural language to describe mathematical operations, **Output**: ``` -import { API } from "./schema"; -function program(api: API) { - const step1 = api.mul(2, 3); - const step2 = api.mul(4, 5); - return api.add(step1, step2); +{ + "@steps": [ + {"@func": "mul", "@args": [2, 3]}, + {"@func": "mul", "@args": [4, 5]}, + {"@func": "add", "@args": [{"@ref": 0}, {"@ref": 1}]} + ] } -Running program: -mul(2, 3) -mul(4, 5) -add(6, 20) -Result: 26 +mul([2, 3]) +mul([4, 5]) +add([6, 20]) +Math Result: 26 ``` diff --git a/python/examples/math/program.py b/python/examples/math/program.py index fc9479b7..fdc2f639 100644 --- a/python/examples/math/program.py +++ b/python/examples/math/program.py @@ -118,18 +118,19 @@ def validate_object(self, obj: Any) -> Success[JsonProgram] | Failure: class TypeChatProgramTranslator(TypeChatJsonTranslator[JsonProgram]): - _api_declaration_str: str - - def __init__(self, model: TypeChatLanguageModel, validator: TypeChatProgramValidator, api_type: type): - super().__init__(model=model, validator=validator, target_type=api_type, _raise_on_schema_errors = False) + def __init__( + self, model: TypeChatLanguageModel, validator: TypeChatProgramValidator, api_type: type, + *, use_legacy_prompt: bool = False, + ): # TODO: the conversion result here has errors! - conversion_result = python_type_to_typescript_schema(api_type) - self._api_declaration_str = conversion_result.typescript_schema_str - - @override - def _create_request_prompt(self, intent: str) -> str: - - prompt = F""" + super().__init__( + model=model, validator=validator, target_type=api_type, + use_legacy_prompt=use_legacy_prompt, _raise_on_schema_errors=False, + ) + self._api_declaration_str = self.schema_str + + def _program_instructions(self) -> str: + return f""" You are a service that translates user requests into programs represented as JSON using the following TypeScript definitions: ``` {program_schema_text} @@ -137,14 +138,23 @@ def _create_request_prompt(self, intent: str) -> str: The programs can call functions from the API defined in the following TypeScript definitions: ``` {self._api_declaration_str} -``` +```""" + + @override + def _create_system_prompt(self) -> str: + return f"""{self._program_instructions()} +Translate each user request into a JSON program object with 2 spaces of indentation and no properties with the value undefined. +""" + + @override + def _create_request_prompt(self, intent: str) -> str: + return f"""{self._program_instructions()} The following is a user request: ''' {intent} ''' The following is the user request translated into a JSON program object with 2 spaces of indentation and no properties with the value undefined: """ - return prompt @override def _create_repair_prompt(self, validation_error: str) -> str: diff --git a/python/examples/multiSchema/router.py b/python/examples/multiSchema/router.py index 05895f72..7062ea80 100644 --- a/python/examples/multiSchema/router.py +++ b/python/examples/multiSchema/router.py @@ -29,16 +29,11 @@ def register_agent(self, name: str, description: str, handler: Callable[[str], A self._current_agents[name] = agent async def route_request(self, line: str): - classes_str = json.dumps(self._current_agents, indent=2, default=lambda o: None, allow_nan=False) - - prompt_fragment = F""" -Classify ""{line}"" using the following classification table: -''' -{classes_str} -''' -""" - - result = await self._translator.translate(prompt_fragment) + classes = {name: agent["description"] for name, agent in self._current_agents.items()} + result = await self._translator.translate(line, prompt_preamble=[{ + "role": "system", + "content": f"Classify the user request using this table of registered agents:\n{json.dumps(classes, indent=2)}", + }]) if isinstance(result, Failure): print("Translation Failed āŒ") print(f"Context: {result.message}") diff --git a/python/package-lock.json b/python/package-lock.json index cda0544c..e7d0f0a6 100644 --- a/python/package-lock.json +++ b/python/package-lock.json @@ -1,12 +1,12 @@ { "name": "typechat-py", - "version": "0.1.0", + "version": "0.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "typechat-py", - "version": "0.1.0", + "version": "0.3.0", "license": "MIT", "devDependencies": { "pyright": "1.1.358" diff --git a/python/package.json b/python/package.json index 6f3f59ca..ebbb13f3 100644 --- a/python/package.json +++ b/python/package.json @@ -1,7 +1,7 @@ { "name": "typechat-py", "private": true, - "version": "0.1.0", + "version": "0.3.0", "description": "TypeChat is a library that makes it easy to build natural language interfaces using types.", "scripts": { "check": "pyright" diff --git a/python/src/typechat/__about__.py b/python/src/typechat/__about__.py index e3ca4347..bb204e1b 100644 --- a/python/src/typechat/__about__.py +++ b/python/src/typechat/__about__.py @@ -1,4 +1,4 @@ # SPDX-FileCopyrightText: Microsoft Corporation # # SPDX-License-Identifier: MIT -__version__ = "0.1.0" +__version__ = "0.3.0" diff --git a/python/tests/test_example_prompt_layouts.py b/python/tests/test_example_prompt_layouts.py new file mode 100644 index 00000000..46454be0 --- /dev/null +++ b/python/tests/test_example_prompt_layouts.py @@ -0,0 +1,123 @@ +import asyncio +import json +from datetime import datetime +from unittest.mock import AsyncMock, Mock + +import pytest +from examples.healthData import translator as health +from examples.healthData.schema import HealthDataResponse +from examples.math.program import TypeChatProgramTranslator, TypeChatProgramValidator, evaluate_json_program, program_schema_text +from examples.math.schema import MathAPI +from examples.multiSchema.router import TextRequestRouter +from typechat import Failure, PromptSection, Success, TypeChatValidator, python_type_to_typescript_schema + +from .test_translator import FixedModel + + +@pytest.mark.parametrize("legacy", [False, True], ids=["schema-first", "legacy"]) +def test_math_uses_program_and_api_schemas_and_repairs_programs(legacy: bool): + request = " Add two and three.\n" + rejected = 'Not a program:\n{"answer": 5}' + program = {"@steps": [{"@func": "add", "@args": [2, 3]}]} + model = FixedModel([rejected, json.dumps(program)]) + translator = TypeChatProgramTranslator(model, TypeChatProgramValidator(), MathAPI, use_legacy_prompt=legacy) + result = asyncio.run(translator.translate(request)) + assert isinstance(result, Success) and result.value == program + add = AsyncMock(return_value=5) + assert asyncio.run(evaluate_json_program(result.value, add)) == 5 + add.assert_awaited_once_with("add", [2, 3]) + + initial = model.request() + instructions = initial[0]["content"] + assert isinstance(instructions, str) and program_schema_text in instructions + assert python_type_to_typescript_schema(MathAPI).typescript_schema_str in instructions + assert "JSON program object with 2 spaces of indentation" in instructions + if legacy: + assert len(initial) == 1 and initial[0]["role"] == "user" + assert f"The following is a user request:\n'''\n{request}\n'''" in instructions + else: + assert initial == [{"role": "system", "content": instructions}, {"role": "user", "content": request}] + assert request not in instructions + repair = model.request(1) + assert repair[:-2] == initial + assert repair[-2] == {"role": "assistant", "content": rejected} + assert repair[-1]["role"] == "user" + assert "The JSON program object is invalid" in repair[-1]["content"] + assert "must have an array of @steps" in repair[-1]["content"] + + +def test_health_refreshes_clock_and_replays_only_validated_assistant_results(monkeypatch: pytest.MonkeyPatch): + clock = Mock() + clock.now.side_effect = [datetime(2026, 1, 1, 23, 59, 59), datetime(2026, 1, 2, 0, 1), datetime(2026, 1, 3, 12, 30)] + monkeypatch.setattr(health, "datetime", clock) + accepted = {"message": "Validated assistant result."} + rejected = '{"message": 42}' + model = FixedModel([json.dumps({**accepted, "extra": "Not validated."}), rejected, "Not JSON.", "{}"]) + instructions = "Application-owned health instructions." + translator = health.TranslatorWithHistory(model, TypeChatValidator(HealthDataResponse), HealthDataResponse, instructions) + + first = asyncio.run(translator.translate("First entry.")) + assert isinstance(first, Success) and first.value == accepted + first.value["message"] = "Changed by caller after validation." + failure = asyncio.run(translator.translate("Second entry.", prompt_preamble="External context.")) + assert isinstance(failure, Failure) + assert failure.value == {"message": 42} and failure.response_text == "Not JSON." + preamble: list[PromptSection] = [{"role": "user", "content": "Caller-supplied history."}] + original = preamble.copy() + assert asyncio.run(translator.translate("Third entry.", prompt_preamble=preamble)) == Success({}) + + first_prompt, failed_prompt, repair, third_prompt = [model.request(i) for i in range(4)] + assert clock.now.call_count == 3 + for prompt, stamp in [(first_prompt, "01 01, 2026 CURRENT TIME: 23:59:59"), + (failed_prompt, "01 02, 2026 CURRENT TIME: 00:01:00"), + (third_prompt, "01 03, 2026 CURRENT TIME: 12:30:00")]: + system = prompt[0]["content"] + assert prompt[0]["role"] == "system" and isinstance(system, str) + assert translator.schema_str in system and instructions in system and stamp in system + for text in ("First entry.", "Second entry.", "Third entry.", accepted["message"], "Not validated.", + rejected, "Not JSON.", "External context.", "Caller-supplied history."): + assert text not in system + assert all(instructions not in message["content"] for message in prompt[1:]) + history = {"role": "assistant", "content": json.dumps(accepted, indent=2)} + assert first_prompt[1:] == [{"role": "user", "content": "First entry."}] + assert failed_prompt[1:] == [{"role": "user", "content": "External context."}, history, + {"role": "user", "content": "Second entry."}] + assert repair[:-2] == failed_prompt and repair[-2] == {"role": "assistant", "content": rejected} + assert third_prompt[1:] == [*original, history, {"role": "user", "content": "Third entry."}] + assert preamble == original + + +def test_health_explicit_legacy_keeps_clock_and_history_in_combined_user_prompt(monkeypatch: pytest.MonkeyPatch): + clock = Mock() + clock.now.side_effect = [datetime(2026, 1, 1, 17), datetime(2026, 1, 2, 18)] + monkeypatch.setattr(health, "datetime", clock) + model = FixedModel(['{"message":"Previous answer."}', "{}"]) + translator = health.TranslatorWithHistory( + model, TypeChatValidator(HealthDataResponse), HealthDataResponse, "Health instructions.", use_legacy_prompt=True, + ) + asyncio.run(translator.translate("First request.")) + asyncio.run(translator.translate("Next request.", prompt_preamble="Caller context.")) + + context, combined = model.request(1) + assert context == {"role": "user", "content": "Caller context."} + assert combined["role"] == "user" and isinstance(combined["content"], str) + text = combined["content"] + assert "CURRENT TIME: 18:00:00" in text and "Health instructions." in text + assert json.dumps([{"source": "assistant", "body": {"message": "Previous answer."}}], indent=2) in text + assert "The following is a user request:\n'''\nNext request.\n'''" in text + assert "First request." not in text + + +def test_router_keeps_registered_table_separate_from_verbatim_request(): + model = FixedModel(['{"task_kind":"Math"}']) + handler = AsyncMock() + router = TextRequestRouter(model) + router.register_agent("Math", "Perform arithmetic.", handler) + request = " Add four and five.\n" + asyncio.run(router.route_request(request)) + handler.assert_awaited_once_with(request) + schema, table, user = model.request() + assert schema["role"] == table["role"] == "system" + assert "Perform arithmetic." in table["content"] + assert request not in schema["content"] and request not in table["content"] + assert user == {"role": "user", "content": request} diff --git a/site/src/docs/python/basic-usage.md b/site/src/docs/python/basic-usage.md index 23707a08..b38356d1 100644 --- a/site/src/docs/python/basic-usage.md +++ b/site/src/docs/python/basic-usage.md @@ -449,12 +449,9 @@ becomes `input_image` with the original reference in a flat omitted. Images are never flattened into text, including during translator repair. The translator's current request remains a string, and ordinary `translate(str)` -calls need no changes. Preamble messages remain before the combined schema/request -message; validation and repair keep the original context and append rejected -assistant text followed by user diagnostics. This does not adopt the alternative -prompt layout proposed in [#241](https://github.com/microsoft/TypeChat/pull/241). -Model completions remain text-only, and schema generation and strict result -validation are unchanged. +calls need no changes. The default [prompt layout](#prompt-layout-and-migration) +places image context after the schema instructions and before the request. +Model completions remain text-only, and schema generation and strict result validation are unchanged. Supply a provider/model that supports images and follow its supported file formats (for example PNG, JPEG, or WebP), accessible-URL requirements, image-count limits, @@ -586,11 +583,60 @@ translator = TypeChatJsonTranslator(model, validator, sentiment.Sentiment) When we are ready to translate a user request, we can call the `translate` method. -```ts -translator.translate("Hello world! šŸ™‚"); +```py +result = await translator.translate("Hello world! šŸ™‚") +``` + +### Prompt layout and migration + +In Python 0.3 the translator builds a `system` message with the application +schema, translation instructions, and JSON formatting rules. It then passes +through any `prompt_preamble` and sends the current request **once, unchanged** +as a `user` message. For example: + +```py +from typechat import PromptSection + +history: list[PromptSection] = [ + {"role": "user", "content": "I liked it."}, + {"role": "assistant", "content": '{"sentiment": "positive"}'}, +] +result = await translator.translate("Actually, I didn't like it.", prompt_preamble=history) +``` + +The roles here are `system`, `user`, `assistant`, `user`. History is +application-managed; omitting it starts an independent request. A nonempty +string preamble becomes one `user` message. Message lists retain their roles, +order, and content. Only label application-owned instructions as `system`; +the translator does not relabel or sanitize a caller's role assignments. + +**Existing custom prompts:** To retain the old layout (preamble, then one +combined schema/request `user` message), select it explicitly: + +```py +translator = TypeChatJsonTranslator(model, validator, sentiment.Sentiment, use_legacy_prompt=True) ``` -We'll come back to this. +The keyword-only option also preserves subclasses' `_create_request_prompt(self, intent)`. +To migrate a subclass, override `_create_system_prompt(self) -> str` instead. +It runs once per turn and takes no request or history. For example, return +`super()._create_system_prompt() + "\nUse the application's approved category names."`. +Keep user data and previous replies out of this hook. A subclass can implement +both hooks to support both layouts. Overriding only the old hook on the default +layout raises a `ValueError` before the model is called; its text is never promoted +to `system` or silently discarded. + +Both layouts validate the same way. A repair keeps the original messages and +appends the **raw** rejected `assistant` reply and a `user` diagnostic (customizable +with `_create_repair_prompt(self, validation_error)`). The default limit is one +repair. A final `Failure` may retain a rejected parsed value and the latest +response text, even if the latter could not be parsed. + +Model adapters must preserve the roles they receive or report an unsupported +prompt. A provider without system-message support needs explicit legacy mode; +there is no automatic fallback that flattens history. Role separation is not a +guarantee of correct answers, resistance to prompt injection, or authorization +to act on a validated result. ## Creating a "REPL" From 212170980c48de39dcab55a6d4fc785ce2ee50d2 Mon Sep 17 00:00:00 2001 From: Robert Gruen Date: Sun, 29 Nov 2026 12:23:27 -0800 Subject: [PATCH 3/7] Use one system message in the Python router and drawing examples Build example-specific instructions alongside the schema. Keep the agent table current on each request and preserve user-only drawing history. Cover both message layouts with offline regression tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- python/examples/drawing/demo.py | 14 +++-- python/examples/multiSchema/README.md | 4 ++ python/examples/multiSchema/router.py | 27 +++++---- python/tests/test_example_prompt_layouts.py | 62 ++++++++++++++++----- 4 files changed, 78 insertions(+), 29 deletions(-) diff --git a/python/examples/drawing/demo.py b/python/examples/drawing/demo.py index 436988a6..d30f466c 100644 --- a/python/examples/drawing/demo.py +++ b/python/examples/drawing/demo.py @@ -3,6 +3,7 @@ import tkinter as tk from dotenv import dotenv_values +from typing_extensions import override import schema from render import render_drawing @@ -18,12 +19,17 @@ ) +class DrawingTranslator(TypeChatJsonTranslator[schema.Drawing]): + @override + def _create_system_prompt(self) -> str: + return super()._create_system_prompt() + "\nReturn the complete drawing, applying all drawing requests in order." + + async def main(file_path: str | None): env_vals = dotenv_values() model = create_language_model(env_vals) validator = TypeChatValidator(schema.Drawing) - translator = TypeChatJsonTranslator(model, validator, schema.Drawing) - # print(translator._schema_str) + translator = DrawingTranslator(model, validator, schema.Drawing) window = tk.Tk() window.title("Click to continue...") @@ -31,9 +37,7 @@ async def main(file_path: str | None): canvas.pack(padx=10, pady=10) canvas.bind("", lambda event: window.quit()) - history: list[PromptSection] = [ - {"role": "system", "content": "Return the complete drawing, applying all drawing requests in order."}, - ] + history: list[PromptSection] = [] async def request_handler(request: str): print("[Sending request...]") diff --git a/python/examples/multiSchema/README.md b/python/examples/multiSchema/README.md index 9d8270de..76fc5cb2 100644 --- a/python/examples/multiSchema/README.md +++ b/python/examples/multiSchema/README.md @@ -2,6 +2,10 @@ This application demonstrates a simple way to write a **super-app** that automatically routes user requests to child apps. +The router sends the classification schema and the current list of registered agents +in one system message. The user's request stays in its own message and is passed +unchanged to the selected app. + In this example, the child apps are existing TypeChat chat examples: * CoffeeShop diff --git a/python/examples/multiSchema/router.py b/python/examples/multiSchema/router.py index 7062ea80..8fc21489 100644 --- a/python/examples/multiSchema/router.py +++ b/python/examples/multiSchema/router.py @@ -1,5 +1,5 @@ import json -from typing_extensions import Any, Callable, Awaitable, TypedDict, Annotated +from typing_extensions import Any, Callable, Awaitable, TypedDict, Annotated, Mapping, override from typechat import Failure, TypeChatValidator, TypeChatLanguageModel, TypeChatJsonTranslator @@ -13,27 +13,34 @@ class TaskClassification(TypedDict): task_kind: Annotated[str, "Describe the kind of task to perform."] +class _RouterTranslator(TypeChatJsonTranslator[TaskClassification]): + def __init__(self, model: TypeChatLanguageModel, agents: Mapping[str, AgentInfo]): + super().__init__(model, TypeChatValidator(TaskClassification), TaskClassification) + self._agents = agents + + @override + def _create_system_prompt(self) -> str: + classes = {name: agent["description"] for name, agent in self._agents.items()} + return ( + super()._create_system_prompt() + + f"\nClassify the user request using this table of registered agents:\n{json.dumps(classes, indent=2)}" + ) + + class TextRequestRouter: _current_agents: dict[str, AgentInfo] - _validator: TypeChatValidator[TaskClassification] - _translator: TypeChatJsonTranslator[TaskClassification] def __init__(self, model: TypeChatLanguageModel): super().__init__() - self._validator = TypeChatValidator(TaskClassification) - self._translator = TypeChatJsonTranslator(model, self._validator, TaskClassification) self._current_agents = {} + self._translator = _RouterTranslator(model, self._current_agents) def register_agent(self, name: str, description: str, handler: Callable[[str], Awaitable[Any]]): agent = AgentInfo(name=name, description=description, handler=handler) self._current_agents[name] = agent async def route_request(self, line: str): - classes = {name: agent["description"] for name, agent in self._current_agents.items()} - result = await self._translator.translate(line, prompt_preamble=[{ - "role": "system", - "content": f"Classify the user request using this table of registered agents:\n{json.dumps(classes, indent=2)}", - }]) + result = await self._translator.translate(line) if isinstance(result, Failure): print("Translation Failed āŒ") print(f"Context: {result.message}") diff --git a/python/tests/test_example_prompt_layouts.py b/python/tests/test_example_prompt_layouts.py index 46454be0..7fb76b3b 100644 --- a/python/tests/test_example_prompt_layouts.py +++ b/python/tests/test_example_prompt_layouts.py @@ -1,14 +1,18 @@ import asyncio import json +import runpy +import sys from datetime import datetime -from unittest.mock import AsyncMock, Mock +from pathlib import Path +from unittest.mock import AsyncMock, Mock, patch import pytest +from examples.drawing import schema as drawing_schema from examples.healthData import translator as health from examples.healthData.schema import HealthDataResponse from examples.math.program import TypeChatProgramTranslator, TypeChatProgramValidator, evaluate_json_program, program_schema_text from examples.math.schema import MathAPI -from examples.multiSchema.router import TextRequestRouter +from examples.multiSchema.router import TaskClassification, TextRequestRouter from typechat import Failure, PromptSection, Success, TypeChatValidator, python_type_to_typescript_schema from .test_translator import FixedModel @@ -108,16 +112,46 @@ def test_health_explicit_legacy_keeps_clock_and_history_in_combined_user_prompt( assert "First request." not in text -def test_router_keeps_registered_table_separate_from_verbatim_request(): - model = FixedModel(['{"task_kind":"Math"}']) - handler = AsyncMock() +def test_router_combines_schema_and_current_registry_in_one_system_message(): + model = FixedModel(['{"task_kind":"Math"}', '{"task_kind":"Calendar"}']) + math_handler, calendar_handler = AsyncMock(), AsyncMock() router = TextRequestRouter(model) - router.register_agent("Math", "Perform arithmetic.", handler) - request = " Add four and five.\n" - asyncio.run(router.route_request(request)) - handler.assert_awaited_once_with(request) - schema, table, user = model.request() - assert schema["role"] == table["role"] == "system" - assert "Perform arithmetic." in table["content"] - assert request not in schema["content"] and request not in table["content"] - assert user == {"role": "user", "content": request} + router.register_agent("Math", "Perform arithmetic.", math_handler) + first, second = " Add four and five.\n", "Schedule lunch." + asyncio.run(router.route_request(first)) + router.register_agent("Calendar", "Schedule events.", calendar_handler) + asyncio.run(router.route_request(second)) + math_handler.assert_awaited_once_with(first) + calendar_handler.assert_awaited_once_with(second) + + schema = python_type_to_typescript_schema(TaskClassification).typescript_schema_str + for index, request in enumerate((first, second)): + system, user = model.request(index) + instructions = system["content"] + assert system["role"] == "system" and isinstance(instructions, str) + assert schema in instructions and '"Math": "Perform arithmetic."' in instructions + assert ('"Calendar": "Schedule events."' in instructions) == (index == 1) + assert request not in instructions + assert user == {"role": "user", "content": request} + + +def test_drawing_demo_keeps_only_prior_requests_in_history(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + model = FixedModel(['{"type":"Drawing","items":[]}'] * 2) + first, second = "Draw a box.\n", "Make it blue.\n" + commands = tmp_path / "drawing.txt" + commands.write_text(first + second, encoding="utf-8") + demo = Path(drawing_schema.__file__).with_name("demo.py") + monkeypatch.setattr(sys, "argv", [str(demo), str(commands)]) + monkeypatch.setattr("dotenv.dotenv_values", dict) + monkeypatch.setattr("typechat.create_language_model", Mock(return_value=model)) + with patch.dict(sys.modules, {"tkinter": Mock(), "schema": drawing_schema, "render": Mock()}): + runpy.run_path(str(demo), run_name="__main__") + + system, user = model.request() + instructions = system["content"] + assert system["role"] == "system" and isinstance(instructions, str) + assert python_type_to_typescript_schema(drawing_schema.Drawing).typescript_schema_str in instructions + assert "Return the complete drawing, applying all drawing requests in order." in instructions + assert first not in instructions and second not in instructions + assert user == {"role": "user", "content": first} + assert model.request(1) == [system, user, {"role": "user", "content": second}] From 53d62cd835d0f461c913128b35980eec9266d53f Mon Sep 17 00:00:00 2001 From: Robert Gruen Date: Sun, 29 Nov 2026 12:38:36 -0800 Subject: [PATCH 4/7] Preserve multipart user requests in Python legacy translations Accept the existing PromptContent type for the current request. Frame legacy multipart content with text parts instead of stringifying images, while retaining the original string prompts, role boundaries, and repair behavior. Update the example hooks and verify Chat Completions and Responses requests offline. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- python/README.md | 13 +++-- python/examples/healthData/translator.py | 11 ++--- python/examples/math/program.py | 4 +- python/src/typechat/_internal/translator.py | 55 ++++++++++++++------- python/tests/test_multimodal_model.py | 44 +++++++++++++++++ python/tests/test_prompt_types.py | 4 ++ python/tests/test_responses_model.py | 23 +++++++++ python/tests/test_translator.py | 22 +++++++++ site/src/docs/python/basic-usage.md | 25 ++++++++-- 9 files changed, 167 insertions(+), 34 deletions(-) diff --git a/python/README.md b/python/README.md index 7e42dab3..d64a1af2 100644 --- a/python/README.md +++ b/python/README.md @@ -65,7 +65,9 @@ message. The translator does not remember earlier turns for you. To keep the pre-0.3 combined user prompt, construct `TypeChatJsonTranslator(model, validator, target_type, use_legacy_prompt=True)`. This keyword-only option keeps existing `_create_request_prompt(self, intent)` -overrides in the **user** role. For the new default, customize +overrides for string requests in the **user** role. For custom multipart legacy +requests, return the text before and after the request from `_get_legacy_prompt_parts(self)`. +For the new default, customize `_create_system_prompt(self)` with application-owned instructions only. See the [migration guide](../site/src/docs/python/basic-usage.md#prompt-layout-and-migration) and the [math](./examples/math/program.py) and [health-data](./examples/healthData/translator.py) examples. @@ -166,9 +168,12 @@ user/system text to `input_text`, assistant text to `output_text`, and images to `input_image` with a flat `image_url` string and optional `detail`, preserving order, references, and omitted detail. -`translate` still takes a string request. Image context stays in the preamble, -including during repair: the translator appends the raw assistant reply and a -user diagnostic without rewriting earlier messages. +`translate` accepts `PromptContent` directly: a string or an ordered list of +tagged text and image parts in one user message. To send several user messages, +pass the earlier ones in `prompt_preamble`. Legacy mode keeps string prompts +unchanged and places its instructions around multipart requests as text parts +in the same user message; the images stay images. Both layouts keep the +original messages during repair. Successful model completions remain text-only. Authentication, HTTP controls, and configured-client ownership remain unchanged. diff --git a/python/examples/healthData/translator.py b/python/examples/healthData/translator.py index 661a307f..7c73c91f 100644 --- a/python/examples/healthData/translator.py +++ b/python/examples/healthData/translator.py @@ -4,7 +4,7 @@ from pydantic_core import to_jsonable_python from typing_extensions import TypeVar, override -from typechat import TypeChatValidator, TypeChatLanguageModel, TypeChatJsonTranslator, Result, Success, PromptSection +from typechat import TypeChatValidator, TypeChatLanguageModel, TypeChatJsonTranslator, Result, Success, PromptContent, PromptSection T = TypeVar("T", covariant=True) @@ -25,7 +25,7 @@ def __init__( self._additional_agent_instructions = additional_agent_instructions @override - async def translate(self, input: str, *, prompt_preamble: str | list[PromptSection] | None = None) -> Result[T]: + async def translate(self, input: PromptContent, *, prompt_preamble: str | list[PromptSection] | None = None) -> Result[T]: if not self._use_legacy_prompt and self._chat_history: context: list[PromptSection] = [] if isinstance(prompt_preamble, str): @@ -47,11 +47,11 @@ def _create_system_prompt(self) -> str: return f"{super()._create_system_prompt()}\n{_clock_instructions()}\n\n{self._additional_agent_instructions}" @override - def _create_request_prompt(self, intent: str) -> str: + def _get_legacy_prompt_parts(self) -> tuple[str, str]: history = [{"source": "assistant", "body": body} for body in self._chat_history] history_str = json.dumps(history, indent=2, allow_nan=False) - prompt = F""" + return f""" user: You are a service that translates user requests into JSON objects of type "{self.type_name}" according to the following TypeScript definitions: ''' {self.schema_str} @@ -70,8 +70,7 @@ def _create_request_prompt(self, intent: str) -> str: user: The following is a user request: ''' -{intent} +""", """ ''' The following is the user request translated into a JSON object with 2 spaces of indentation and no properties with the value undefined: """ - return prompt diff --git a/python/examples/math/program.py b/python/examples/math/program.py index fdc2f639..1e5b449f 100644 --- a/python/examples/math/program.py +++ b/python/examples/math/program.py @@ -147,11 +147,11 @@ def _create_system_prompt(self) -> str: """ @override - def _create_request_prompt(self, intent: str) -> str: + def _get_legacy_prompt_parts(self) -> tuple[str, str]: return f"""{self._program_instructions()} The following is a user request: ''' -{intent} +""", """ ''' The following is the user request translated into a JSON program object with 2 spaces of indentation and no properties with the value undefined: """ diff --git a/python/src/typechat/_internal/translator.py b/python/src/typechat/_internal/translator.py index 9d4dc573..bab2b704 100644 --- a/python/src/typechat/_internal/translator.py +++ b/python/src/typechat/_internal/translator.py @@ -3,7 +3,7 @@ import pydantic_core -from typechat._internal.model import PromptSection, TypeChatLanguageModel +from typechat._internal.model import PromptContent, PromptSection, TypeChatLanguageModel from typechat._internal.result import Failure, Result, Success from typechat._internal.ts_conversion import python_type_to_typescript_schema from typechat._internal.validator import TypeChatValidator @@ -53,7 +53,7 @@ def __init__( self.type_name = conversion_result.typescript_type_reference self.schema_str = conversion_result.typescript_schema_str - async def translate(self, input: str, *, prompt_preamble: str | list[PromptSection] | None = None) -> Result[T]: + async def translate(self, input: PromptContent, *, prompt_preamble: str | list[PromptSection] | None = None) -> Result[T]: """ Translates a natural language request into an object of type `T`. If the JSON object returned by the language model fails to validate, repair attempts will be made up until `_max_repair_attempts`. @@ -63,7 +63,7 @@ async def translate(self, input: str, *, prompt_preamble: str | list[PromptSecti from different attempts if a repair response couldn't be parsed. Args: - input: A natural language request. + input: One user request: a string or an ordered list of tagged text and image parts. prompt_preamble: Context placed before the current user message, after the default system instructions. A nonempty string becomes one user message; a list keeps its roles. """ @@ -71,15 +71,11 @@ async def translate(self, input: str, *, prompt_preamble: str | list[PromptSecti messages: list[PromptSection] = [] if not self._use_legacy_prompt: - # Don't silently bypass a more specific legacy hook, including one assigned to this instance. - for owner in (self, *type(self).__mro__): - if "_create_system_prompt" in vars(owner): - break - if "_create_request_prompt" in vars(owner): - raise ValueError( - "_create_request_prompt is a legacy hook. Pass use_legacy_prompt=True, or override " - + "_create_system_prompt(self) with application instructions only (no request or history)." - ) + if self._has_unmigrated_request_hook("_create_system_prompt"): + raise ValueError( + "_create_request_prompt is a legacy hook. Pass use_legacy_prompt=True, or override " + + "_create_system_prompt(self) with application instructions only (no request or history)." + ) messages.append({"role": "system", "content": self._create_system_prompt()}) if prompt_preamble: @@ -87,7 +83,19 @@ async def translate(self, input: str, *, prompt_preamble: str | list[PromptSecti prompt_preamble = [{"role": "user", "content": prompt_preamble}] messages.extend(prompt_preamble) - user_prompt = self._create_request_prompt(input) if self._use_legacy_prompt else input + user_prompt: PromptContent = input + if self._use_legacy_prompt: + match input: + case str(): + user_prompt = self._create_request_prompt(input) + case list(): + if self._has_unmigrated_request_hook("_get_legacy_prompt_parts"): + raise ValueError( + "_create_request_prompt accepts text only. Override _get_legacy_prompt_parts(self) " + + "for multipart requests, or pass a string request with images in prompt_preamble." + ) + prefix, suffix = self._get_legacy_prompt_parts() + user_prompt = [{"type": "text", "text": prefix}, *input, {"type": "text", "text": suffix}] messages.append({"role": "user", "content": user_prompt}) num_repairs_attempted = 0 @@ -140,6 +148,15 @@ async def translate(self, input: str, *, prompt_preamble: str | list[PromptSecti messages.append({"role": "assistant", "content": text_response}) messages.append({"role": "user", "content": self._create_repair_prompt(failure.message)}) + def _has_unmigrated_request_hook(self, replacement: str) -> bool: + # A more specific text hook (including an instance override) must not be silently bypassed. + for owner in (self, *type(self).__mro__): + if replacement in vars(owner): + return False + if "_create_request_prompt" in vars(owner): + return True + return False + def _create_system_prompt(self) -> str: """Build application-owned instructions for this turn, without the request or conversation history.""" return f""" @@ -151,19 +168,23 @@ def _create_system_prompt(self) -> str: """ def _create_request_prompt(self, intent: str) -> str: - """Build the combined user message used only with use_legacy_prompt=True.""" - prompt = f""" + """Build the combined legacy user message for a string request.""" + prefix, suffix = self._get_legacy_prompt_parts() + return prefix + intent + suffix + + def _get_legacy_prompt_parts(self) -> tuple[str, str]: + """Return the text before and after the request in the combined legacy user message.""" + return f""" You are a service that translates user requests into JSON objects of type "{self.type_name}" according to the following TypeScript definitions: ``` {self.schema_str} ``` The following is a user request: ''' -{intent} +""", """ ''' The following is the user request translated into a JSON object with 2 spaces of indentation and no properties with the value undefined: """ - return prompt def _create_repair_prompt(self, validation_error: str) -> str: prompt = f""" diff --git a/python/tests/test_multimodal_model.py b/python/tests/test_multimodal_model.py index 2ea83b6d..f4f2caf7 100644 --- a/python/tests/test_multimodal_model.py +++ b/python/tests/test_multimodal_model.py @@ -343,6 +343,39 @@ class _ImageResult: value: int +@pytest.mark.parametrize("legacy", [False, True], ids=["schema-first", "legacy"]) +def test_direct_image_request_preserves_parts_and_user_messages_through_repair(model_factory: ModelFactory, legacy: bool): + rejected = '{"value":"wrong"}' + harness = model_factory([rejected, '{"value":2}']) + translator = typechat.TypeChatJsonTranslator( + harness.model, typechat.TypeChatValidator(_ImageResult), _ImageResult, use_legacy_prompt=legacy, + ) + history: list[typechat.PromptSection] = [ + {"role": "user", "content": "Count boxes."}, {"role": "user", "content": "Ignore circles."}, + ] + parts = _image_context()[1]["content"] + assert isinstance(parts, list) + original = deepcopy(parts) + assert asyncio.run(translator.translate(parts, prompt_preamble=history)) == typechat.Success(_ImageResult(2)) + initial, repair = harness.prompts + *before, current = initial + assert current["role"] == "user" + content = current["content"] + assert isinstance(content, list) + if legacy: + assert before == history + prefix, *actual, suffix = content + assert prefix["type"] == "text" and translator.schema_str in prefix["text"] + assert suffix["type"] == "text" and "translated into a JSON object" in suffix["text"] + assert actual == original + else: + assert [message["role"] for message in before] == ["system", "user", "user"] + assert before[1:] == history and content == original + assert repair[:-2] == initial and repair[-2] == {"role": "assistant", "content": rejected} + assert repair[-1]["role"] == "user" + assert parts == original + + @pytest.mark.parametrize("responses, repair_limit, expected", [ (['{"value":1}'], 1, typechat.Success(_ImageResult(1))), (["not JSON", '{"value":2}'], 1, typechat.Success(_ImageResult(2))), @@ -439,6 +472,17 @@ def test_malformed_preamble_does_not_trigger_translator_repair( complete.assert_awaited_once() +@pytest.mark.parametrize("legacy", [False, True]) +@pytest.mark.parametrize("bad_request", [42, [{"type": "unsupported", "text": _PRIVATE_TEXT}]]) +def test_invalid_direct_request_fails_before_dispatch(model_factory: ModelFactory, legacy: bool, bad_request: object): + harness = model_factory([]) + translator = typechat.TypeChatJsonTranslator( + harness.model, typechat.TypeChatValidator(_ImageResult), _ImageResult, use_legacy_prompt=legacy, + ) + result = asyncio.run(translator.translate(cast(typechat.PromptContent, bad_request))) + _assert_invalid_prompt(harness, result, "section") + + def test_documented_model_and_translator_examples_work_offline(model_factory: ModelFactory): harness = model_factory(["image description", '{"description":"two images"}']) text, data = asyncio.run(inspect_images(harness.model, "aW1hZ2U=")) diff --git a/python/tests/test_prompt_types.py b/python/tests/test_prompt_types.py index 9e472ca3..6c9f53b0 100644 --- a/python/tests/test_prompt_types.py +++ b/python/tests/test_prompt_types.py @@ -95,6 +95,10 @@ async def check_completion_and_request_types( ) assert_type(await inspect_images(responses_model, "aW1hZ2U="), tuple[Result[str], Result[ImageDescription]]) assert_type(await translator.translate("existing text"), Result[ImageDescription]) + assert_type(await translator.translate([ + {"type": "text", "text": "Describe this image."}, + {"type": "image_url", "image_url": {"url": "https://adatum.com/photo.png"}}, + ]), Result[ImageDescription]) assert_type( await translator.translate("existing text", prompt_preamble="context"), Result[ImageDescription], diff --git a/python/tests/test_responses_model.py b/python/tests/test_responses_model.py index 89f7aaad..a1a18409 100644 --- a/python/tests/test_responses_model.py +++ b/python/tests/test_responses_model.py @@ -798,6 +798,29 @@ class _Value: value: str +@pytest.mark.parametrize("use_client", [False, True]) +@pytest.mark.parametrize("legacy", [False, True], ids=["schema-first", "legacy"]) +def test_direct_image_request_uses_responses_wire_parts(use_client: bool, legacy: bool, mock_client: MockClient): + model, requests = _model([_response('{"value":"ok"}')], use_client, mock_client) + translator = typechat.TypeChatJsonTranslator(model, typechat.TypeChatValidator(_Value), _Value, use_legacy_prompt=legacy) + sections, wire = _image_prompts(detail="low") + parts = sections[1]["content"] + + async def run() -> None: + async with _open_model(model): + assert await translator.translate(parts) == typechat.Success(_Value("ok")) + + asyncio.run(run()) + messages = requests[0]["input"] + assert [message["role"] for message in messages] == (["user"] if legacy else ["system", "user"]) + content = messages[-1]["content"] + assert isinstance(content, list) + if legacy: + assert content[0]["type"] == content[-1]["type"] == "input_text" + content = content[1:-1] + assert content == wire[1]["content"] + + @pytest.mark.parametrize("use_client", [False, True]) @pytest.mark.parametrize("with_images", [False, True]) def test_translator_accepts_valid_responses_without_repair( diff --git a/python/tests/test_translator.py b/python/tests/test_translator.py index 9d6e5a4b..ee12d358 100644 --- a/python/tests/test_translator.py +++ b/python/tests/test_translator.py @@ -214,6 +214,28 @@ def _create_request_prompt(self, intent: str) -> str: return f"custom request: {intent}" +def test_legacy_multipart_request_requires_matching_custom_framing(): + parts: typechat.PromptContent = [{"type": "image_url", "image_url": {"url": "https://adatum.com/photo.png"}}] + model = FixedModel([_VALID, _VALID]) + text_only = _LegacyOnlyTranslator(model, v, ExampleABC, use_legacy_prompt=True) + with pytest.raises(ValueError, match=r"_create_request_prompt.*_get_legacy_prompt_parts.*prompt_preamble"): + asyncio.run(text_only.translate(parts)) + assert model.conversation == [] + + class FramedTranslator(_LegacyOnlyTranslator): + @override + def _get_legacy_prompt_parts(self) -> tuple[str, str]: + return "custom opening", "custom closing" + + translator = FramedTranslator(model, v, ExampleABC, use_legacy_prompt=True) + asyncio.run(translator.translate(_CURRENT)) + asyncio.run(translator.translate(parts)) + assert model.request() == [{"role": "user", "content": f"custom request: {_CURRENT}"}] + assert model.request(1) == [{"role": "user", "content": [ + {"type": "text", "text": "custom opening"}, *parts, {"type": "text", "text": "custom closing"}, + ]}] + + def test_explicit_legacy_uses_custom_request_prompt_after_preamble(): model = FixedModel([_VALID]) translator = _LegacyOnlyTranslator(model, v, ExampleABC, use_legacy_prompt=True) diff --git a/site/src/docs/python/basic-usage.md b/site/src/docs/python/basic-usage.md index b38356d1..a63dacd6 100644 --- a/site/src/docs/python/basic-usage.md +++ b/site/src/docs/python/basic-usage.md @@ -448,10 +448,20 @@ becomes `input_image` with the original reference in a flat `image_url` field. Supplied `detail` moves alongside it; omitted detail remains omitted. Images are never flattened into text, including during translator repair. -The translator's current request remains a string, and ordinary `translate(str)` -calls need no changes. The default [prompt layout](#prompt-layout-and-migration) -places image context after the schema instructions and before the request. -Model completions remain text-only, and schema generation and strict result validation are unchanged. +The current request can be a string or an ordered list of text and image parts: + +```py +result = await translator.translate([ + {"type": "text", "text": "Describe this image."}, + {"type": "image_url", "image_url": {"url": "https://adatum.com/photo.png"}}, +]) +``` + +The list is **one user message**. For several messages, pass earlier ones as +role-tagged sections in `prompt_preamble`, not as parts of the current request. +Both [prompt layouts](#prompt-layout-and-migration) preserve images in either +position, including during repair. Model completions remain text-only; schema +generation and strict result validation are unchanged. Supply a provider/model that supports images and follow its supported file formats (for example PNG, JPEG, or WebP), accessible-URL requirements, image-count limits, @@ -617,7 +627,12 @@ combined schema/request `user` message), select it explicitly: translator = TypeChatJsonTranslator(model, validator, sentiment.Sentiment, use_legacy_prompt=True) ``` -The keyword-only option also preserves subclasses' `_create_request_prompt(self, intent)`. +For strings, the keyword-only option also preserves subclasses' `_create_request_prompt(self, intent)`. +For multipart requests, legacy mode wraps the original parts with opening and +closing text parts in the same `user` message. To customize those strings, +override `_get_legacy_prompt_parts(self) -> tuple[str, str]`. A subclass with +only the old text hook must either provide this framing or keep passing a +string request with images in the preamble. It is never handed a stringified image. To migrate a subclass, override `_create_system_prompt(self) -> str` instead. It runs once per turn and takes no request or history. For example, return `super()._create_system_prompt() + "\nUse the application's approved category names."`. From bf5ab0041682b174a6d2c5354052d277a848d263 Mon Sep 17 00:00:00 2001 From: Robert Gruen Date: Sun, 29 Nov 2026 12:49:52 -0800 Subject: [PATCH 5/7] Preserve multipart requests in TypeScript translations Accept PromptContent directly in both layouts and frame legacy requests without stringifying images. Keep string hooks compatible and share Chat Completions and Responses serialization across HTTP and client adapters. Cover program prompts, repair, and request bodies with offline tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- site/src/docs/typescript/basic-usage.md | 22 ++++++- typescript/README.md | 11 ++-- .../examples/healthData/src/translator.ts | 6 +- typescript/src/model.ts | 41 +++++++------ typescript/src/ts/program.ts | 13 ++-- typescript/src/typechat.ts | 56 +++++++++++++----- typescript/test/program.test.ts | 26 +++++++- typescript/test/prompt-layout.test.ts | 59 ++++++++++++++++++- typescript/tests/examples.test.mjs | 7 ++- typescript/tests/model.test.mjs | 43 +++++++++++++- 10 files changed, 224 insertions(+), 60 deletions(-) diff --git a/site/src/docs/typescript/basic-usage.md b/site/src/docs/typescript/basic-usage.md index cd19e381..dcb93a72 100644 --- a/site/src/docs/typescript/basic-usage.md +++ b/site/src/docs/typescript/basic-usage.md @@ -416,6 +416,19 @@ By default the translator sends: 2. Any **caller-supplied context**, in its original order and roles. A string preamble becomes one user message. 3. One **user** message containing the current request exactly as passed to `translate`, without quoting or other wrappers. +The current request can be text or one ordered array of text and image parts: + +```ts +const result = await translator.translate([ + { type: "text", text: "What color is the square?" }, + { type: "image_url", image_url: { url: "https://adatum.com/square.png", detail: "low" } } +]); +``` + +Both layouts keep the image in the user message, including during repair. To send +multiple user messages, put the earlier ones in the second argument. Chat Completions +and Responses encode the same public parts in their respective wire formats. + TypeChat does not store conversation history. For a follow-up, pass prior turns as the second argument, **not** as part of the new request: ```ts @@ -445,7 +458,7 @@ it asks for a JSON **Program** with `@steps`, provides the Program definitions * ### Migrating a 0.2 request hook or model If you need the previous layout, select it when constructing the translator. This preserves the combined schema/request **user** prompt -and the `createRequestPrompt(request)` hook, including hooks that return structured content: +and the `createRequestPrompt(request)` hook for string requests, including hooks that return structured content: ```ts const legacy = createJsonTranslator(model, validator, { promptLayout: "legacy" }); @@ -453,6 +466,13 @@ const legacy = createJsonTranslator(model, validator, { promptLayout: "legacy" } legacy.createRequestPrompt = myExistingRequestPrompt; ``` +For multipart requests in legacy mode, opening and closing instructions are text parts +in the same user message, not a string representation of its images. To customize them, +set `getLegacyPromptParts()` to return `[openingText, closingText]` (including your +schema and output instructions). This also frames ordinary string requests. If you +replace `createRequestPrompt`, a direct multipart request returns an error before +dispatch; migrate the hook to `getLegacyPromptParts` or pass a string with images in the preamble. + `createProgramTranslator` accepts the same option. In the default layout an override of `createRequestPrompt` returns a migration error from `translate` before a model call; TypeChat neither ignores the override nor calls it to build a system message. To migrate, move just the trusted instructions into `createSystemPrompt()` and pass the context as a preamble. diff --git a/typescript/README.md b/typescript/README.md index 2f5c8985..3eaf0d34 100644 --- a/typescript/README.md +++ b/typescript/README.md @@ -67,13 +67,16 @@ JavaScript and declarations in `dist/esm`. `createJsonTranslator` sends the schema and JSON output instructions as a system message, then caller-supplied context in its original roles and order, then the exact request as a user message. -Extend `translator.createSystemPrompt()` with application-owned instructions only; pass history or image -parts as the second argument to `translate`, not as part of the system message. `typechat/ts`'s +The request can be a string or an ordered array of text and image parts. Each array is one user +message; pass additional messages as the second argument to `translate`. Neither images nor history +belong in `translator.createSystemPrompt()`. `typechat/ts`'s `createProgramTranslator` describes both the JSON Program to return and the API it may call. To keep the 0.2 layout or an existing `createRequestPrompt(request)` override, explicitly pass -`{ promptLayout: "legacy" }` as the factory's third argument. Without that option a request-hook -override produces a migration error before dispatch. Validation, repair, and model retry settings +`{ promptLayout: "legacy" }` as the factory's third argument. Legacy string prompts are unchanged; +multipart requests keep the original parts between two text parts in the same user message. +To customize both kinds, implement `getLegacyPromptParts()` instead of replacing the string-only +`createRequestPrompt`. Validation, repair, and model retry settings are independent of layout. See the [TypeScript usage and migration examples](https://microsoft.github.io/TypeChat/docs/typescript/basic-usage/). ### Running the tests diff --git a/typescript/examples/healthData/src/translator.ts b/typescript/examples/healthData/src/translator.ts index 8d052595..a46c654e 100644 --- a/typescript/examples/healthData/src/translator.ts +++ b/typescript/examples/healthData/src/translator.ts @@ -1,4 +1,4 @@ -import { PromptSection, Result, TypeChatLanguageModel, createJsonTranslator, TypeChatJsonTranslator } from "typechat"; +import { PromptContent, PromptSection, Result, TypeChatLanguageModel, createJsonTranslator, TypeChatJsonTranslator } from "typechat"; import { createTypeScriptJsonValidator } from "typechat/ts"; export interface TranslatorWithHistory { @@ -6,7 +6,7 @@ export interface TranslatorWithHistory { _maxPromptLength: number; _additionalAgentInstructions: string; _translator: TypeChatJsonTranslator; - translate(request: string): Promise>; + translate(request: PromptContent): Promise>; } export function createHealthDataTranslator(model: TypeChatLanguageModel, schema: string, typename: string, additionalAgentInstructions: string): TranslatorWithHistory { @@ -34,7 +34,7 @@ export function createHealthDataTranslator(model: TypeChatLang return customtranslator; - async function translate(request: string): Promise> { + async function translate(request: PromptContent): Promise> { const response = await _translator.translate(request, _chatHistory); if (response.success) { _chatHistory.push({ role: "assistant", content: JSON.stringify(response.data, undefined, 2) }); diff --git a/typescript/src/model.ts b/typescript/src/model.ts index b34d69bc..95b6e64a 100644 --- a/typescript/src/model.ts +++ b/typescript/src/model.ts @@ -304,15 +304,9 @@ export function createOpenAILanguageModelFromClient(client: ChatCompletionClient } return { async complete(prompt) { - const messages = clientMessages(prompt); + const messages = normalizeMessages(prompt); if (!messages.success) return messages; - const input = typeof prompt === "string" ? prompt : messages.data.map(message => ({ - role: message.role, - content: typeof message.content === "string" ? message.content : - message.content.map((part): ClientResponseContent => part.type === "text" ? - { type: "input_text", text: part.text } : - { type: "input_image", image_url: part.image_url.url, detail: part.image_url.detail ?? "auto" }) - })); + const input = typeof prompt === "string" ? prompt : responsesMessages(messages.data); return finish(await client.responses.create({ model, input, temperature: 0, stream: false })); } }; @@ -322,7 +316,7 @@ export function createOpenAILanguageModelFromClient(client: ChatCompletionClient } return { async complete(prompt) { - const messages = clientMessages(prompt); + const messages = normalizeMessages(prompt); if (!messages.success) return messages; return finish(await client.chat.completions.create({ model, messages: messages.data, temperature: 0, n: 1, stream: false @@ -343,7 +337,17 @@ function validateAuthentication(apiKey: string | undefined, provider: TokenProvi } } -function clientMessages(prompt: string | PromptSection[]): Result { +function responsesMessages(messages: ClientMessage[]) { + return messages.map(({ role, content }) => ({ + role, + content: typeof content === "string" ? content : + content.map((part): ClientResponseContent => part.type === "text" ? + { type: "input_text", text: part.text } : + { type: "input_image", image_url: part.image_url.url, detail: part.image_url.detail ?? "auto" }) + })); +} + +function normalizeMessages(prompt: string | PromptSection[]): Result { const sections: PromptSection[] = typeof prompt === "string" ? [{ role: "user", content: prompt }] : prompt; const messages: ClientMessage[] = []; for (const { role, content } of sections) { @@ -419,6 +423,11 @@ function createFetchLanguageModel(url: string, headers: object, defaultParams: o async function complete(prompt: string | PromptSection[]) { const responses: TypeChatResponseMetadata[] = []; const finish = (result: Result) => withResponseMetadata(result, responses); + const messages = normalizeMessages(prompt); + if (!messages.success) return finish(messages); + const payload = responsesApi ? + { input: typeof prompt === "string" ? prompt : responsesMessages(messages.data) } : + { messages: messages.data, n: 1 }; dispatcherPromise ??= resolveProxyDispatcher(proxy); let dispatcher: RequestInit["dispatcher"]; try { @@ -431,20 +440,10 @@ function createFetchLanguageModel(url: string, headers: object, defaultParams: o const retryPauseMs = model.retryPauseMs ?? 1000; const timeoutMs = model.timeoutMs ?? defaultTimeoutMs; const maxResponseBytes = model.maxResponseBytes ?? defaultMaxResponseBytes; - const messages = typeof prompt === "string" ? [{ role: "user", content: prompt }] : prompt; while (true) { const options: RequestInit = { method: "POST", - body: JSON.stringify(responsesApi ? { - ...defaultParams, - input: prompt, - temperature: 0 - } : { - ...defaultParams, - messages, - temperature: 0, - n: 1 - }), + body: JSON.stringify({ ...defaultParams, ...payload, temperature: 0 }), headers: { "content-type": "application/json", ...headers diff --git a/typescript/src/ts/program.ts b/typescript/src/ts/program.ts index 8947afd3..6ec6e2cf 100644 --- a/typescript/src/ts/program.ts +++ b/typescript/src/ts/program.ts @@ -225,7 +225,10 @@ export function createProgramTranslator(model: TypeChatLanguageModel, schema: st `\`\`\`\n${validator.getSchemaText()}\n\`\`\`\n` + `Return only a JSON object of type Program with 2 spaces of indentation and no properties with the value undefined.`; if (options?.promptLayout === "legacy") { - translator.createRequestPrompt = createRequestPrompt; + translator.getLegacyPromptParts = () => [ + describeProgram() + `\`\`\`\n${validator.getSchemaText()}\`\`\`\nThe following is a user request:\n"""\n`, + `\n"""\nThe following is the user request translated into a JSON program object with 2 spaces of indentation and no properties with the value undefined:\n` + ]; } translator.createRepairPrompt = createRepairPrompt; return translator; @@ -236,14 +239,6 @@ export function createProgramTranslator(model: TypeChatLanguageModel, schema: st `The programs can call functions from the API defined in the following TypeScript definitions:\n`; } - function createRequestPrompt(request: string) { - return describeProgram() + - `\`\`\`\n${validator.getSchemaText()}\`\`\`\n` + - `The following is a user request:\n` + - `"""\n${request}\n"""\n` + - `The following is the user request translated into a JSON program object with 2 spaces of indentation and no properties with the value undefined:\n`; - } - function createRepairPrompt(validationError: string) { return `The JSON program object is invalid for the following reason:\n` + `"""\n${validationError}\n"""\n` + diff --git a/typescript/src/typechat.ts b/typescript/src/typechat.ts index 1fa9ddaf..6ccc134d 100644 --- a/typescript/src/typechat.ts +++ b/typescript/src/typechat.ts @@ -40,10 +40,15 @@ export interface TypeChatJsonTranslator { */ createSystemPrompt(): string; /** - * Creates the final user message in the legacy layout. To use an existing override, select + * Creates the final user message for a string request in the legacy layout. To use an existing override, select * `{ promptLayout: "legacy" }` at construction. Its content is never used as a system message. */ createRequestPrompt(request: string): PromptContent; + /** + * Customizes the text before and after a legacy request. Use this instead of replacing + * createRequestPrompt to support both strings and multipart requests in one user message. + */ + getLegacyPromptParts?(): readonly [prefix: string, suffix: string]; /** * Creates a repair prompt to append to an original prompt/response. This function is called when * `attemptRepair` is true and the response has no usable JSON object or the object failed to validate. @@ -69,12 +74,12 @@ export interface TypeChatJsonTranslator { * A failure retains the latest rejected candidate and available model response text. These may * come from different attempts if a repair response couldn't be parsed. * Optional result metadata retains response records and reported usage across both attempts. - * @param request The natural language request. + * @param request One user message: a string or an ordered array of text and image parts. * @param promptPreamble Optional context before the current user message (after the system message * in the default layout). A string becomes one user message; sections retain their roles and order. * @returns A promise for the resulting object. */ - translate(request: string, promptPreamble?: string | PromptSection[]): Promise>; + translate(request: PromptContent, promptPreamble?: string | PromptSection[]): Promise>; } /** @@ -135,12 +140,19 @@ export function createJsonTranslator( `Return only the JSON object with 2 spaces of indentation and no properties with the value undefined.`; } - function createRequestPrompt(request: string) { - return `You are a service that translates user requests into JSON objects of type "${validator.getTypeName()}" according to the following TypeScript definitions:\n` + + function legacyPromptParts(): readonly [string, string] { + if (typeChat.getLegacyPromptParts) return typeChat.getLegacyPromptParts(); + return [ + `You are a service that translates user requests into JSON objects of type "${validator.getTypeName()}" according to the following TypeScript definitions:\n` + `\`\`\`\n${validator.getSchemaText()}\`\`\`\n` + - `The following is a user request:\n` + - `"""\n${request}\n"""\n` + - `The following is the user request translated into a JSON object with 2 spaces of indentation and no properties with the value undefined:\n`; + `The following is a user request:\n"""\n`, + `\n"""\nThe following is the user request translated into a JSON object with 2 spaces of indentation and no properties with the value undefined:\n` + ]; + } + + function createRequestPrompt(request: string) { + const [prefix, suffix] = legacyPromptParts(); + return prefix + request + suffix; } function createRepairPrompt(validationError: string) { @@ -149,20 +161,36 @@ export function createJsonTranslator( `The following is a revised JSON object:\n`; } - async function translate(request: string, promptPreamble?: string | PromptSection[]): Promise> { + async function translate(request: PromptContent, promptPreamble?: string | PromptSection[]): Promise> { const schemaValidator = validator as TypeChatJsonValidator & Partial, typeof typeChatSchemaValidation>>; const preflight = schemaValidator[typeChatSchemaValidation]?.(); if (preflight && !preflight.success) { return error(`Schema validation failed before model request: ${preflight.message}`); } + if (typeof request !== "string" && !Array.isArray(request)) { + return error("Translation request must be a string or an array of text/image parts."); + } const preamble: PromptSection[] = typeof promptPreamble === "string" ? [{ role: "user", content: promptPreamble }] : promptPreamble ?? []; - if (promptLayout !== "legacy" && typeChat.createRequestPrompt !== createRequestPrompt) { - return error('A custom createRequestPrompt requires { promptLayout: "legacy" }. To migrate, move application instructions to createSystemPrompt() and pass context as promptPreamble.'); + let prompt: PromptSection[]; + if (promptLayout === "legacy") { + let content: PromptContent; + if (typeof request === "string") { + content = typeChat.createRequestPrompt(request); + } else { + if (typeChat.createRequestPrompt !== createRequestPrompt) { + return error("A custom createRequestPrompt accepts string requests. Use getLegacyPromptParts instead for multipart requests, or pass images in promptPreamble with a string request."); + } + const [prefix, suffix] = legacyPromptParts(); + content = [{ type: "text", text: prefix }, ...request, { type: "text", text: suffix }]; + } + prompt = [...preamble, { role: "user", content }]; + } else { + if (typeChat.createRequestPrompt !== createRequestPrompt) { + return error('A custom createRequestPrompt requires { promptLayout: "legacy" }. To migrate, move application instructions to createSystemPrompt() and pass context as promptPreamble.'); + } + prompt = [{ role: "system", content: typeChat.createSystemPrompt() }, ...preamble, { role: "user", content: request }]; } - const prompt: PromptSection[] = promptLayout === "legacy" - ? [...preamble, { role: "user", content: typeChat.createRequestPrompt(request) }] - : [{ role: "system", content: typeChat.createSystemPrompt() }, ...preamble, { role: "user", content: request }]; let attemptRepair = typeChat.attemptRepair; let failureContext: (Pick & { responseText: string }) | undefined; const responses: TypeChatResponseMetadata[] = []; diff --git a/typescript/test/program.test.ts b/typescript/test/program.test.ts index f68248d4..fa4a8e06 100644 --- a/typescript/test/program.test.ts +++ b/typescript/test/program.test.ts @@ -1,6 +1,6 @@ import { describe, it } from "node:test"; import assert from "node:assert/strict"; -import type { PromptSection } from "../dist/index.js"; +import type { PromptContent, PromptSection } from "../dist/index.js"; import { createModuleTextFromProgram, createProgramTranslator, @@ -166,6 +166,30 @@ describe("createProgramTranslator", () => { } }); + it("legacy multipart program prompt wraps images with the Program and API instructions", async () => { + const parts: PromptContent = [{ type: "image_url", image_url: { url: "https://adatum.com/sum.png" } }]; + const translator = createProgramTranslator({ + async complete(prompt) { + assert.ok(Array.isArray(prompt)); + assert.deepEqual(prompt.map(section => section.role), ["user"]); + const content = prompt[0].content; + assert.ok(Array.isArray(content)); + const prefix = content[0], suffix = content[content.length - 1]; + assert.ok(typeof prefix === "object" && prefix.type === "text"); + assert.match(prefix.text, /export type Program =/); + assert.ok(prefix.text.includes(apiSchema)); + assert.deepEqual(content.slice(1, -1), parts); + assert.ok(typeof suffix === "object" && suffix.type === "text" && suffix.text.includes("JSON program object")); + return { success: true, data: '{"@steps":[]}' }; + } + }, apiSchema, { promptLayout: "legacy" }); + try { + assert.ok((await translator.translate(parts)).success); + } finally { + (translator.validator as TypeScriptJsonValidator).close(); + } + }); + it("repairs a program response that does not match the API", async () => { const responses = [ '{"@steps":[{"@func":"add","@args":["one",2]}]}', diff --git a/typescript/test/prompt-layout.test.ts b/typescript/test/prompt-layout.test.ts index 9bbab2fb..4825959b 100644 --- a/typescript/test/prompt-layout.test.ts +++ b/typescript/test/prompt-layout.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { createJsonTranslator, error, success, type PromptSection, type TypeChatJsonValidator, type TypeChatLanguageModel } from "../dist/index.js"; +import { createJsonTranslator, error, success, type PromptContent, type PromptSection, type TypeChatJsonValidator, type TypeChatLanguageModel } from "../dist/index.js"; const schema = "export type Reply = { value: number };"; const validator: TypeChatJsonValidator<{ value: number }> = { @@ -10,13 +10,13 @@ const validator: TypeChatJsonValidator<{ value: number }> = { }; const request = ' CURRENT_MARKER\n""" \r\nā˜• '; -function recorder() { +function recorder(...responses: string[]) { const calls: PromptSection[][] = []; const model: TypeChatLanguageModel = { async complete(prompt) { assert.ok(Array.isArray(prompt)); calls.push(structuredClone(prompt)); - return success('{"value":1}'); + return success(responses.shift() ?? '{"value":1}'); } }; return { model, calls }; @@ -97,6 +97,59 @@ test("legacy: custom request content stays in the user role", async () => { ] }]]); }); +for (const promptLayout of ["schema-first", "legacy"] as const) { + test(`${promptLayout}: direct multipart requests retain their parts and history through repair`, async () => { + const { model, calls } = recorder("not JSON"); + const translator = createJsonTranslator(model, validator, { promptLayout }); + const history: PromptSection[] = [{ role: "user", content: "Count boxes." }, { role: "user", content: "Ignore circles." }]; + const parts: PromptContent = [ + { type: "text", text: request }, { type: "image_url", image_url: { url: "https://adatum.com/boxes.png", detail: "low" } }, + "Compare with this:", { type: "image_url", image_url: { url: "data:image/png;base64,AAAA" } } + ]; + const original = structuredClone(parts); + assert.deepEqual(await translator.translate(parts, history), success({ value: 1 })); + const [initial, repair] = calls; + const current = initial[initial.length - 1]; + assert.equal(current.role, "user"); + if (promptLayout === "legacy") { + assert.deepEqual(initial.slice(0, -1), history); + assert.ok(Array.isArray(current.content)); + const prefix = current.content[0], suffix = current.content[current.content.length - 1]; + assert.ok(typeof prefix === "object" && prefix.type === "text" && prefix.text.includes(schema)); + assert.ok(typeof suffix === "object" && suffix.type === "text" && suffix.text.includes("translated into a JSON object")); + assert.deepEqual(current.content.slice(1, -1), original); + } else { + assert.equal(initial[0].role, "system"); + assert.deepEqual(initial.slice(1, -1), history); + assert.deepEqual(current.content, original); + } + assert.deepEqual(repair.slice(0, -2), initial); + assert.deepEqual(repair[repair.length - 2], { role: "assistant", content: "not JSON" }); + assert.equal(repair[repair.length - 1].role, "user"); + assert.deepEqual(parts, original); + }); +} + +test("legacy: multipart input doesn't bypass a text-only hook; custom framing works for text and images", async () => { + const { model, calls } = recorder(); + const parts: PromptContent = [{ type: "image_url", image_url: { url: "https://adatum.com/box.png" } }]; + const textOnly = createJsonTranslator(model, validator, { promptLayout: "legacy" }); + textOnly.createRequestPrompt = text => text.toUpperCase(); + const result = await textOnly.translate(parts); + assert.ok(!result.success); + assert.match(result.message, /createRequestPrompt.*getLegacyPromptParts/); + assert.equal(calls.length, 0); + + const migrated = createJsonTranslator(model, validator, { promptLayout: "legacy" }); + migrated.getLegacyPromptParts = () => ["opening:", ":closing"]; + assert.ok((await migrated.translate("hello")).success); + assert.ok((await migrated.translate(parts)).success); + assert.deepEqual(calls, [ + [{ role: "user", content: "opening:hello:closing" }], + [{ role: "user", content: [{ type: "text", text: "opening:" }, ...parts, { type: "text", text: ":closing" }] }] + ]); +}); + test("unmigrated request hook fails before dispatch, without fallback", async () => { const { model, calls } = recorder(); const translator = createJsonTranslator(model, validator); diff --git a/typescript/tests/examples.test.mjs b/typescript/tests/examples.test.mjs index 887dcdaa..987efbdc 100644 --- a/typescript/tests/examples.test.mjs +++ b/typescript/tests/examples.test.mjs @@ -145,20 +145,21 @@ test("healthData example: validated prior answer stays assistant context", async const firstAnswer = { message: "PAST_ANSWER" }; const { model, calls } = recordingModel(firstAnswer, { message: "OK" }); const translator = createHealthDataTranslator(model, schema, "HealthDataResponse", "APP_INSTRUCTIONS"); + const next = [{ type: "text", text: "NEXT_REQUEST" }, { type: "image_url", image_url: { url: "https://adatum.com/photo.png" } }]; try { assert.ok((await translator.translate("FIRST_REQUEST")).success); - assert.ok((await translator.translate("NEXT_REQUEST")).success); + assert.ok((await translator.translate(next)).success); assert.equal(calls.length, 2); for (const [system] of calls) { assert.equal(system.role, "system"); assert.ok(system.content.includes(schema)); assert.match(system.content, /APP_INSTRUCTIONS/); - assert.doesNotMatch(system.content, /PAST_ANSWER|FIRST_REQUEST|NEXT_REQUEST/); + assert.doesNotMatch(system.content, /PAST_ANSWER|FIRST_REQUEST|NEXT_REQUEST|photo\.png/); } assert.deepEqual(calls[0].slice(1), [{ role: "user", content: "FIRST_REQUEST" }]); assert.deepEqual(calls[1].slice(1), [ { role: "assistant", content: JSON.stringify(firstAnswer, null, 2) }, - { role: "user", content: "NEXT_REQUEST" } + { role: "user", content: next } ]); } finally { translator._translator.validator.close(); diff --git a/typescript/tests/model.test.mjs b/typescript/tests/model.test.mjs index b840737b..8206e901 100644 --- a/typescript/tests/model.test.mjs +++ b/typescript/tests/model.test.mjs @@ -15,7 +15,7 @@ import { join } from "node:path"; // Load the compiled module from dist import { createOpenAILanguageModel, createAzureOpenAILanguageModel, createLanguageModel, - createOpenAILanguageModelFromClient + createOpenAILanguageModelFromClient, createJsonTranslator } from "../dist/index.js"; test("missing optional undici returns an actionable result for both API paths", async () => { @@ -323,6 +323,47 @@ function mockClient(api, responses) { return { client, calls, isClosed: () => closed }; } +describe("direct multipart translation on the wire", () => { + after(teardownFetch); + for (const api of ["chat", "responses"]) { + for (const transport of ["HTTP", "client"]) { + for (const promptLayout of ["schema-first", "legacy"]) { + test(`${transport} ${api} ${promptLayout}: preserves ordered text and image parts`, async () => { + const options = { useResponsesApi: api === "responses" }; + const reply = '{"color":"red"}'; + const { client, calls } = mockClient(api, [clientBody(api, reply)]); + if (transport === "HTTP") { + setupFetch([api === "responses" ? makeResponsesAPIResponse(reply) : makeChatCompletionsResponse(reply)]); + } + const model = transport === "client" ? createOpenAILanguageModelFromClient(client, "test-model", options) : + createOpenAILanguageModel("test-key", "test-model", "https://adatum.com/endpoint", "", options); + const translator = createJsonTranslator(model, { + getTypeName: () => "Answer", getSchemaText: () => "type Answer = { color: string };", + validate: data => ({ success: true, data }) + }, { promptLayout }); + const url = "https://adatum.com/red-square.png"; + const parts = ["What color?", { type: "image_url", image_url: { url, detail: "low" } }]; + assert.ok((await translator.translate(parts)).success); + const body = transport === "client" ? calls[0] : JSON.parse(capturedRequests[0].options.body); + const messages = api === "chat" ? body.messages : body.input; + assert.deepEqual(messages.map(m => m.role), promptLayout === "legacy" ? ["user"] : ["system", "user"]); + const content = messages.at(-1).content; + assert.ok(Array.isArray(content)); + const textType = api === "responses" ? "input_text" : "text"; + if (promptLayout === "legacy") { + assert.equal(content[0].type, textType); + assert.equal(content.at(-1).type, textType); + } + assert.deepEqual(promptLayout === "legacy" ? content.slice(1, -1) : content, [ + { type: textType, text: "What color?" }, + api === "responses" ? { type: "input_image", image_url: url, detail: "low" } : parts[1] + ]); + }); + } + } + } +}); + describe("configured-client adapters", () => { for (const api of ["chat", "responses"]) { const options = { useResponsesApi: api === "responses" }; From 9da5ff8b44a3992aae479ba36ae6b09a1fefc962 Mon Sep 17 00:00:00 2001 From: Robert Gruen Date: Sun, 29 Nov 2026 12:54:23 -0800 Subject: [PATCH 6/7] Fix Python package README links for PyPI Link to the hosted Python guides and canonical example files instead of repository-relative paths. Give the referenced guide headings stable IDs so the links land on the intended sections. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- python/README.md | 19 ++++++++++--------- site/src/docs/python/basic-usage.md | 10 +++++----- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/python/README.md b/python/README.md index d64a1af2..edc7d407 100644 --- a/python/README.md +++ b/python/README.md @@ -33,8 +33,8 @@ pip install typechat ``` To use TypeChat in an existing backend without an interactive chat loop, follow the -[non-interactive Python quickstart](../site/src/docs/python/non-interactive.md). -It includes a [standalone sentiment example](./examples/sentiment/non_interactive.py) and an async function you can call from application code. +[non-interactive Python quickstart](https://microsoft.github.io/TypeChat/docs/python/non-interactive/). +It includes a [standalone sentiment example](https://github.com/microsoft/TypeChat/blob/main/python/examples/sentiment/non_interactive.py) and an async function you can call from application code. You can also develop TypeChat from source, which needs [Python >=3.11](https://www.python.org/downloads/), [hatch](https://hatch.pypa.io/1.6/install/), and [Node.js >=24.22.1](https://nodejs.org/en/download): @@ -69,8 +69,9 @@ overrides for string requests in the **user** role. For custom multipart legacy requests, return the text before and after the request from `_get_legacy_prompt_parts(self)`. For the new default, customize `_create_system_prompt(self)` with application-owned instructions only. See the -[migration guide](../site/src/docs/python/basic-usage.md#prompt-layout-and-migration) -and the [math](./examples/math/program.py) and [health-data](./examples/healthData/translator.py) examples. +[migration guide](https://microsoft.github.io/TypeChat/docs/python/basic-usage/#prompt-layout-and-migration) +and the [math](https://github.com/microsoft/TypeChat/blob/main/python/examples/math/program.py) +and [health-data](https://github.com/microsoft/TypeChat/blob/main/python/examples/healthData/translator.py) examples. ## Reusing model authentication @@ -82,8 +83,8 @@ already has a configured asynchronous OpenAI or Azure OpenAI client, use Both paths reuse authentication supplied by your application without adding SDK dependencies to TypeChat or requiring TypeChat-specific environment-variable names. Existing API-key and environment-based calls are unchanged. See the -[token-provider example](../site/src/docs/python/basic-usage.md#using-a-bearer-token-provider) -and [configured-client example](../site/src/docs/python/basic-usage.md#reusing-an-already-configured-client) +[token-provider example](https://microsoft.github.io/TypeChat/docs/python/basic-usage/#using-a-bearer-token-provider) +and [configured-client example](https://microsoft.github.io/TypeChat/docs/python/basic-usage/#reusing-an-already-configured-client) for ownership, retry, and error behavior. ## Using the Responses API @@ -99,8 +100,8 @@ Existing calls still use Chat Completions. Endpoint paths do not select an API, and automatic Responses-to-Chat fallback is deferred. Both APIs preserve TypeChat's schema validation and bounded repair. -See the [Responses API guide](../site/src/docs/python/basic-usage.md#using-the-responses-api) -and [minimal HTTP/client example](./examples/responses/demo.py). +See the [Responses API guide](https://microsoft.github.io/TypeChat/docs/python/basic-usage/#using-the-responses-api) +and [minimal HTTP/client example](https://github.com/microsoft/TypeChat/blob/main/python/examples/responses/demo.py). All four model factories accept a keyword-only `temperature` option. It defaults to `0.0` for Chat Completions, preserving existing behavior. In Chat Completions @@ -181,7 +182,7 @@ TypeChat only forwards image references: it does not fetch, decode, resize, or validate image contents. Supported formats (such as PNG, JPEG, or WebP), URL accessibility, image counts, detail support, and size/resolution limits depend on your provider and model. No image-processing or provider SDK dependency is added. -See [text and image usage](../site/src/docs/python/basic-usage.md#text-and-image-prompts) +See [text and image usage](https://microsoft.github.io/TypeChat/docs/python/basic-usage/#text-and-image-prompts) for the complete prompt type definitions and limitations. ## Documenting schema fields diff --git a/site/src/docs/python/basic-usage.md b/site/src/docs/python/basic-usage.md index f19d4651..97556e76 100644 --- a/site/src/docs/python/basic-usage.md +++ b/site/src/docs/python/basic-usage.md @@ -112,7 +112,7 @@ pass them in. Based on whether `OPENAI_API_KEY` or `AZURE_OPENAI_API_KEY` is set, you'll get a model of the appropriate type. -#### Using a bearer-token provider +

Using a bearer-token provider

For keyless Azure OpenAI authentication, pass `api_key=None` and an existing token provider directly. `TokenProvider` is a callable returning either a token @@ -164,7 +164,7 @@ Existing API-key calls, positional arguments, environment-variable handling, and legacy headers are unchanged. In particular, setting `AZURE_OPENAI_API_KEY=identity` does not activate a credential provider. -#### Reusing an already configured client +

Reusing an already configured client

If your application already has an `AsyncOpenAI`, `AsyncAzureOpenAI`, or compatible asynchronous Chat Completions client, adapt that instance directly: @@ -194,7 +194,7 @@ API instead, select it explicitly as shown below. Pass either model to `TypeChatJsonTranslator` as usual. Schema generation, validation, and repair behavior remain unchanged. -#### Using the Responses API +

Using the Responses API

For new text and image integrations, select Responses explicitly with `use_responses_api=True`. All existing calls still default to Chat Completions; @@ -365,7 +365,7 @@ import typechat model = typechat.create_language_model(os.environ) ``` -## Text and image prompts +

Text and image prompts

The HTTP models and configured-client adapters accept image references alongside text in both Chat Completions and explicitly selected Responses mode. Use @@ -600,7 +600,7 @@ method. result = await translator.translate("Hello world! šŸ™‚") ``` -### Prompt layout and migration +

Prompt layout and migration

In Python 0.3 the translator builds a `system` message with the application schema, translation instructions, and JSON formatting rules. It then passes From c508555e85fbe5cf70a29b7b622b100361487212 Mon Sep 17 00:00:00 2001 From: Robert Gruen Date: Sun, 29 Nov 2026 13:08:00 -0800 Subject: [PATCH 7/7] Fix Responses assistant history and reject malformed prompt sections Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- site/src/docs/typescript/basic-usage.md | 7 ++++--- typescript/src/model.ts | 18 +++++++++++++----- typescript/tests/model.test.mjs | 24 +++++++++++++++++++++--- 3 files changed, 38 insertions(+), 11 deletions(-) diff --git a/site/src/docs/typescript/basic-usage.md b/site/src/docs/typescript/basic-usage.md index dcb93a72..95d7f602 100644 --- a/site/src/docs/typescript/basic-usage.md +++ b/site/src/docs/typescript/basic-usage.md @@ -154,9 +154,10 @@ cancellation propagate unchanged; missing/malformed output and filtered/refused return TypeChat errors. String prompts and text/image user messages are supported. Bare strings in content arrays -become text parts; images retain URLs/data URLs and detail levels. Responses mode maps them -to `input_text`/`input_image` parts, defaulting omitted image detail to `"auto"`. System and -assistant messages support text only; unsupported content is reported rather than dropped. +become text parts; images retain URLs/data URLs and detail levels. In Responses mode, tagged +user and system text becomes `input_text`, tagged assistant history becomes `output_text`, and +user images become `input_image` (omitted detail defaults to `"auto"`). System and assistant +messages support text only. Both adapters return an error for malformed prompt sections before dispatch. Neither path fetches image references separately. Pass either model to `createJsonTranslator` as usual. Schema validation, repair, and diff --git a/typescript/src/model.ts b/typescript/src/model.ts index 95b6e64a..358f0e88 100644 --- a/typescript/src/model.ts +++ b/typescript/src/model.ts @@ -142,7 +142,7 @@ type ClientMessage = | { role: "assistant"; content: string | TextPromptContent[] }; type ClientResponseContent = - | { type: "input_text"; text: string } + | { type: "input_text" | "output_text"; text: string } | { type: "input_image"; image_url: string; detail: NonNullable }; /** Structural contract for a caller-owned asynchronous Chat Completions client. */ @@ -342,15 +342,23 @@ function responsesMessages(messages: ClientMessage[]) { role, content: typeof content === "string" ? content : content.map((part): ClientResponseContent => part.type === "text" ? - { type: "input_text", text: part.text } : + { type: role === "assistant" ? "output_text" : "input_text", text: part.text } : { type: "input_image", image_url: part.image_url.url, detail: part.image_url.detail ?? "auto" }) })); } -function normalizeMessages(prompt: string | PromptSection[]): Result { - const sections: PromptSection[] = typeof prompt === "string" ? [{ role: "user", content: prompt }] : prompt; +function normalizeMessages(prompt: unknown): Result { + const sections = typeof prompt === "string" ? [{ role: "user", content: prompt }] : prompt; + if (!Array.isArray(sections)) { + return error("Prompt must be a string or an array of prompt sections."); + } const messages: ClientMessage[] = []; - for (const { role, content } of sections) { + for (const section of sections) { + const fields = record(section); + if (!fields) { + return error("Prompt section must be an object with a role and content."); + } + const { role, content } = fields; if (role !== "user" && role !== "system" && role !== "assistant") { return error("Unsupported prompt role."); } diff --git a/typescript/tests/model.test.mjs b/typescript/tests/model.test.mjs index 8206e901..89ce710f 100644 --- a/typescript/tests/model.test.mjs +++ b/typescript/tests/model.test.mjs @@ -325,10 +325,23 @@ function mockClient(api, responses) { describe("direct multipart translation on the wire", () => { after(teardownFetch); + test("HTTP adapters reject malformed prompt sections before fetching", async () => { + setupFetch([]); + for (const useResponsesApi of [false, true]) { + const model = createOpenAILanguageModel("test-key", "test-model", "https://adatum.com/endpoint", "", { useResponsesApi }); + for (const prompt of [null, [null], [undefined]]) { + const result = await model.complete(prompt); + assert.equal(result.success, false); + assert.match(result.message, /prompt section/i); + } + } + assert.equal(capturedRequests.length, 0); + }); + for (const api of ["chat", "responses"]) { for (const transport of ["HTTP", "client"]) { for (const promptLayout of ["schema-first", "legacy"]) { - test(`${transport} ${api} ${promptLayout}: preserves ordered text and image parts`, async () => { + test(`${transport} ${api} ${promptLayout}: preserves tagged assistant history and ordered user parts`, async () => { const options = { useResponsesApi: api === "responses" }; const reply = '{"color":"red"}'; const { client, calls } = mockClient(api, [clientBody(api, reply)]); @@ -343,10 +356,14 @@ describe("direct multipart translation on the wire", () => { }, { promptLayout }); const url = "https://adatum.com/red-square.png"; const parts = ["What color?", { type: "image_url", image_url: { url, detail: "low" } }]; - assert.ok((await translator.translate(parts)).success); + const history = [{ role: "assistant", content: [{ type: "text", text: "The first square was blue." }] }]; + assert.ok((await translator.translate(parts, history)).success); const body = transport === "client" ? calls[0] : JSON.parse(capturedRequests[0].options.body); const messages = api === "chat" ? body.messages : body.input; - assert.deepEqual(messages.map(m => m.role), promptLayout === "legacy" ? ["user"] : ["system", "user"]); + assert.deepEqual(messages.map(m => m.role), promptLayout === "legacy" ? ["assistant", "user"] : ["system", "assistant", "user"]); + assert.deepEqual(messages.at(-2), { + role: "assistant", content: [{ type: api === "responses" ? "output_text" : "text", text: "The first square was blue." }] + }); const content = messages.at(-1).content; assert.ok(Array.isArray(content)); const textType = api === "responses" ? "input_text" : "text"; @@ -444,6 +461,7 @@ describe("configured-client adapters", () => { const { client, calls } = mockClient(api, []); const model = createOpenAILanguageModelFromClient(client, "test", options); const prompts = [ + null, [null], [undefined], [{ role: "developer", content: "unsupported role" }], [{ role: "user", content: { type: "text", text: "not an array" } }], [{ role: "user", content: [{ type: "audio", data: "unsupported" }] }],