Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 32 additions & 9 deletions python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -150,16 +169,20 @@ 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.

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

Expand Down
17 changes: 12 additions & 5 deletions python/examples/drawing/demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,46 @@
import tkinter as tk

from dotenv import dotenv_values
from typing_extensions import override

import schema
from render import render_drawing

from typechat import (
Success,
Failure,
PromptSection,
TypeChatJsonTranslator,
TypeChatValidator,
create_language_model,
process_requests,
)


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...")
canvas = tk.Canvas(window, width=800, height=600, bg="white", highlightthickness=0)
canvas.pack(padx=10, pady=10)
canvas.bind("<Button-1>", 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:
Expand Down
10 changes: 9 additions & 1 deletion python/examples/healthData/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
61 changes: 35 additions & 26 deletions python/examples/healthData/translator.py
Original file line number Diff line number Diff line change
@@ -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}
Expand All @@ -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
27 changes: 16 additions & 11 deletions python/examples/math/README.md
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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
```
38 changes: 24 additions & 14 deletions python/examples/math/program.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,33 +118,43 @@ 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}
```
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:
Expand Down
4 changes: 4 additions & 0 deletions python/examples/multiSchema/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading