diff --git a/python/README.md b/python/README.md index 02765944..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): @@ -54,6 +54,25 @@ 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 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](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 For keyless Azure OpenAI requests, pass a synchronous or asynchronous bearer-token @@ -64,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 @@ -81,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 @@ -150,8 +169,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. Its preamble stays before the generated -schema/request message, and image context is preserved during validation and repair. +`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. @@ -159,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/python/examples/drawing/demo.py b/python/examples/drawing/demo.py index 0f499084..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 @@ -10,6 +11,7 @@ from typechat import ( Success, Failure, + PromptSection, TypeChatJsonTranslator, TypeChatValidator, create_language_model, @@ -17,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...") @@ -30,12 +37,12 @@ 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] = [] 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..7c73c91f 100644 --- a/python/examples/healthData/translator.py +++ b/python/examples/healthData/translator.py @@ -1,54 +1,64 @@ 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, PromptContent, 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]: + 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): + 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 _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} ''' 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} @@ -60,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/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..1e5b449f 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 _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: """ - return prompt @override def _create_repair_prompt(self, validation_error: str) -> str: 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 05895f72..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,32 +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_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) + result = await self._translator.translate(line) 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/src/typechat/_internal/model.py b/python/src/typechat/_internal/model.py index df49fbf4..ae7e91b7 100644 --- a/python/src/typechat/_internal/model.py +++ b/python/src/typechat/_internal/model.py @@ -30,9 +30,9 @@ class ImagePromptContent(TypedDict): class PromptSection(TypedDict): """ - Represents a section of an LLM prompt with an associated role. TypeChat uses the "user" role for - prompts it generates and the "assistant" role for previous LLM responses (which will be part of - the prompt in repair attempts). TypeChat currently doesn't use the "system" role. + Represents a section of an LLM prompt with an associated role. By default the translator sends + schema instructions as "system" and the request as "user". Repairs append the rejected response + as "assistant" and the diagnostic as "user". """ role: Literal["system", "user", "assistant"] content: PromptContent diff --git a/python/src/typechat/_internal/translator.py b/python/src/typechat/_internal/translator.py index db44b4b2..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 @@ -28,6 +28,7 @@ def __init__( validator: TypeChatValidator[T], target_type: type[T], *, # keyword-only parameters follow + use_legacy_prompt: bool = False, _raise_on_schema_errors: bool = True, ): """ @@ -35,11 +36,13 @@ def __init__( model: The associated `TypeChatLanguageModel`. validator: The associated `TypeChatValidator[T]`. target_type: A runtime type object describing `T` - the expected shape of JSON data. + use_legacy_prompt: Use the pre-0.3 combined user prompt and `_create_request_prompt` hook. """ super().__init__() self.model = model self.validator = validator self.target_type = target_type + self._use_legacy_prompt = use_legacy_prompt conversion_result = python_type_to_typescript_schema(target_type) @@ -50,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`. @@ -60,19 +63,40 @@ 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. - prompt_preamble: An optional string or list of prompt sections to prepend to the generated prompt.\ - If a string is given, it is converted to a single "user" role prompt section. + 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. """ messages: list[PromptSection] = [] + if not self._use_legacy_prompt: + 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: if isinstance(prompt_preamble, str): prompt_preamble = [{"role": "user", "content": prompt_preamble}] messages.extend(prompt_preamble) - messages.append({"role": "user", "content": self._create_request_prompt(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 last_failure: Failure | None = None @@ -124,19 +148,43 @@ 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""" +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} +``` +You translate each user request into a JSON object with 2 spaces of indentation and no properties with the value undefined. +""" + def _create_request_prompt(self, intent: str) -> str: - 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_client_model.py b/python/tests/test_client_model.py index ade6ff55..37272be3 100644 --- a/python/tests/test_client_model.py +++ b/python/tests/test_client_model.py @@ -171,7 +171,7 @@ def test_client_adapter_preserves_translation_validation_and_repair(): assert asyncio.run(translator.translate("Get a value")) == typechat.Success(_Response("repaired")) requests = client.chat.completions.requests assert len(requests) == 2 - assert [message["role"] for message in requests[1]["messages"]] == ["user", "assistant", "user"] + assert [message["role"] for message in requests[1]["messages"]] == ["system", "user", "assistant", "user"] def test_typechat_import_does_not_require_provider_sdks(): diff --git a/python/tests/test_example_prompt_layouts.py b/python/tests/test_example_prompt_layouts.py new file mode 100644 index 00000000..7fb76b3b --- /dev/null +++ b/python/tests/test_example_prompt_layouts.py @@ -0,0 +1,157 @@ +import asyncio +import json +import runpy +import sys +from datetime import datetime +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 TaskClassification, 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_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.", 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}] diff --git a/python/tests/test_failure.py b/python/tests/test_failure.py index 86c283c8..2322a9b4 100644 --- a/python/tests/test_failure.py +++ b/python/tests/test_failure.py @@ -166,6 +166,18 @@ def test_translator_propagates_initial_model_failures_unchanged(): assert asyncio.run(translator.translate("request")) is original +def test_unsupported_system_role_is_not_retried_with_flattened_history(): + unsupported = Failure("This provider does not support system messages.") + translator, model = translator_for([unsupported]) + history: list[PromptSection] = [ + {"role": "user", "content": "earlier request"}, {"role": "assistant", "content": '{"value":1}'}, + ] + assert asyncio.run(translator.translate("next request", prompt_preamble=history)) is unsupported + [prompt] = model.prompts + assert isinstance(prompt, list) and prompt[0]["role"] == "system" + assert prompt[1:] == [*history, {"role": "user", "content": "next request"}] + + def test_translator_preserves_successful_repair(): first = '{"value":"invalid"}' translator, model = translator_for([Success(first), Success('{"value":42}')]) @@ -173,8 +185,9 @@ def test_translator_preserves_successful_repair(): assert len(model.prompts) == 2 repair_prompt = model.prompts[1] assert isinstance(repair_prompt, list) - assert repair_prompt[1]["content"] == first - assert "failed for value" in repair_prompt[2]["content"] + assert repair_prompt[-2] == {"role": "assistant", "content": first} + assert repair_prompt[-1]["role"] == "user" + assert "failed for value" in repair_prompt[-1]["content"] def test_translator_returns_latest_rejected_candidate_after_one_repair(): diff --git a/python/tests/test_multimodal_model.py b/python/tests/test_multimodal_model.py index e2fe7ab1..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))), @@ -402,18 +435,14 @@ class LimitedTranslator(typechat.TypeChatJsonTranslator[_ImageResult]): assert result.response_text == expected.response_text assert preamble == original assert len(harness.prompts) == len(responses) - expected_request: typechat.PromptSection = {"role": "user", "content": f""" + expected_system: typechat.PromptSection = {"role": "system", "content": f""" You are a service that translates user requests into JSON objects of type "{translator.type_name}" according to the following TypeScript definitions: ``` {translator.schema_str} ``` -The following is a user request: -''' -Describe the images. -''' -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. """} - first_prompt = [*original, expected_request] + first_prompt: list[typechat.PromptSection] = [expected_system, *original, {"role": "user", "content": "Describe the images."}] for attempt, prompt in enumerate(harness.prompts): assert prompt[:len(first_prompt)] == first_prompt assert len(prompt) == len(first_prompt) + 2 * attempt @@ -439,17 +468,30 @@ def test_malformed_preamble_does_not_trigger_translator_repair( ) preamble = cast(list[typechat.PromptSection], [{"role": "user", "content": [_PRIVATE_TEXT]}]) result = asyncio.run(translator.translate("Describe the images.", prompt_preamble=preamble)) - _assert_invalid_prompt(harness, result, "section 0, part 0") + _assert_invalid_prompt(harness, result, "section 1, part 0") 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=")) assert text == typechat.Success("image description") assert data == typechat.Success({"description": "two images"}) assert len(harness.prompts) == 2 - assert harness.prompts[1][:-1] == harness.prompts[0] + assert harness.prompts[1][0]["role"] == "system" + assert harness.prompts[1][1:-1] == harness.prompts[0] + assert harness.prompts[1][-1] == {"role": "user", "content": "Describe the images."} @pytest.mark.parametrize("model_factory", ["http-key", "http-token"], indirect=True) 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 382bf477..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( @@ -814,7 +837,9 @@ async def run() -> typechat.Result[_Value]: assert asyncio.run(run()) == typechat.Success(_Value("validated")) assert len(requests) == 1 - assert requests[0]["input"][:-1] == expected + assert requests[0]["input"][0]["role"] == "system" + assert requests[0]["input"][1:-1] == expected + assert requests[0]["input"][-1] == {"role": "user", "content": "get value"} assert preamble == original @@ -838,8 +863,9 @@ async def run() -> None: asyncio.run(run()) assert len(requests) == 2 - assert requests[0]["input"][:-1] == expected - assert requests[0]["input"][-1]["role"] == "user" + assert requests[0]["input"][0]["role"] == "system" + assert requests[0]["input"][1:-1] == expected + assert requests[0]["input"][-1] == {"role": "user", "content": "get value"} assert requests[1]["input"][:-2] == requests[0]["input"] assert requests[1]["input"][-2] == {"role": "assistant", "content": initial} assert requests[1]["input"][-1]["role"] == "user" @@ -865,7 +891,7 @@ async def run() -> typechat.Result[_Value]: assert result.has_value and result.value == {"value": 123} assert result.response_text == "not JSON" assert len(requests) == 2 - assert all(request["input"][:len(expected)] == expected for request in requests) + assert all(request["input"][1:1 + len(expected)] == expected for request in requests) assert preamble == original @@ -889,7 +915,7 @@ async def run() -> typechat.Result[_Value]: result = asyncio.run(run()) assert isinstance(result, typechat.Failure) assert len(requests) == (2 if after_repair else 1) - assert all(request["input"][:len(expected)] == expected for request in requests) + assert all(request["input"][1:1 + len(expected)] == expected for request in requests) assert preamble == original if after_repair: assert result.has_value and result.value == {"value": 123} @@ -917,7 +943,7 @@ async def run() -> typechat.Result[_Value]: result = asyncio.run(run()) assert isinstance(result, typechat.Failure) - assert "section 0, part 0" in result.message + assert "section 1, part 0" in result.message assert not result.has_value and result.response_text is None assert requests == [] provider.assert_not_called() diff --git a/python/tests/test_sentiment_non_interactive.py b/python/tests/test_sentiment_non_interactive.py index 017de78a..e6084aa8 100644 --- a/python/tests/test_sentiment_non_interactive.py +++ b/python/tests/test_sentiment_non_interactive.py @@ -33,9 +33,7 @@ def test_classify_returns_validated_sentiment(sentiment: str) -> None: assert isinstance(result, non_interactive.Sentiment) assert result.sentiment == sentiment - request = model.conversation[0]["payload"] - assert isinstance(request, list) - assert "Classify this text." in request[0]["content"] + assert model.request()[-1] == {"role": "user", "content": "Classify this text."} def test_classify_reuses_translator_for_independent_requests() -> None: @@ -50,13 +48,11 @@ async def classify_both() -> tuple[non_interactive.Sentiment, non_interactive.Se first, second = asyncio.run(classify_both()) assert first.sentiment == "positive" assert second.sentiment == "negative" - first_request = model.conversation[0]["payload"] - second_request = model.conversation[2]["payload"] - assert isinstance(first_request, list) - assert isinstance(second_request, list) - assert len(first_request) == len(second_request) == 1 - assert "I love this!" in first_request[0]["content"] - assert "I hate this!" in second_request[0]["content"] + first_system, first_user = model.request() + second_system, second_user = model.request(1) + assert first_system == second_system and first_system["role"] == "system" + assert first_user == {"role": "user", "content": "I love this!"} + assert second_user == {"role": "user", "content": "I hate this!"} def test_classify_repairs_invalid_sentiment() -> None: diff --git a/python/tests/test_translator.py b/python/tests/test_translator.py index 6d23b60a..ee12d358 100644 --- a/python/tests/test_translator.py +++ b/python/tests/test_translator.py @@ -3,6 +3,7 @@ from dataclasses import dataclass from typing import NewType from typing_extensions import Any, Iterator, Literal, TypedDict, override +import pytest import typechat class ConvoRecord(TypedDict): @@ -31,6 +32,13 @@ async def complete(self, prompt: str | list[typechat.PromptSection]) -> typechat self.conversation.append({ "kind": "MODEL RESPONSE", "payload": response }) return typechat.Success(response) + def request(self, index: int = 0) -> list[typechat.PromptSection]: + entry = self.conversation[index * 2] + assert entry["kind"] == "CLIENT REQUEST" + prompt = entry["payload"] + assert isinstance(prompt, list) + return prompt + @dataclass class ExampleABC: a: str @@ -39,11 +47,12 @@ class ExampleABC: v = typechat.TypeChatValidator(ExampleABC) +# Keep the original conversation snapshots as byte-for-byte legacy prompt checks. def test_translator_with_immediate_pass(snapshot: Any): m = FixedModel([ '{ "a": "hello", "b": true, "c": 1234 }', ]) - t = typechat.TypeChatJsonTranslator(m, v, ExampleABC) + t = typechat.TypeChatJsonTranslator(m, v, ExampleABC, use_legacy_prompt=True) asyncio.run(t.translate("Get me stuff.")) assert m.conversation == snapshot @@ -73,7 +82,7 @@ def test_translator_with_single_failure(snapshot: Any): '{ "a": "hello", "b": true }', '{ "a": "hello", "b": true, "c": 1234 }', ]) - t = typechat.TypeChatJsonTranslator(m, v, ExampleABC) + t = typechat.TypeChatJsonTranslator(m, v, ExampleABC, use_legacy_prompt=True) asyncio.run(t.translate("Get me stuff.")) assert m.conversation == snapshot @@ -83,7 +92,7 @@ def test_translator_with_invalid_json(snapshot: Any): '{ "a": "hello" "b": true }', '{ "a": "hello" "b": true, "c": 1234 }', ]) - t = typechat.TypeChatJsonTranslator(m, v, ExampleABC) + t = typechat.TypeChatJsonTranslator(m, v, ExampleABC, use_legacy_prompt=True) asyncio.run(t.translate("Get me stuff.")) assert m.conversation == snapshot @@ -93,7 +102,7 @@ def test_translator_with_single_failure_and_str_preamble(snapshot: Any): '{ "a": "hello", "b": true }', '{ "a": "hello", "b": true, "c": 1234 }', ]) - t = typechat.TypeChatJsonTranslator(m, v, ExampleABC) + t = typechat.TypeChatJsonTranslator(m, v, ExampleABC, use_legacy_prompt=True) asyncio.run(t.translate( "Get me stuff.", prompt_preamble="Just so you know, I need some stuff.", @@ -106,7 +115,7 @@ def test_translator_with_single_failure_and_list_preamble_1(snapshot: Any): '{ "a": "hello", "b": true }', '{ "a": "hello", "b": true, "c": 1234 }', ]) - t = typechat.TypeChatJsonTranslator(m, v, ExampleABC) + t = typechat.TypeChatJsonTranslator(m, v, ExampleABC, use_legacy_prompt=True) asyncio.run(t.translate("Get me stuff.", prompt_preamble=[ {"role": "user", "content": "Hey, I need some stuff."}, {"role": "assistant", "content": "Okay, what kind of stuff?"}, @@ -127,8 +136,162 @@ def test_translator_with_newtype(snapshot: Any): m = FixedModel([ '{ "user_id": "abc", "count": 1 }', ]) - t = typechat.TypeChatJsonTranslator(m, v_newtype, ExampleWithNewType) + t = typechat.TypeChatJsonTranslator(m, v_newtype, ExampleWithNewType, use_legacy_prompt=True) asyncio.run(t.translate("Get me a user.")) assert m.conversation == snapshot + +_VALID = '{"a":"ok","b":true,"c":1}' +_CURRENT = " A new request:\n'''keep these delimiters''' ā˜•\n" + + +def test_schema_first_sends_system_and_one_verbatim_user_request(): + model = FixedModel([_VALID]) + translator = typechat.TypeChatJsonTranslator(model, v, ExampleABC) + assert asyncio.run(translator.translate(_CURRENT)) == typechat.Success(ExampleABC("ok", True, 1)) + + system, user = model.request() + assert system["role"] == "system" + instructions = system["content"] + assert isinstance(instructions, str) + assert translator.schema_str in instructions + assert 'JSON objects of type "ExampleABC"' in instructions + assert "2 spaces of indentation and no properties with the value undefined" in instructions + assert _CURRENT not in instructions + assert user == {"role": "user", "content": _CURRENT} + + +def test_schema_first_keeps_history_roles_and_order_outside_system(): + model = FixedModel([_VALID, _VALID]) + translator = typechat.TypeChatJsonTranslator(model, v, ExampleABC) + prior = "A prior request." + asyncio.run(translator.translate(prior)) + history: list[typechat.PromptSection] = [ + {"role": "user", "content": prior}, {"role": "assistant", "content": _VALID}, + ] + original = history.copy() + asyncio.run(translator.translate(_CURRENT, prompt_preamble=history)) + + system = model.request()[0] + assert model.request(1) == [system, *original, {"role": "user", "content": _CURRENT}] + assert system["role"] == "system" + assert all(text not in system["content"] for text in (prior, _VALID, _CURRENT)) + assert history == original + + +def test_schema_first_string_preamble_stays_a_user_message(): + model = FixedModel([_VALID]) + translator = typechat.TypeChatJsonTranslator(model, v, ExampleABC) + asyncio.run(translator.translate(_CURRENT, prompt_preamble="Untrusted context.")) + system, context, request = model.request() + assert system["role"] == "system" and "Untrusted context." not in system["content"] + assert context == {"role": "user", "content": "Untrusted context."} + assert request == {"role": "user", "content": _CURRENT} + + +def test_schema_invalid_repair_appends_raw_assistant_and_user_diagnostic(): + raw = 'Model commentary\n```json\n{ "a": "ok", "b": true, "c": "not an int" }\n```\n' + model = FixedModel([raw, _VALID]) + translator = typechat.TypeChatJsonTranslator(model, v, ExampleABC) + result = asyncio.run(translator.translate(_CURRENT)) + assert result == typechat.Success(ExampleABC("ok", True, 1)) + initial = model.request() + repair = model.request(1) + assert repair[:-2] == initial + assert repair[-2] == {"role": "assistant", "content": raw} + assert repair[-1]["role"] == "user" + diagnostic = repair[-1]["content"] + assert isinstance(diagnostic, str) + assert 'Validation path `c` failed for value `"not an int"`' in diagnostic + assert initial[0]["role"] == "system" + assert raw not in initial[0]["content"] and "not an int" not in initial[0]["content"] + + +class _LegacyOnlyTranslator(typechat.TypeChatJsonTranslator[ExampleABC]): + @override + 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) + asyncio.run(translator.translate(_CURRENT, prompt_preamble="context")) + assert model.request() == [ + {"role": "user", "content": "context"}, {"role": "user", "content": f"custom request: {_CURRENT}"}, + ] + + +@pytest.mark.parametrize("instance_override", [False, True], ids=["subclass", "instance"]) +def test_legacy_only_override_requires_migration_before_model_call(instance_override: bool, monkeypatch: pytest.MonkeyPatch): + model = FixedModel([]) + if instance_override: + translator = typechat.TypeChatJsonTranslator(model, v, ExampleABC) + def legacy_prompt(intent: str) -> str: + return f"custom request: {intent}" + monkeypatch.setattr(translator, "_create_request_prompt", legacy_prompt) + else: + translator = _LegacyOnlyTranslator(model, v, ExampleABC) + with pytest.raises(ValueError, match=r"_create_request_prompt.*use_legacy_prompt=True.*_create_system_prompt"): + asyncio.run(translator.translate(_CURRENT)) + assert model.conversation == [] + + +def test_custom_system_prompt_is_used_without_invoking_legacy_hook(): + class DualTranslator(_LegacyOnlyTranslator): + @override + def _create_request_prompt(self, intent: str) -> str: + raise AssertionError("The legacy request hook must not be called for the default layout.") + + @override + def _create_system_prompt(self) -> str: + return super()._create_system_prompt() + "Application instructions." + + model = FixedModel([_VALID]) + translator = DualTranslator(model, v, ExampleABC) + asyncio.run(translator.translate(_CURRENT)) + system, user = model.request() + assert system["role"] == "system" + assert isinstance(system["content"], str) and system["content"].endswith("Application instructions.") + assert "custom request:" not in system["content"] and _CURRENT not in system["content"] + assert user == {"role": "user", "content": _CURRENT} + + +def test_more_specific_legacy_only_override_requires_migration(): + class Migrated(_LegacyOnlyTranslator): + @override + def _create_system_prompt(self) -> str: + return "Application instructions." + + class Downstream(Migrated): + @override + def _create_request_prompt(self, intent: str) -> str: + return f"Downstream instructions: {intent}" + + model = FixedModel([]) + with pytest.raises(ValueError, match="use_legacy_prompt=True"): + asyncio.run(Downstream(model, v, ExampleABC).translate(_CURRENT)) + assert model.conversation == [] diff --git a/site/src/docs/python/basic-usage.md b/site/src/docs/python/basic-usage.md index 16ed7210..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 @@ -451,13 +451,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. 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. +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, @@ -589,11 +596,65 @@ 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. +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."`. +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" diff --git a/site/src/docs/typescript/basic-usage.md b/site/src/docs/typescript/basic-usage.md index cd19e381..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 @@ -416,6 +417,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 +459,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 +467,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..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. */ @@ -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,10 +337,28 @@ function validateAuthentication(apiKey: string | undefined, provider: TokenProvi } } -function clientMessages(prompt: string | PromptSection[]): Result { - const sections: PromptSection[] = typeof prompt === "string" ? [{ role: "user", content: prompt }] : prompt; +function responsesMessages(messages: ClientMessage[]) { + return messages.map(({ role, content }) => ({ + role, + content: typeof content === "string" ? content : + content.map((part): ClientResponseContent => part.type === "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: 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."); } @@ -419,6 +431,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 +448,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..89ce710f 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,64 @@ function mockClient(api, responses) { return { client, calls, isClosed: () => closed }; } +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 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)]); + 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" } }]; + 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" ? ["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"; + 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" }; @@ -403,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" }] }],