Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide a Python implementation of TypeChat #148

Merged
merged 6 commits into from
Dec 31, 2023
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
162 changes: 162 additions & 0 deletions python/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at /~https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

node_modules
47 changes: 47 additions & 0 deletions python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# TypeChat

<!--
[![PyPI - Version](https://img.shields.io/pypi/v/typechat.svg)](https://pypi.org/project/typechat)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/typechat.svg)](https://pypi.org/project/typechat)
-->

-----

**Table of Contents**

- [Installation](#installation)
- [License](#license)

## Installation

<!--
```console
pip install typechat
```
-->

## License

`typechat` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license.

## Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide
a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions
provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.

## Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft
trademarks or logos is subject to and must follow
[Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general).
Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship.
Any use of third-party trademarks or logos are subject to those third-party's policies.
33 changes: 33 additions & 0 deletions python/examples/coffee-shop/demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import asyncio
import json
import sys

import openai
import schema as coffeeshop
from dotenv import dotenv_values

from typechat import DefaultOpenAIModel, Failure, TypeChatTranslator, TypeChatValidator


async def main():
vals = dotenv_values()
client = openai.AsyncOpenAI(api_key=vals["OPENAI_API_KEY"])
model = DefaultOpenAIModel(model_name=vals.get("OPENAI_MODEL", None) or "gpt-3.5-turbo", client=client)
validator = TypeChatValidator(coffeeshop.Cart)
translator = TypeChatTranslator(model, validator, coffeeshop.Cart)
print("☕> ", end="", flush=True)
for line in sys.stdin:
result = await translator.translate(line)
if isinstance(result, Failure):
print("Translation Failed ❌")
print(f"Context: {result.message}")
else:
result = result.value
print("Translation Succeeded! ✅\n")
print("JSON View")
print(json.dumps(result, indent=2))
print("\n☕> ", end="", flush=True)


if __name__ == "__main__":
asyncio.run(main())
140 changes: 140 additions & 0 deletions python/examples/coffee-shop/schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
from typing import Literal, NotRequired, TypedDict


class UnknownText(TypedDict):
"""
Represents any text that could not be understood.
"""

type: Literal["UnknownText"]
text: str


class Caffeine(TypedDict):
type: Literal["Caffeine"]
name: Literal["regular", "two thirds caf", "half caf", "one third caf", "decaf"]


class Milk(TypedDict):
type: Literal["Milk"]
name: Literal[
"whole milk", "two percent milk", "nonfat milk", "coconut milk", "soy milk", "almond milk", "oat milk"
]


class Creamer(TypedDict):
type: Literal["Creamer"]
name: Literal[
"whole milk creamer",
"two percent milk creamer",
"one percent milk creamer",
"nonfat milk creamer",
"coconut milk creamer",
"soy milk creamer",
"almond milk creamer",
"oat milk creamer",
"half and half",
"heavy cream",
]


class Topping(TypedDict):
type: Literal["Topping"]
name: Literal["cinnamon", "foam", "ice", "nutmeg", "whipped cream", "water"]
optionQuantity: NotRequired["OptionQuantity"]


class LattePreparation(TypedDict):
type: Literal["LattePreparation"]
name: Literal["for here cup", "lid", "with room", "to go", "dry", "wet"]


class Sweetener(TypedDict):
type: Literal["Sweetener"]
name: Literal["equal", "honey", "splenda", "sugar", "sugar in the raw", "sweet n low", "espresso shot"]
optionQuantity: NotRequired["OptionQuantity"]


CaffeineOptions = Caffeine | Milk | Creamer

LatteOptions = CaffeineOptions | Topping | LattePreparation | Sweetener

CoffeeTemperature = Literal["hot", "extra hot", "warm", "iced"]

CoffeeSize = Literal["short", "tall", "grande", "venti"]

EspressoSize = Literal["solo", "doppio", "triple", "quad"]

OptionQuantity = Literal["no", "light", "regular", "extra"]


class Syrup(TypedDict):
type: Literal["Syrup"]
name: Literal[
"almond syrup",
"buttered rum syrup",
"caramel syrup",
"cinnamon syrup",
"hazelnut syrup",
"orange syrup",
"peppermint syrup",
"raspberry syrup",
"toffee syrup",
"vanilla syrup",
]
optionQuantity: NotRequired[OptionQuantity]


class LatteDrink(TypedDict):
type: Literal["LatteDrink"]
name: Literal["cappuccino", "flat white", "latte", "latte macchiato", "mocha", "chai latte"]
temperature: NotRequired["CoffeeTemperature"]
size: NotRequired["CoffeeSize"] # The default is 'grande'
options: NotRequired[list[Creamer | Sweetener | Syrup | Topping | Caffeine | LattePreparation]]


class EspressoDrink(TypedDict):
type: Literal["EspressoDrink"]
name: Literal["espresso", "lungo", "ristretto", "macchiato"]
temperature: NotRequired["CoffeeTemperature"]
size: NotRequired["EspressoSize"] # The default is 'doppio'
options: NotRequired[list[Creamer | Sweetener | Syrup | Topping | Caffeine | LattePreparation]]


class CoffeeDrink(TypedDict):
type: Literal["CoffeeDrink"]
name: Literal["americano", "coffee"]
temperature: NotRequired[CoffeeTemperature]
size: NotRequired[CoffeeSize] # The default is "grande"
options: NotRequired[list[Creamer | Sweetener | Syrup | Topping | Caffeine | LattePreparation]]


class BakeryOption(TypedDict):
type: Literal["BakeryOption"]
name: Literal["butter", "strawberry jam", "cream cheese"]
optionQuantity: NotRequired["OptionQuantity"]


class BakeryPreparation(TypedDict):
type: Literal["BakeryPreparation"]
name: Literal["warmed", "cut in half"]


class BakeryProduct(TypedDict):
type: Literal["BakeryProduct"]
name: Literal["apple bran muffin", "blueberry muffin", "lemon poppyseed muffin", "bagel"]
options: NotRequired[list[BakeryOption | BakeryPreparation]]


Product = BakeryProduct | LatteDrink | CoffeeDrink | UnknownText


class LineItem(TypedDict):
type: Literal["LineItem"]
product: Product
quantity: int


class Cart(TypedDict):
type: Literal["Cart"]
items: list[LineItem | UnknownText]
Loading