Skip to content
Open
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
21 changes: 19 additions & 2 deletions python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,22 @@ To learn more about TypeChat, visit the
[documentation](https://microsoft.github.io/TypeChat/docs/python/basic-usage/)
which includes more information on TypeChat and how to get started.

## Translator prompts in 0.3

`await translator.translate(request)` sends the schema and JSON instructions as a
`system` message, then the verbatim request as a `user` message. For a follow-up,
pass earlier messages as `prompt_preamble`: they go between those two messages,
with their original roles and order. A nonempty string preamble is one `user`
message. The translator does not remember earlier turns for you.

To keep the pre-0.3 combined user prompt, construct
`TypeChatJsonTranslator(model, validator, target_type, use_legacy_prompt=True)`.
This keyword-only option keeps existing `_create_request_prompt(self, intent)`
overrides in the **user** role. For the new default, customize
`_create_system_prompt(self)` with application-owned instructions only. See the
[migration guide](../site/src/docs/python/basic-usage.md#prompt-layout-and-migration)
and the [math](./examples/math/program.py) and [health-data](./examples/healthData/translator.py) examples.

## Reusing model authentication

For keyless Azure OpenAI requests, pass a synchronous or asynchronous bearer-token
Expand Down Expand Up @@ -150,8 +166,9 @@ user/system text to `input_text`, assistant text to `output_text`, and images to
`input_image` with a flat `image_url` string and optional `detail`, preserving
order, references, and omitted detail.

`translate` still takes a string request. Its preamble stays before the generated
schema/request message, and image context is preserved during validation and repair.
`translate` still takes a string request. Image context stays in the preamble,
including during repair: the translator appends the raw assistant reply and a
user diagnostic without rewriting earlier messages.
Successful model completions remain text-only. Authentication, HTTP controls, and
configured-client ownership remain unchanged.

Expand Down
9 changes: 6 additions & 3 deletions python/examples/drawing/demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from typechat import (
Success,
Failure,
PromptSection,
TypeChatJsonTranslator,
TypeChatValidator,
create_language_model,
Expand All @@ -30,12 +31,14 @@ async def main(file_path: str | None):
canvas.pack(padx=10, pady=10)
canvas.bind("<Button-1>", lambda event: window.quit())

history: list[str] = []
history: list[PromptSection] = [
{"role": "system", "content": "Return the complete drawing, applying all drawing requests in order."},
]

async def request_handler(request: str):
print("[Sending request...]")
history.append(request)
result: Success[schema.Drawing] | Failure = await translator.translate("\n".join(history))
result: Success[schema.Drawing] | Failure = await translator.translate(request, prompt_preamble=history)
history.append({"role": "user", "content": request})
if isinstance(result, Failure):
print("Failure:", result.message)
else:
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
54 changes: 32 additions & 22 deletions python/examples/healthData/translator.py
Original file line number Diff line number Diff line change
@@ -1,44 +1,55 @@
import json
from typing_extensions import TypeVar, Any, override, TypedDict, Literal
from datetime import datetime

from typechat import TypeChatValidator, TypeChatLanguageModel, TypeChatJsonTranslator, Result, Failure, PromptSection
from pydantic_core import to_jsonable_python
from typing_extensions import TypeVar, override

from datetime import datetime
from typechat import TypeChatValidator, TypeChatLanguageModel, TypeChatJsonTranslator, Result, Success, PromptSection

T = TypeVar("T", covariant=True)


class ChatMessage(TypedDict):
source: Literal["system", "user", "assistant"]
body: Any
def _clock_instructions() -> str:
now = datetime.now()
return f"""Use precise date and times RELATIVE TO CURRENT DATE: {now:%A, %m %d, %Y} CURRENT TIME: {now:%H:%M:%S}
Also turn ranges like next week and next month into precise dates"""


class TranslatorWithHistory(TypeChatJsonTranslator[T]):
_chat_history: list[ChatMessage]
_max_prompt_length: int
_additional_agent_instructions: str

def __init__(
self, model: TypeChatLanguageModel, validator: TypeChatValidator[T], target_type: type[T], additional_agent_instructions: str
self, model: TypeChatLanguageModel, validator: TypeChatValidator[T], target_type: type[T],
additional_agent_instructions: str, *, use_legacy_prompt: bool = False,
):
super().__init__(model=model, validator=validator, target_type=target_type)
self._chat_history = []
self._max_prompt_length = 2048
super().__init__(model, validator, target_type, use_legacy_prompt=use_legacy_prompt)
self._chat_history: list[object] = []
self._additional_agent_instructions = additional_agent_instructions

@override
async def translate(self, input: str, *, prompt_preamble: str | list[PromptSection] | None = None) -> Result[T]:
if not self._use_legacy_prompt and self._chat_history:
context: list[PromptSection] = []
if isinstance(prompt_preamble, str):
if prompt_preamble:
context.append({"role": "user", "content": prompt_preamble})
elif prompt_preamble:
context.extend(prompt_preamble)
for body in self._chat_history:
context.append({"role": "assistant", "content": json.dumps(body, indent=2, allow_nan=False)})
prompt_preamble = context

result = await super().translate(input=input, prompt_preamble=prompt_preamble)
if not isinstance(result, Failure):
self._chat_history.append(ChatMessage(source="assistant", body=result.value))
if isinstance(result, Success):
self._chat_history.append(to_jsonable_python(result.value))
return result

@override
def _create_request_prompt(self, intent: str) -> str:
# TODO: drop history entries if we exceed the max_prompt_length
history_str = json.dumps(self._chat_history, indent=2, default=lambda o: None, allow_nan=False)
def _create_system_prompt(self) -> str:
return f"{super()._create_system_prompt()}\n{_clock_instructions()}\n\n{self._additional_agent_instructions}"

now = datetime.now()
@override
def _create_request_prompt(self, intent: str) -> str:
history = [{"source": "assistant", "body": body} for body in self._chat_history]
history_str = json.dumps(history, indent=2, allow_nan=False)

prompt = F"""
user: You are a service that translates user requests into JSON objects of type "{self.type_name}" according to the following TypeScript definitions:
Expand All @@ -47,8 +58,7 @@ def _create_request_prompt(self, intent: str) -> str:
'''

user:
Use precise date and times RELATIVE TO CURRENT DATE: {now.strftime('%A, %m %d, %Y')} CURRENT TIME: {now.strftime("%H:%M:%S")}
Also turn ranges like next week and next month into precise dates
{_clock_instructions()}

user:
{self._additional_agent_instructions}
Expand Down
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
```
36 changes: 23 additions & 13 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 _create_request_prompt(self, intent: str) -> str:
return f"""{self._program_instructions()}
The following is a user request:
'''
{intent}
'''
The following is the user request translated into a JSON program object with 2 spaces of indentation and no properties with the value undefined:
"""
return prompt

@override
def _create_repair_prompt(self, validation_error: str) -> str:
Expand Down
15 changes: 5 additions & 10 deletions python/examples/multiSchema/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,11 @@ def register_agent(self, name: str, description: str, handler: Callable[[str], A
self._current_agents[name] = agent

async def route_request(self, line: str):
classes_str = json.dumps(self._current_agents, indent=2, default=lambda o: None, allow_nan=False)

prompt_fragment = F"""
Classify ""{line}"" using the following classification table:
'''
{classes_str}
'''
"""

result = await self._translator.translate(prompt_fragment)
classes = {name: agent["description"] for name, agent in self._current_agents.items()}
result = await self._translator.translate(line, prompt_preamble=[{
"role": "system",
"content": f"Classify the user request using this table of registered agents:\n{json.dumps(classes, indent=2)}",
}])
if isinstance(result, Failure):
print("Translation Failed ❌")
print(f"Context: {result.message}")
Expand Down
4 changes: 2 additions & 2 deletions python/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion python/package.json
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
2 changes: 1 addition & 1 deletion python/src/typechat/__about__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# SPDX-FileCopyrightText: Microsoft Corporation
#
# SPDX-License-Identifier: MIT
__version__ = "0.1.0"
__version__ = "0.3.0"
6 changes: 3 additions & 3 deletions python/src/typechat/_internal/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading