Skip to content

Proposed alternate prompting scheme - #241

Open
Guido van Rossum (gvanrossum) wants to merge 3 commits into
microsoft:mainfrom
gvanrossum:history
Open

Guido van Rossum (gvanrossum) wants to merge 3 commits into
microsoft:mainfrom
gvanrossum:history

Conversation

@gvanrossum

@gvanrossum Guido van Rossum (gvanrossum) commented Apr 22, 2024 •

Copy link
Copy Markdown
Collaborator

This is my proposal to address #39. It also fixes the issue I flagged in #240 about the user input being repeated twice. I tried it with my demo from #238 and that seems to work.

The prompt structure is as follows:

  • System: "You are a ..., up to and including the schema, with instructions for how to format the JSON"
  • prompt_prelude (user and bot messages)
  • User: (the user request)

I don't understand how your test tools work (I'm a dinosaur, I don't know how hatch or toml or pipenv work, I can handle pytest though).

Daniel Rosenwasser (@DanielRosenwasser)

@DanielRosenwasser

Copy link
Copy Markdown
Member

So this matches my intuition around how to put all of this together. While we have no way of testing for a regression, I'd be okay with running with something like this for now. The thing I'll note is that when Anders Hejlsberg (@ahejlsberg) tried something like this with the system prompt, he got slightly worse results.

That said, he guessed part of this was probably tied to the schema falling further and further behind in history. So maybe something to alleviate this would be to instead do:

  • prompt_prelude (user and bot messages)
  • System: "You are a ..., up to and including the schema, with instructions for how to format the JSON"
  • User: (the user request)

Basically, move the system prompt immediately before the user request.


I don't understand how your test tools work

No worries. To most quickly fix the build:

cd TypeChat/python
pip install -e .[dev,examples]
pytest --snapshot-update
git add tests
git commit -m "Update snapshots."

@DanielRosenwasser

Copy link
Copy Markdown
Member

It probably also makes sense to make the repair prompt a system message as well.

@DanielRosenwasser

Copy link
Copy Markdown
Member

One of the things I tried in https://github.com/microsoft/TypeChat/tree/systemPromptPython (ea0e0d8) was to take the approach here after fixing some issues. As Anders Hejlsberg (@ahejlsberg) mentioned, OpenAI unfortunately doesn't do a great job when you switch to the system prompts. Trying things out on the coffee shop example input file, it generally got more "wrong".

One idea we could try is to expose the (very basic) logic we use to parse out JSON so that people can override translate and do whatever they want.

But otherwise, the only other approaches I could advise to implement something like #238 is to experiment with preambles to talk about past state.

@gvanrossum

Copy link
Copy Markdown
Collaborator Author

Thanks for the feedback!

Preamble issues

My problem with the preamble is that it is prefixed to the prompt containing the schema, which makes the conversation a bit awkward, as it goes like this (ignoring system messages):

  • user: draw three squares
  • bot: {some JSON}
  • user: make them bigger
  • bot: {some JSON}
  • user: Please translate user requests into JSON using this schema: {schema JSON}. Here is a user question: make them red

What I want is this (because my intuition tells me that it's a more natural dialog):

  • user: Please translate user requests into JSON using this schema: {schema JSON}. Here is a user question: draw three squares
  • bot: {some JSON}
  • user: make them bigger
  • bot: {some JSON}
  • user: make them red

About system messages:

My (rudimentary) understanding of system messages is that it's meant to set a behavior or personality that's hard(er) to subvert by users trying to be clever -- e.g. the system prompt would tell the model not to be racist. In TypeChat's case, I think that at best the prompt that sets the schema should be a system prompt, but the repair prompts should probably just be user prompts.

The docs say a little bit about this. It makes me think that it's not worth experimenting too much with this in particular.

I also just noticed "JSON Mode" in the docs, which may or may not be useful for TypeChat.

@ahejlsberg

Anders Hejlsberg (ahejlsberg) commented May 2, 2024 •

Copy link
Copy Markdown
Member

Guido van Rossum (@gvanrossum) FWIW, a while back I did a multi-turn experiment where I didn't include previous replies in the prompt, but rather just repeated the request with the additional user input concatenated to the the previous user input (separated by newlines). So, your example would have a single user prompt section with text like:

Please translate user requests into JSON using this schema:
{schema JSON}.
Here is a user question:
draw three squares
make them bigger
make them red

It seemed to work quite well. Wonder if that would work in your case?

@ahejlsberg

Anders Hejlsberg (ahejlsberg) commented May 2, 2024 •

Copy link
Copy Markdown
Member

I also just noticed "JSON Mode" in the docs, which may or may not be useful for TypeChat.

The reason we aren't using JSON Mode is that there is no good way to know upfront if a model supports it, and, unfortunately, older models don't know to ignore it, but instead error on the request.

Also, not getting JSON back from requests hasn't really been an issue.

@gvanrossum

Copy link
Copy Markdown
Collaborator Author

robgruen added a commit that referenced this pull request Jun 1, 2026
* Install python-dotenv and tabulate

* Small working demo that can draw boxes on a canvas

The idea is that you can write a small amount of JavaScript that reads the
JSON and renders in an HTML5 canvas, or some Python that renders it in Tkinter,
or anything else that strikes your fancy.

I would like to use this to draw diagrams representing the stack and
memory layout for an interpreter, to be used in internal docs.

* Add chat history to drawing demo

* [WIP] Hack on translation a bit

* New API for chat history

* Improved the schema with ChatGPT's help. Added Arrow and Ellipse.

* rendering program using Tkinter

* Add a simple rendering function (most of it written by ChatGPT)

* Added dashed and dotted arrows (some help from ChatGPT)

* Rip oput history, for now

* Make pyright happy

* Keep pydantic also happy

* Add (flawed) history based on prompt_preamble

* Prune history

* Add temporary logging

* Alternate prompting scheme from #241

* Revert changes to translator.py

* Use Anders' suggestion for history

(Just append the inputs, separated by newlines.)

* Switch schema to dataclasses

* Black formatting

* Remove unused imports

* Clarify Failure output

* Revert verbose logging

* Reuse drawing window

* Don't crash if we cannot import readline (e.g. on Windows)

* Add crude progress messages

* Address PR #238 review-thread feedback in drawing example and interactive input helper

Restrict Style.line_style to Literal["solid", "dashed", "dotted"], align the
UnknownText discriminant to Literal["Unknown"], fix the Arrow docstring, harden
the dash-pattern lookup with a safe fallback to solid, and mark the optional
readline import as intentionally unused (noqa: F401).

---------

Co-authored-by: robgruen <robgruen@microsoft.com>

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Shouldn't there be a test showing something has improved? Or are there no tests using live models?

I have to say I'm not sure about the AI-generated report -- I feel overwhelmed by all the data, and I don't know what it's trying to look for or what's significant. Also, why is it testing the non-Python implementations? Any changes there would be just noise, since this PR doesn't affect them.

num_repairs_attempted += 1
messages.append({"role": "user", "content": self._create_repair_prompt(error_message)})

def _create_request_prompt(self, intent: str) -> str:

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The 'intent' argument is no longer used. Since this is an internal function, can't you remove it?

if isinstance(prompt_preamble, str):
prompt_preamble = [{"role": "user", "content": prompt_preamble}]
else:
messages.extend(prompt_preamble)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Do I understand correctly that the original code had a bug, where if prompt_preamble was a string, it would be ignored? Was that bug reported in any issue?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This was your change from a while ago so I can't speak to that. I think you mean to have the "intent" to be a separate user message after the JSON translation string which you're proposing as the system prompt.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

here are no live tests at the moment, that's on the TODO list.  The AI generated report I sent you compares the existing prompting scheme in comparison with the one proposed here. Since both the C# and TypeScript implementations have the same prompting scheme I wanted to ensure that we see the same results across implementations.

The net takeaway is that the net token count goes down by a few percentage points as does the overall retry count. With the current set of models this approach is marginally better given the sample schemas we have in the repo at this time. I would like to flush it out a bit more before declaring victory and making a final determination. I favor this approach since there is clear separation between the messages whereas the existing schema is slightly more coupled.

@robgruen

Copy link
Copy Markdown
Contributor

Guido van Rossum (@gvanrossum), thanks for proposing this. We followed up on your question about conversation history with live A/B tests. The clearest result was a reduction in repeated input on hosted sessions, not better accuracy.

576-call cross-runtime comparison. We used the real Python, TypeScript, and TypeChat.NET translators with the same Cart schema, wording, and scorer. The four conversations covered two-latte corrections, removing a bakery item, moving a modifier, and selectively undoing an earlier edit. Each layout went first and second for every case. Both layouts got 288/288 turns correct, including 192/192 follow-ups; all 576 responses passed validation on the first attempt. Each runtime also passed 56 offline checks, including stale-but-valid carts, invalid responses, and forced repairs.

Total tokens per 24 turns per layout per runtime, baseline → schema-first. Median turn times are across the three runtimes. A/B/C denote fixed Azure deployments; the SDK comparison requested the same model as C.

Route Python TypeScript TypeChat.NET Tokens saved Median turn
Direct Azure A 34,822 → 34,352 34,794 → 34,278 34,762 → 34,268 1.42% 2.14 → 2.14 s
Direct Azure B 34,055 → 33,594 34,049 → 33,620 34,031 → 33,581 1.31% 1.54 → 1.39 s
Direct Azure C 33,706 → 33,514 33,706 → 33,514 33,706 → 33,514 0.57% 2.92 → 2.91 s
GitHub Copilot SDK (C) 132,800 → 106,094 132,800 → 106,094 132,800 → 106,094 20.11% 3.17 → 3.19 s

The SDK baseline retains earlier user messages that contain the schema. Direct TypeChat history in this test keeps the earlier plain requests and assistant replies instead. On route C via the SDK, the entire 80,118-token difference across runtimes was input; output was unchanged. Latency did not consistently improve.

Earlier Python-only checks (separate runs, not pooled)
  • Eight-call smoke test: both layouts got 4/4 turns right; 5,338 → 5,282 tokens.
  • 240-call multi-family matrix: 79/80 → 80/80 correct follow-ups. The single miss was a selective undo; the baseline got it right on repeat. All responses validated without repair. Schema-first used 16.6–21.5% fewer tokens across four SDK models and 0.9% fewer on the direct Azure control.

Suggested next step for this draft: make schema-first opt-in in Python. Keep the existing default layout, preamble roles/order, validation, and repair behavior. Give the new mode a separate builder for the trusted schema/instructions: the existing math and health-data prompt overrides include the user's request, so their output shouldn't be relabeled as a system message. We checked that user text, raw replies, and repair diagnostics stayed out of the application-owned system text. That's a message-construction guarantee, not a claim of jailbreak resistance. Four coffee scenarios aren't enough evidence to change the default.

Guido, we'd like to build on your original commit here. Happy for you to lead, to pair, or to bring the branch up to date and do the implementation if you'd prefer. Let us know what works for you.

robgruen and others added 2 commits November 23, 2026 17:46
Keep current main's validation, raw repair messages, failure payloads and adapters. Separate the application system hook from the legacy request hook and retain the original prompt snapshots for explicit compatibility.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Keep both calculator schemas in the math instructions, refresh the health clock per turn, and replay only validated assistant results as history. Cover the native examples and document the explicit pre-0.3 layout.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@robgruen

Copy link
Copy Markdown
Contributor

Thanks again, Guido van Rossum (@gvanrossum). The current Python candidate builds on your original commit: main was merged into this branch, without rewriting its history.

One update to the earlier benchmark note: the 0.3.x proposal (#539) now puts schema-first on by default at a breaking release boundary, rather than opting people into the new layout. A fresh translation sends the application's schema/instructions and then the raw user request. Existing applications can explicitly select use_legacy_prompt=True. Math still distinguishes the output program from its callable API; health-data keeps prior validated assistant results out of system instructions.

The Python candidate passed 764 tests and 22 snapshots, with a clean Pyright check. From an isolated install of the 0.3.0 wheel, a recording model verified the fresh request, a follow-up with role-tagged history, and a forced repair retaining the rejected assistant text and user-role diagnostic. The separately installed TypeScript candidate (#540) passed the same check. No live calls or registry publication were needed.

This remains a draft pending the policy review and normal code review; the existing discussions are left open.

@robgruen
robgruen marked this pull request as ready for review November 24, 2026 17:13
Copilot AI balanced review requested due to automatic review settings November 24, 2026 17:13
@robgruen

Copy link
Copy Markdown
Contributor

Live check for the 0.3 review handoff: after #539 merged, we exercised the installed Python wheel (638fbad8), TypeScript tarball (3ae4c63a), and .NET preview package (9393d888) against Azure OpenAI GPT-4.1-mini.

All three returned a validated count of 12 on a fresh schema-first request, 17 when asked to add five using the actual prior reply, and 4 on a separate explicit legacy request. The fresh default sent system, user; the follow-up sent system, user, assistant, user. Nine live calls, nine correct results, no repairs or retries. This is a small release smoke test, not a general model-accuracy comparison. All three unchanged heads are now ready for human review.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues are reported for the Python prompt-layout changes.

No open issues 🎉

1 file not reviewed
  • python/package-lock.json: Generated file
What changed in this PR

This PR changes Python translator prompts to support conversation-style requests: schema instructions come first, followed by supplied history and one unchanged user request. It also provides an explicit legacy mode for existing custom prompts.

Changes:

  • Introduces system-first prompts, a system-prompt customization hook, and migration checks for legacy overrides.
  • Updates examples and regression tests for history, repair, multimodal context, and provider adapters.
  • Documents migration and updates Python version metadata to 0.3.0.
File Description
site/​src/​docs/​python/​basic-usage.md Documents prompt layout, migration, history, and repair behavior.
python/​tests/​test_translator.py Tests the new layout and hooks while retaining legacy snapshots.
python/​tests/​test_sentiment_non_interactive.py Updates assertions for separate system and user messages.
python/​tests/​test_responses_model.py Updates Responses adapter tests for system-first prompts.
python/​tests/​test_multimodal_model.py Checks image-context preservation with the new layout.
python/​tests/​test_failure.py Tests unsupported system roles and repair message ordering.
python/​tests/​test_example_prompt_layouts.py Adds offline prompt-layout tests for example translators.
python/​tests/​test_client_model.py Updates configured-client repair role expectations.
python/​src/​typechat/​_internal/​translator.py Adds system-first prompts, legacy mode, and override migration checks.
python/​src/​typechat/​_internal/​model.py Updates prompt-role documentation.
python/​src/​typechat/​__about__.py Sets the Python package version to 0.3.0.
python/​README.md Explains new prompts, compatibility, and context preservation.
python/​package.json Aligns tooling package version metadata with 0.3.0.
python/​package-lock.json Synchronizes lockfile version metadata.
python/​examples/​multiSchema/​router.py Separates routing instructions from the user request.
python/​examples/​math/​README.md Documents both layouts and corrects sample output.
python/​examples/​math/​program.py Supports system-first and legacy program-generation prompts.
python/​examples/​healthData/​translator.py Separates instructions from validated history and preserves legacy mode.
python/​examples/​healthData/​README.md Documents clock and history behavior; corrects the example name.
python/​examples/​drawing/​demo.py Passes earlier drawing requests as structured preamble messages.

Review effort: Balanced

@gvanrossum Guido van Rossum (gvanrossum) left a comment •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Hi Rob,

I'm sorry, I just can't refresh my brain about the intricacies of TypeChat. It also looks like I can't even rubber-stamp approve it -- probably because there's a commit of mine in the PR. :-(

Enjoy the holidays!

@robgruen

robgruen commented Nov 24, 2026 via email

Copy link
Copy Markdown
Contributor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants