### Set up TypeChat on Local Machine Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/README.md Clones the TypeChat repository, navigates into the TypeScript directory, and installs Node.js dependencies. Requires Node.js 18.16.0 LTS or newer. ```sh git clone https://github.com/microsoft/TypeChat cd TypeChat/typescript npm install ``` -------------------------------- ### Run TypeChat Example with Input File Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/README.md Demonstrates how to execute a TypeChat example by providing an input file path as an argument to the main script. This allows for non-interactive processing of predefined inputs. ```sh node ./dist/main.js ./dist/input.txt ``` -------------------------------- ### Build TypeChat and Examples Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/README.md Executes the build script to compile TypeChat and its associated examples. This command should be run from the repository root. ```sh npm run build-all ``` -------------------------------- ### Example .env File for API Configuration Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/README.md Illustrates how to structure a `.env` file in the project's root directory to set environment variables for OpenAI API access. ```ini # For OpenAI OPENAI_MODEL=... OPENAI_API_KEY=... ``` -------------------------------- ### Local Development Setup: Using venv and pip for TypeChat Python Source: https://github.com/microsoft/typechat/blob/main/python/examples/README.md Details the steps to set up the TypeChat Python examples using a standard Python virtual environment (venv) and pip. It includes cloning the repository, creating and activating the virtual environment, installing dependencies, and running the sentiment analysis demo. ```Shell git clone https://github.com/microsoft/TypeChat cd TypeChat/python python -m venv ../.venv # Activate the virtual environment # Windows ../.venv/Scripts/Activate.ps1 # Unix/POSIX source ../.venv/bin/activate pip install .[examples] python examples/sentiment/demo.py ``` -------------------------------- ### Clone and Install TypeChat Repository Source: https://github.com/microsoft/typechat/blob/main/site/src/docs/examples.md This snippet provides commands to clone the TypeChat GitHub repository and install its dependencies using npm. This is the first step to set up the development environment on a local machine, requiring Node.js 18.16.0 LTS or newer. ```bash git clone https://github.com/microsoft/TypeChat cd TypeChat npm install ``` -------------------------------- ### Run TypeChat Examples with Input File Source: https://github.com/microsoft/typechat/blob/main/python/examples/README.md This command demonstrates how to run a TypeChat example script by providing a specific input file. This is useful for automated testing or processing predefined inputs, such as sample prose files found in the 'src' directories. ```shell python demo.py ``` ```shell python demo.py input.txt ``` -------------------------------- ### Install TypeChat Project in Editable Mode Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/calendar.ipynb Installs the TypeChat project from the parent directory in editable mode, allowing local changes to be reflected without reinstallation. ```python %pip install -e ../ ``` -------------------------------- ### Install Core Python Dependencies Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/calendar.ipynb Installs essential Python packages required for the TypeChat project, including Gradio for the UI, pandas for data handling, and python-dotenv for environment variables. ```python %pip install --upgrade setuptools %pip install --upgrade gradio %pip install ipywidgets %pip install pandas %pip install tabulate %pip install python-dotenv ``` -------------------------------- ### Install Core Python Dependencies Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/music.ipynb This snippet installs essential Python packages required for the TypeChat project, including `setuptools`, `gradio`, `ipywidgets`, `openai`, `pandas`, `tabulate`, and `python-dotenv`. These packages provide functionalities for project setup, UI, AI model interaction, data handling, and environment variable management. ```python %pip install --upgrade setuptools %pip install --upgrade gradio %pip install ipywidgets %pip install openai %pip install pandas %pip install tabulate %pip install python-dotenv ``` -------------------------------- ### Install Required Python Packages Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/math.ipynb This snippet installs or upgrades the necessary Python packages, `setuptools` and `gradio`, which are dependencies for running the TypeChat math example and creating the web interface. ```python %pip install --upgrade setuptools %pip install --upgrade gradio ``` -------------------------------- ### Local Development Setup: Using Hatch for TypeChat Python Source: https://github.com/microsoft/typechat/blob/main/python/examples/README.md Provides commands to clone the TypeChat repository, navigate to the Python directory, activate a Hatch shell, and run the sentiment analysis demo. This method uses Hatch for project and environment management. ```Shell git clone https://github.com/microsoft/TypeChat cd TypeChat/python hatch shell python examples/sentiment/demo.py ``` -------------------------------- ### Run TypeChat Examples Interactively Source: https://github.com/microsoft/typechat/blob/main/python/examples/README.md This command shows how to execute a TypeChat example script in an interactive mode. Users can provide input directly in the console until they type 'quit' or 'exit' to terminate the session. ```shell python examples//demo.py ``` -------------------------------- ### Build TypeChat Examples Source: https://github.com/microsoft/typechat/blob/main/site/src/docs/examples.md After setting up the development environment, this command compiles TypeChat and all its examples. It should be run from the repository root to ensure all necessary components are built. ```bash npm run build-all ``` -------------------------------- ### Configure Environment Variables for Azure OpenAI Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/README.md Defines the required environment variables for connecting to an Azure OpenAI API endpoint. Includes the full REST API URL and the API key. ```APIDOC AZURE_OPENAI_ENDPOINT: The full URL of the Azure OpenAI REST API (e.g. https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/chat/completions?api-version=2023-05-15) AZURE_OPENAI_API_KEY: Your Azure OpenAI API key ``` -------------------------------- ### Install TypeChat via npm Source: https://github.com/microsoft/typechat/blob/main/typescript/README.md Instructions to install the TypeChat library using the npm package manager. This is the quickest way to get started with TypeChat for JavaScript/TypeScript projects. ```sh npm install typechat ``` -------------------------------- ### Install Required Python Packages Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/coffeeShop.ipynb This snippet shows how to install or upgrade the necessary Python packages, `setuptools` and `gradio`, using pip. These packages are essential for managing dependencies and creating the web-based user interface, respectively. ```Python %pip install --upgrade setuptools %pip install --upgrade gradio ``` -------------------------------- ### Configure Environment Variables for OpenAI Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/README.md Defines the required and optional environment variables for connecting to an OpenAI API endpoint. Includes model name, API key, optional endpoint URL, and organization ID. ```APIDOC OPENAI_MODEL: The OpenAI model name (e.g. gpt-3.5-turbo or gpt-4) OPENAI_API_KEY: Your OpenAI API key OPENAI_ENDPOINT: OpenAI API Endpoint - optional, defaults to "https://api.openai.com/v1/chat/completions" OPENAI_ORGANIZATION: OpenAI Organization - optional, defaults to "" ``` -------------------------------- ### Example .env File Configuration Source: https://github.com/microsoft/typechat/blob/main/site/src/docs/examples.md This snippet provides an example of a `.env` file structure for conveniently setting both OpenAI and Azure OpenAI environment variables. This method is recommended for managing API keys and endpoint URLs locally. ```dotenv # For OpenAI OPENAI_MODEL=... OPENAI_API_KEY=... # For Azure OpenAI AZURE_OPENAI_ENDPOINT=... AZURE_OPENAI_API_KEY=... ``` -------------------------------- ### Run TypeChat Example with Input File Source: https://github.com/microsoft/typechat/blob/main/site/src/docs/examples.md Demonstrates how to execute a TypeChat example using a specific input file. This command runs the main script with the content of `input.txt` as its input, useful for non-interactive processing. ```Shell node ./dist/main.js ./dist/input.txt ``` -------------------------------- ### Configure Environment Variables for OpenAI and Azure OpenAI Source: https://github.com/microsoft/typechat/blob/main/python/examples/README.md This snippet illustrates the recommended `.env` file format for configuring API keys and model names for both OpenAI and Azure OpenAI services. It provides a template for setting up the necessary environment variables to connect to these endpoints. ```ini # For OpenAI OPENAI_MODEL=... OPENAI_API_KEY=... # For Azure OpenAI AZURE_OPENAI_ENDPOINT=... AZURE_OPENAI_API_KEY=... ``` -------------------------------- ### Configure Azure OpenAI Environment Variables Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/README.md Specifies the environment variables required to connect to Azure OpenAI services, including the endpoint URL and the API key for authentication. ```sh AZURE_OPENAI_ENDPOINT=... AZURE_OPENAI_API_KEY=... ``` -------------------------------- ### Define Translation and Example Retrieval Functions Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/calendar.ipynb Defines `get_translation`, an asynchronous function that uses the TypeChat translator to convert natural language messages into structured data, handling success and failure cases and formatting output as a Markdown table. It also defines `get_examples` to load sample prompts from a file for the UI. ```python import pandas async def get_translation(message, history): result = await translator.translate(message) if isinstance(result, Failure): return f"Translation Failed āŒ \n Context: {result.message}" else: result = result.value df = pandas.DataFrame.from_dict(result["actions"]) return f"Translation Succeeded! āœ…\n Table View \n ``` {df.fillna('').to_markdown(tablefmt='grid')} \n ``` \n" def get_examples(): example_prompts = [] with open('../examples/calendar/input.txt') as prompts_file: for line in prompts_file: example_prompts.append(line) return example_prompts ``` -------------------------------- ### Launch Gradio Chat Interface for Calendar Application Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/calendar.ipynb Initializes and launches a Gradio chat interface. It uses the `get_translation` function to process user inputs and `get_examples` to provide sample prompts, creating an interactive web application for the calendar translation feature. ```python import gradio as gr gr.ChatInterface(get_translation, title="šŸ“… Calendar", examples=get_examples()).launch() ``` -------------------------------- ### Install Local TypeChat Package Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/music.ipynb This command installs the local TypeChat package in editable mode, allowing the project to import modules from the parent directory. This is crucial for development and ensures that changes to the TypeChat library are immediately reflected without reinstallation. ```python %pip install -e ../ ``` -------------------------------- ### Import Core Modules and Configure Python Path Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/calendar.ipynb Imports standard Python modules like `json`, `setuptools`, `os`, and `sys`. It also modifies the system path to include the parent directory, ensuring that TypeChat modules can be imported correctly. ```python import json import setuptools import os import sys module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path) ``` -------------------------------- ### Import TypeChat Components and Calendar Schema Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/calendar.ipynb Imports necessary classes and functions from the `dotenv` and `typechat` libraries, including `TypeChatJsonTranslator`, `TypeChatValidator`, and `create_language_model`. It also imports the specific `calendar` schema for the example application. ```python from dotenv import dotenv_values from typechat import Failure, TypeChatJsonTranslator, TypeChatValidator, create_language_model from examples.calendar import schema as calendar ``` -------------------------------- ### Define Translation and Example Retrieval Logic Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/music.ipynb This snippet defines two asynchronous functions: `get_translation` and `get_examples`. `get_translation` takes a user message, translates it using the TypeChat translator, handles success or failure, and executes the translated music actions. `get_examples` reads predefined prompts from a file to populate the Gradio interface with example inputs. ```python import pandas async def get_translation(message, history): result = await translator.translate(message) if isinstance(result, Failure): return f"Translation Failed āŒ \n Context: {result.message}" else: result = result.value df = pandas.DataFrame.from_dict(result["actions"]) try: for action in result["actions"]: await handle_call(action, player_context) return f"Translation Succeeded! āœ…\n Table View \n ``` {df.fillna('').to_markdown(tablefmt='grid')} \n ``` \n" except Exception as error: return f"An exception occurred: {error}" def get_examples(): example_prompts = [] with open('../examples/music/input.txt') as prompts_file: for line in prompts_file: example_prompts.append(line) return example_prompts ``` -------------------------------- ### Install TypeChat Library Source: https://github.com/microsoft/typechat/blob/main/site/src/blog/introducing-typechat.md Instructions to install the TypeChat library using npm, making it available for use in JavaScript and TypeScript projects. ```JavaScript npm install typechat ``` -------------------------------- ### Install Python Dependencies for TypeChat Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/sentiment.ipynb Installs or upgrades necessary Python packages like setuptools and gradio using pip, which are required for running the TypeChat examples and the Gradio UI. These commands are typically used in a Jupyter or IPython environment. ```python %pip install --upgrade setuptools %pip install --upgrade gradio ``` -------------------------------- ### Launch Gradio Chat Interface Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/music.ipynb This snippet initializes and launches a Gradio chat interface. It uses the `get_translation` function as the backend for processing user messages and populates the interface with example prompts from `get_examples`. This creates an interactive web UI for testing the TypeChat music command translation. ```python import gradio as gr gr.ChatInterface(get_translation, title="šŸŽµ Music", examples=get_examples()).launch() ``` -------------------------------- ### Launch Gradio Chat Interface for Math Example Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/math.ipynb This code imports the `gradio` library and uses it to create and launch a web-based chat interface. The interface is configured to use the `get_translation` function for processing user inputs, sets the title to '🧮 Math', and populates example prompts using the `get_examples` function. ```python import gradio as gr gr.ChatInterface(get_translation, title="🧮 Math", examples=get_examples()).launch() ``` -------------------------------- ### Import TypeChat and Music Example Modules Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/music.ipynb This snippet imports necessary classes and functions from the `dotenv` library for environment variables, and core TypeChat components like `TypeChatJsonTranslator`, `TypeChatValidator`, and `create_language_model`. It also imports the specific `music` schema and client-side utilities for the music example. ```python from dotenv import dotenv_values from typechat import Failure, TypeChatJsonTranslator, TypeChatValidator, create_language_model from examples.music import schema as music from examples.music.client import handle_call, get_client_context ``` -------------------------------- ### Initialize TypeChat Language Model and Translator Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/calendar.ipynb Initializes the TypeChat language model using environment variables, creates a validator based on the `CalendarActions` schema, and instantiates a JSON translator with the model and validator. This setup prepares the core components for natural language to structured data translation. ```python model = create_language_model(dotenv_values()) validator = TypeChatValidator(calendar.CalendarActions) translator = TypeChatJsonTranslator(model, validator, calendar.CalendarActions) ``` -------------------------------- ### Azure OpenAI API Environment Variables Source: https://github.com/microsoft/typechat/blob/main/site/src/docs/examples.md This section details the environment variables needed to connect TypeChat examples to an Azure OpenAI endpoint. It includes the full REST API URL and the Azure OpenAI API key. ```APIDOC AZURE_OPENAI_ENDPOINT: The full URL of the Azure OpenAI REST API (e.g. `https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/chat/completions?api-version=2023-05-15`) AZURE_OPENAI_API_KEY: Your Azure OpenAI API key ``` -------------------------------- ### Import TypeChat Components for Math Example Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/math.ipynb This snippet imports specific components from the `dotenv` library to load environment variables, and crucial classes and functions from the `typechat` library and its `math` example. These imports are essential for setting up the language model, translator, and validator for mathematical operations. ```python from dotenv import dotenv_values from typechat import Failure, create_language_model from examples.math.program import TypeChatProgramTranslator, TypeChatProgramValidator, evaluate_json_program from examples.math import schema as math ``` -------------------------------- ### Install TypeChat Python Library from GitHub Source: https://github.com/microsoft/typechat/blob/main/python/README.md Instructions to install the TypeChat Python library directly from its GitHub repository using pip. This is the recommended installation method as TypeChat is not yet published to PyPI. ```sh pip install "typechat @ git+https://github.com/microsoft/TypeChat#subdirectory=python" ``` -------------------------------- ### OpenAI API Environment Variables Source: https://github.com/microsoft/typechat/blob/main/site/src/docs/examples.md This section outlines the environment variables required to configure TypeChat examples for use with an OpenAI endpoint. It specifies the necessary variables for the OpenAI model name and the corresponding API key. ```APIDOC OPENAI_MODEL: The OpenAI model name (e.g. `gpt-3.5-turbo` or `gpt-4`) OPENAI_API_KEY: Your OpenAI API key ``` -------------------------------- ### Import Core Python Modules and Adjust Path Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/math.ipynb This code imports standard Python modules like `json`, `setuptools`, `os`, and `sys`. It also modifies the system path to include the parent directory, ensuring that local modules (like `typechat` or `examples`) can be imported correctly. ```python import json import setuptools import os import sys module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path) ``` -------------------------------- ### Install Required Python Packages Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/restaurant.ipynb This snippet installs or upgrades the necessary Python packages, `setuptools` and `gradio`, which are essential for running the TypeChat application and its web interface. ```python %pip install --upgrade setuptools %pip install --upgrade gradio ``` -------------------------------- ### Natural Language to Spotify API Plan and Code Generation Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/music/README.md This snippet illustrates the core functionality of the TypeChat Music example: converting a natural language command into a structured JSON plan for Spotify API interaction, and subsequently generating the corresponding TypeScript code to execute that plan. It demonstrates how user intent is transformed into an executable dataflow program. ```JSON { "@steps": [ { "@func": "searchTracks", "@args": [ "shake it off taylor swift" ] }, { "@func": "play", "@args": [ { "@ref": 0 } ] } ] } ``` ```TypeScript import { API } from "./schema"; function program(api: API) { const step1 = api.searchTracks("shake it off taylor swift"); return api.play(step1); } ``` -------------------------------- ### Example JSON Output for Coffee Order Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/coffeeShop-zod/README.md This JSON snippet illustrates the structured output generated from a natural language coffee order. It details the ordered items, including product type, name, quantity, and any specified options like sweeteners. ```json { "items": [ { "type": "lineitem", "product": { "type": "LatteDrinks", "name": "cappuccino", "options": [ { "type": "Sweeteners", "name": "sugar", "optionQuantity": "regular" } ] }, "quantity": 1 } ] } ``` -------------------------------- ### Launch Gradio Chat Interface Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/coffeeShop.ipynb This final snippet sets up and launches the Gradio chat interface. It utilizes the `get_translation` function as the backend for processing user input and `get_examples` to populate the interface with sample prompts. The interface is titled 'ā˜• Coffee' and is launched, making the application accessible. ```Python import setuptools import gradio as gr gr.ChatInterface(get_translation, title="ā˜• Coffee", examples=get_examples()).launch() ``` -------------------------------- ### Install TypeChat Library via npm Source: https://github.com/microsoft/typechat/blob/main/site/src/blog/announcing-typechat-0-1-0.md This command demonstrates how to install the TypeChat library using npm, the Node.js package manager. It's the first step to integrate TypeChat into a project. ```sh npm install typechat ``` -------------------------------- ### Guiding JSON Generation with TypeScript Types Source: https://github.com/microsoft/typechat/blob/main/site/src/docs/introduction.md This advanced example demonstrates how to prompt a language model to generate JSON that strictly conforms to a provided TypeScript interface. This approach leverages type definitions to ensure robust and predictable data structures from natural language models, forming the core idea behind TypeChat. ```User Prompt Provide 3 suggestions for specific places to go to in Seattle on a rainy day. Respond strictly with JSON. The JSON should be compatible with the TypeScript type `Response` from the following: ``` ```ts interface Response { data: Array<{ venue: string, description: string }>; } ``` ```json { "data": [ { "venue": "Museum of Pop Culture", "description": "Explore the fascinating world of popular culture through interactive exhibits, music memorabilia, and multimedia displays at the Museum of Pop Culture." }, { "venue": "Seattle Art Museum", "description": "Indulge in the diverse collection of artworks from around the world at the Seattle Art Museum, featuring both contemporary and classical pieces." }, { "venue": "Pike Place Market", "description": "Enjoy the vibrant atmosphere of Pike Place Market, where you can wander through covered stalls offering fresh produce, crafts, and delicious food from local vendors." } ] } ``` -------------------------------- ### Define Translation Logic and Example Prompts Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/coffeeShop.ipynb This snippet defines the asynchronous `get_translation` function, which uses the `TypeChatJsonTranslator` to process user messages. It handles both successful translations, displaying the results as a formatted Pandas DataFrame, and failures, returning an error message. Additionally, the `get_examples` function is included to load predefined example prompts from a file for the Gradio interface. ```Python import pandas async def get_translation(message, history): result = await translator.translate(message) if isinstance(result, Failure): return f"Translation Failed āŒ \n Context: {result.message}" else: result = result.value df = pandas.DataFrame.from_dict(result["items"]) #return f"Translation Succeeded! āœ…\n JSON View \n ``` {json.dumps(result, indent=2)} \n ``` \n" return f"Translation Succeeded! āœ…\n Coffee Shop Items \n ``` {df.fillna('').to_markdown(tablefmt='grid')} \n ``` \n" def get_examples(): example_prompts = [] with open('../examples/coffeeShop/input.txt') as prompts_file: for line in prompts_file: example_prompts.append(line) return example_prompts ``` -------------------------------- ### Define Translation and Example Retrieval Functions Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/restaurant.ipynb This snippet defines two key functions: `get_translation` and `get_examples`. `get_translation` asynchronously translates a user message using the initialized TypeChat translator, handling both success and failure cases, and formats the output using pandas. `get_examples` reads example prompts from a file to populate the Gradio interface. ```python import pandas async def get_translation(message, history): result = await translator.translate(message) if isinstance(result, Failure): return f"Translation Failed āŒ \n Context: {result.message}" else: result = result.value df = pandas.DataFrame.from_dict(result["items"]) return f"Translation Succeeded! āœ…\n Restaurant orders \n ``` {df.fillna('').to_markdown(tablefmt='grid')} \n ``` \n" def get_examples(): example_prompts = [] with open('../examples/restaurant/input.txt') as prompts_file: for line in prompts_file: example_prompts.append(line) return example_prompts ``` -------------------------------- ### Define Math Operation Handler and Translation Logic Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/math.ipynb This snippet defines three key functions: `handleCall` which executes the mathematical operations parsed by TypeChat, `get_translation` which orchestrates the translation of user messages into a program, evaluates it, and formats the output, and `get_examples` which loads example prompts from a file. It also imports `pandas` for data formatting. ```python import pandas async def handleCall(func:str, args: list[int|float]) -> int|float: print(f"{func}({json.dumps(args)}) ") match func: case "add": return args[0] + args[1] case "sub": return args[0] - args[1] case "mul": return args[0] * args[1] case "div": return args[0] / args[1] case "neg": return -1 * args[0] case "id": return args[0] case _: raise ValueError(f'Unexpected function name {func}') async def get_translation(message, history): result = await translator.translate(message) if isinstance(result, Failure): return f"Translation Failed āŒ \n Context: {result.message}" else: result = result.value math_result = await evaluate_json_program(result, handleCall) df = pandas.DataFrame.from_dict(result["@steps"]) return f"Translation Succeeded! āœ…\n Here is a table of operations needed to get the answer \n ``` {df.fillna('').to_markdown(tablefmt='grid')} \n ``` \n Math Result: {math_result}" def get_examples(): example_prompts = [] with open('../examples/math/input.txt') as prompts_file: for line in prompts_file: example_prompts.append(line) return example_prompts ``` -------------------------------- ### Example JSON Output for Coffee Order Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/coffeeShop/README.md This JSON snippet illustrates the structured representation of a user's natural language coffee order. It shows how a 'cappuccino with a pack of sugar' is parsed into a `lineitem` with product details, options, and quantity, conforming to the `Cart` schema. ```json { "items": [ { "type": "lineitem", "product": { "type": "LatteDrinks", "name": "cappuccino", "options": [ { "type": "Sweeteners", "name": "sugar", "optionQuantity": "regular" } ] }, "quantity": 1 } ] } ``` -------------------------------- ### Set Up TypeChat for Local Development Source: https://github.com/microsoft/typechat/blob/main/python/README.md Steps to clone the TypeChat repository and prepare the Python and Node.js development environments for contributing to the project. This setup requires Python >=3.11, hatch, and Node.js >=20. ```sh git clone https://github.com/microsoft/TypeChat cd TypeChat/python hatch shell npm ci ``` -------------------------------- ### Example Crossword Prompt and Output Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/crossword/README.md This snippet illustrates a user's input prompt to the Crossword application and the AI model's generated response, demonstrating the system's ability to extract specific information (a crossword clue) from a multimodal context. ```Prompt šŸ> What is the clue for 61 across ``` ```Plaintext "Monogram in French fashion" ``` -------------------------------- ### Record Flu Episode and Sudafed Usage Source: https://github.com/microsoft/typechat/blob/main/python/examples/healthData/input.txt Example conversation to record a past flu episode, its start date and duration, and the subsequent use of Sudafed medication, including dosage and frequency. ```Conversational I got the flu Started 2 weeks ago Its gone now. Only lasted about a week I took some sudafed though I took 2 sudafed twice a day. Regular strength ``` -------------------------------- ### Import Core Libraries and TypeChat Components Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/coffeeShop.ipynb This code imports essential Python libraries like `json` and `sys`, along with `dotenv` for environment variable management. It also sets up the module path to access `typechat` components and imports specific modules from the `coffeeShop` example, including `schema`, `Failure`, `TypeChatJsonTranslator`, `TypeChatValidator`, and `create_language_model`. ```Python import json import sys from dotenv import dotenv_values import os import sys module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path) from examples.coffeeShop import schema as coffeeshop from typechat import Failure, TypeChatJsonTranslator, TypeChatValidator, create_language_model ``` -------------------------------- ### Example User Input for Calendar Event Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/calendar/README.md A natural language prompt provided by the user to describe an event they wish to add to their calendar. ```text šŸ“…> I need to get my tires changed from 12:00 to 2:00 pm on Friday March 15, 2024 ``` -------------------------------- ### Record Shingles and Broken Foot History Source: https://github.com/microsoft/typechat/blob/main/python/examples/healthData/input.txt Example conversation to record past medical conditions like shingles, including its start date and duration, and a broken foot, specifying the year it occurred and recovery time. ```Conversational i want to record my shingles August 2016 It lasted 3 months I also broke my foot I broke it in high school 2001 The foot took a year to be ok ``` -------------------------------- ### Example User Input and Language Model Output for Food Order Source: https://github.com/microsoft/typechat/blob/main/python/examples/restaurant/README.md This snippet presents a complex natural language input for a food order and the corresponding structured output generated by a language model (specifically GPT-4-0613). It demonstrates the model's capability to interpret intricate requests and produce a concise, itemized summary of the order. ```Input Text šŸ•> I want three pizzas, one with mushrooms and the other two with sausage. Make one sausage a small. And give me a whole Greek and a Pale Ale. And give me a Mack and Jacks. ``` ```Output Text 1 large pizza with mushrooms 1 large pizza with sausage 1 small pizza with sausage 1 whole Greek salad 1 Pale Ale 1 Mack and Jacks ``` -------------------------------- ### Example User Input and Model Output for Restaurant Order Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/restaurant/README.md Demonstrates a complex natural language input for a food order and the expected structured output from a language model (GPT-4-0613). This highlights the model's ability to parse compound sentences and corrections. ```text šŸ•> I want three pizzas, one with mushrooms and the other two with sausage. Make one sausage a small. And give me a whole Greek and a Pale Ale. And give me a Mack and Jacks. ``` ```text 1 large pizza with mushrooms 1 large pizza with sausage 1 small pizza with sausage 1 whole Greek salad 1 Pale Ale 1 Mack and Jacks ``` -------------------------------- ### Install Required Python Packages Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/healthData.ipynb This snippet demonstrates how to install or upgrade the `setuptools` and `gradio` Python packages using pip, which are essential dependencies for the application's functionality and user interface. ```Python %pip install --upgrade setuptools %pip install --upgrade gradio ``` -------------------------------- ### Initialize TypeChat Model and Translator Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/music.ipynb This snippet initializes the TypeChat language model, validator, and JSON translator using environment variables. It sets up the `TypeChatValidator` with the `music.PlayerActions` schema and creates a `TypeChatJsonTranslator` to convert natural language into structured music actions. It also retrieves the client context for music playback. ```python env_vals = dotenv_values() model = create_language_model(env_vals) validator = TypeChatValidator(music.PlayerActions) translator = TypeChatJsonTranslator(model, validator, music.PlayerActions) player_context = await get_client_context(env_vals) ``` -------------------------------- ### Incorrect Model Output Example (GPT-3.5-turbo) Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/restaurant/README.md Illustrates a common error where GPT-3.5-turbo incorrectly interprets the user's intent, leading to an incorrect quantity of items. This highlights the probabilistic nature of language models and the need for user confirmation. ```diff 1 large pizza with mushrooms - 1 large pizza with sausage + 2 large pizza with sausage 1 small pizza with sausage 1 whole Greek salad 1 Pale Ale 1 Mack and Jacks ``` -------------------------------- ### Install TypeChat for TypeScript/JavaScript Source: https://github.com/microsoft/typechat/blob/main/README.md This command installs the TypeChat library using npm, the package manager for Node.js. It is a prerequisite for using TypeChat in TypeScript or JavaScript development environments. ```Shell npm install typechat ``` -------------------------------- ### Initialize TypeChat Translator with Health Data Instructions Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/healthData.ipynb This code block defines a set of instructions for the AI agent to guide its interaction regarding health data entry. It then loads environment variables, initializes a language model, creates a `TypeChatValidator` for the `HealthDataResponse` schema, and finally instantiates a `TranslatorWithHistory` with the model, validator, schema, and the defined instructions. This setup prepares the system for interactive health data translation. ```Python health_instructions = """ Help me enter my health data step by step. Ask specific questions to gather required and optional fields I have not already providedStop asking if I don't know the answer Automatically fix my spelling mistakes My health data may be complex: always record and return ALL of it. Always return a response: - If you don't understand what I say, ask a question. - At least respond with an OK message. """ env_vals = dotenv_values() model = create_language_model(env_vals) validator = TypeChatValidator(health.HealthDataResponse) translator = TranslatorWithHistory(model, validator, health.HealthDataResponse, additional_agent_instructions=health_instructions) ``` -------------------------------- ### TypeChat Generated Math Program Example Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/math/README.md This TypeScript code snippet represents a program generated by TypeChat from a natural language prompt. It demonstrates how TypeChat translates a complex mathematical instruction into a sequence of API calls, using an `API` schema to perform multiplication and addition operations. ```TypeScript 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); } ``` -------------------------------- ### Initialize TypeChat Language Model and Translator Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/math.ipynb This code initializes the TypeChat components. It loads environment variables, creates a language model instance using those variables, instantiates a `TypeChatProgramValidator`, and finally sets up a `TypeChatProgramTranslator` with the model, validator, and the `MathAPI` schema for mathematical operations. ```python env_vals = dotenv_values() model = create_language_model(env_vals) validator = TypeChatProgramValidator() translator = TypeChatProgramTranslator(model, validator, math.MathAPI) ``` -------------------------------- ### Example of Incorrect Language Model Output (GPT-3.5-turbo) Diff Source: https://github.com/microsoft/typechat/blob/main/python/examples/restaurant/README.md This snippet illustrates an incorrect inference from GPT-3.5-turbo, showing how it misinterprets the pizza count in a complex order. The diff format highlights the discrepancy between the expected and actual output, underscoring the probabilistic nature of language models and the necessity for user confirmation mechanisms. ```Diff 1 large pizza with mushrooms - 1 large pizza with sausage + 2 large pizza with sausage 1 small pizza with sausage 1 whole Greek salad 1 Pale Ale 1 Mack and Jacks ``` -------------------------------- ### Initialize TypeChat Model and Translator Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/coffeeShop.ipynb This snippet initializes the core components for the TypeChat application. It loads environment variables, creates a language model using `create_language_model`, instantiates a `TypeChatValidator` with the `coffeeshop.Cart` schema, and finally creates a `TypeChatJsonTranslator` to handle the translation process. ```Python env_vals = dotenv_values() model = create_language_model(env_vals) validator = TypeChatValidator(coffeeshop.Cart) translator = TypeChatJsonTranslator(model, validator, coffeeshop.Cart) ``` -------------------------------- ### LLM Prompt for Basic JSON Translation Source: https://github.com/microsoft/typechat/blob/main/site/src/blog/introducing-typechat.md An example of a user prompt instructing a Large Language Model to translate a natural language request into a specific JSON format, including a sample JSON structure for guidance. ```JSON { "items": [ { "name": "croissant", "quantity": 2 }, { "name": "latte", "quantity": 1, "size": "tall" } ] } ``` -------------------------------- ### Build TypeChat from source Source: https://github.com/microsoft/typechat/blob/main/typescript/README.md Steps to clone the TypeChat repository from GitHub, navigate to the TypeScript directory, install its dependencies, and build the project from its source code. This is useful for development or contributing to the project. ```sh git clone https://github.com/microsoft/TypeChat cd TypeChat/typescript npm install npm run build ``` -------------------------------- ### Natural Language Input to Spotify API JSON Output Source: https://github.com/microsoft/typechat/blob/main/python/examples/music/README.md This snippet illustrates how a natural language command to play a song is processed into a structured JSON object, ready to be executed against the Spotify API. It shows the transformation of user intent into a machine-readable format. ```Natural Language šŸŽµ> play shake it off by taylor swift ``` ```JSON { "actions": [ { "actionName": "play", "parameters": { "artist": "taylor swift", "trackName": "shake it off", "quantity": 0 } } ] } ``` -------------------------------- ### Configure Python Module Path Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/music.ipynb This snippet configures the Python system path to include the parent directory, enabling the import of modules from the TypeChat library. It's a common practice in projects with a specific directory structure to ensure all necessary modules are discoverable. ```python import json import setuptools import os import sys module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path) ``` -------------------------------- ### Define Translation Logic and Example Prompt Loader Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/healthData.ipynb This snippet defines `get_translation`, an asynchronous function that takes a user message and history, uses the `translator` to process it, and formats the output including any translated health data (as a Pandas DataFrame), agent messages, or untranslated parts. It also includes `get_examples`, a utility function to read example prompts from a file, which can be used to pre-populate a UI. ```Python import pandas async def get_translation(message, history): result = await translator.translate(message) if isinstance(result, Failure): return f"Translation Failed āŒ \n Context: {result.message}" else: result = result.value output = f"Translation Succeeded! āœ…\n" data = result.get("data", None) if data: df = pandas.DataFrame.from_dict(data) output += f"HealthData \n ``` {df.fillna('').to_markdown(tablefmt='grid')} \n ``` \n" message = result.get("message", None) not_translated = result.get("notTranslated", None) if message: output += f"\nšŸ“: {message}" if not_translated: output += f"\nšŸ¤”: I did not understand\n {not_translated}" return output def get_examples(): example_prompts = [] with open('../examples/healthData/input.txt') as prompts_file: for line in prompts_file: example_prompts.append(line) return example_prompts ``` -------------------------------- ### Health Data Agent User Input Example Source: https://github.com/microsoft/typechat/blob/main/python/examples/healthData/README.md This snippet illustrates a sample user input provided to the Health Data Agent. It demonstrates how a user might interact with the agent to convey health-related information, such as current medications. ```console 🤧> I am taking klaritin for my allergies ``` -------------------------------- ### Example Natural Language Input for Calendar Event Source: https://github.com/microsoft/typechat/blob/main/python/examples/calendar/README.md Demonstrates a natural language prompt used as input to the Calendar application to describe an event for scheduling. ```Plaintext šŸ“…> I need to get my tires changed from 12:00 to 2:00 pm on Friday March 15, 2024 ``` -------------------------------- ### Multiple Actions: Sequential Event Additions Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/calendar/src/expectedOutput.txt Demonstrates how a series of sequential events mentioned in natural language are translated into multiple 'add event' actions, with inferred start times based on previous events and durations. ```json { "actions": [ { "actionType": "add event", "event": { "day": "today", "timeRange": { "startTime": "2:00 pm", "duration": "1 hour" }, "description": "meeting with Jenny", "participants": [ "Jenny" ] } }, { "actionType": "add event", "event": { "day": "today", "timeRange": { "startTime": "3:30 pm", "duration": "1 hour" }, "description": "dry cleaner" } }, { "actionType": "add event", "event": { "day": "today", "timeRange": { "startTime": "4:30 pm" ``` -------------------------------- ### Add Event: Appointment with Duration Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/calendar/src/expectedOutput.txt Shows how to add an appointment with a specified start time and duration, including a participant's name in the description. ```json { "actions": [ { "actionType": "add event", "event": { "day": "today", "timeRange": { "startTime": "9 am", "duration": "2 hours" }, "description": "appointment with Jerri Skinner" } } ] } ``` -------------------------------- ### Launch Gradio Chat Interface for Restaurant Orders Source: https://github.com/microsoft/typechat/blob/main/python/notebooks/restaurant.ipynb This code initializes and launches a Gradio chat interface. It uses the `get_translation` function as the backend for processing user inputs and populates example prompts using `get_examples`, providing a user-friendly web interface for the restaurant order translation system. ```python import gradio as gr gr.ChatInterface(get_translation, title="šŸ• Restaurant", examples=get_examples()).launch() ``` -------------------------------- ### Record Klaritin Medication (Attempt 1) Source: https://github.com/microsoft/typechat/blob/main/python/examples/healthData/input.txt Example conversation for recording Klaritin medication, including initial dosage and frequency, followed by a correction to the tablet count and strength. ```Conversational klaritin 2 tablets 3 times a day 300 mg actually that is 1 tablet ``` -------------------------------- ### Add Event: Schedule Party Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/calendar/src/expectedOutput.txt Shows the structured JSON for adding a new event with a specific name, day, and start time. ```json { "actions": [ { "actionType": "add event", "event": { "day": "friday", "timeRange": { "startTime": "6pm" }, "description": "Jeffs pizza party" } } ] } ``` -------------------------------- ### Record Klaritin Medication (Attempt 2) Source: https://github.com/microsoft/typechat/blob/main/python/examples/healthData/input.txt Another example conversation for recording Klaritin medication, demonstrating a different dosage and frequency, with a subsequent correction to the tablet count and strength. ```Conversational klaritin 1 pill, morning and before bedtime Can't remember Actually, that is 3 tablets 500 mg ``` -------------------------------- ### Add Event: Team Meeting Today Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/calendar/src/expectedOutput.txt A simple example of adding a meeting with a team for the current day at a specified time, with a default duration. ```json { "actions": [ { "actionType": "add event", "event": { "day": "today", "timeRange": { "startTime": "2:00", "duration": "1 hour" }, "description": "meeting with team", "participants": [ "team" ] } } ] } ``` -------------------------------- ### TypeScript printOrder Function Signature Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/restaurant/README.md Shows the signature of the `printOrder` function in `main.ts`, which summarizes the food order. This function operates on a strongly typed `Order` object, ensuring that the data has been validated by the TypeChat process. ```typescript function printOrder(order: Order) { ``` -------------------------------- ### Coffee Order Natural Language Input and JSON Output Transformation Source: https://github.com/microsoft/typechat/blob/main/python/examples/coffeeShop/README.md Illustrates the process of converting a natural language coffee order into a structured JSON object. The input shows a user's request, and the output displays the parsed 'Cart' structure, including line items, products, and options, demonstrating TypeChat's intent capture capabilities. ```Natural Language ā˜•> we'd like a cappuccino with a pack of sugar ``` ```JSON { "items": [ { "type": "lineitem", "product": { "type": "LatteDrinks", "name": "cappuccino", "options": [ { "type": "Sweeteners", "name": "sugar", "optionQuantity": "regular" } ] }, "quantity": 1 } ] } ``` -------------------------------- ### Multiple Actions: Add Event and Add Participants Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/calendar/src/expectedOutput.txt This example shows how two distinct actions, adding a new event and adding participants to another existing event, are represented in a single structured JSON output. ```json { "actions": [ { "actionType": "add event", "event": { "day": "Friday", "timeRange": { "startTime": "12pm", "duration": "1h" }, "description": "lunch with Luis", "participants": [ "Luis" ] } }, { "actionType": "add participants", "eventReference": { "day": "Wednesday", "timeRange": { "startTime": "4pm", "duration": "1h" }, "description": "ping pong game" }, "participants": [ "Isobel" ] } ] } ``` -------------------------------- ### Record Robotussin Medication Source: https://github.com/microsoft/typechat/blob/main/python/examples/healthData/input.txt Example conversation for recording Robotussin with Codeine, including dosage and frequency, and handling a scenario where the strength is unknown. ```Conversational Robotussin 1 cup Daily, as needed Robotussin with Codeine Put down strength as I don't know ``` -------------------------------- ### JSON Output for Adding Calendar Event Source: https://github.com/microsoft/typechat/blob/main/typescript/examples/calendar/README.md The structured JSON output representing the captured user intent to add a calendar event, including event details like description, date, and time range, based on the natural language input. ```json { "actions": [ { "actionType": "add event", "event": { "day": "Friday March 15, 2024", "timeRange": { "startTime": "12:00 pm", "endTime": "2:00 pm" }, "description": "get my tires changed" } } ] } ``` -------------------------------- ### Record Melatonin Medication Source: https://github.com/microsoft/typechat/blob/main/python/examples/healthData/input.txt Example conversation for recording Melatonin medication, specifying the exact dosage and frequency of use. ```Conversational Hey Melatonin 1 3mg tablet every night ``` -------------------------------- ### Generating JSON with a Provided Template Source: https://github.com/microsoft/typechat/blob/main/site/src/docs/introduction.md This example shows how to instruct a language model to generate a JSON response by providing an explicit JSON template. This method significantly improves the structure and parseability of the model's output for programmatic use. ```User Prompt Provide 3 suggestions for specific places to go to in Seattle on a rainy day. Respond in the form of JSON. The JSON should have the following format ```json [ { "venue": "...", "description": "..." }, { "venue": "...", "description": "..." } ] ``` ``` ```json [ { "venue": "Seattle Art Museum", "description": "The Seattle Art Museum (SAM) is a world-class museum with a diverse collection of art from around the globe. It offers a great indoor activity for a rainy day, allowing you to explore various art exhibitions and displays, including contemporary art, African and Oceanic art, and European painting and sculpture." }, { "venue": "Chihuly Garden and Glass", "description": "Chihuly Garden and Glass is an extraordinary exhibition showcasing the breathtaking glass artwork of Dale Chihuly. Located at the Seattle Center, this indoor attraction offers a mesmerizing experience as you wander through vibrant glass sculptures and installations. The beautiful interplay of light and color will captivate your senses, making it a perfect rainy day destination." }, { "venue": "Museum of Pop Culture", "description": "The Museum of Pop Culture (MoPOP) is a vibrant museum dedicated to contemporary pop culture, music, science fiction, and more. It features engaging exhibits that celebrate music icons, explore science fiction themes, and delve into the world of video games. Whether you're a fan of music, movies, or pop culture in general, MoPOP offers an immersive and entertaining experience, making it an ideal choice on a rainy day." } ] ``` -------------------------------- ### Record Benadryl Usage and Allergies Source: https://github.com/microsoft/typechat/blob/main/python/examples/healthData/input.txt Example conversation to record current medication (Benadryl) specifying its usage frequency and strength, and also to record an allergy (pollen). ```Conversational I am taking binadryl now As needed. Groceery store strength That is all I have I also got allergies. Pollen ``` -------------------------------- ### TypeScript Function to Print Validated Food Order Summary Source: https://github.com/microsoft/typechat/blob/main/python/examples/restaurant/README.md The `printOrder` function, located in `main.ts`, is responsible for summarizing a food order without relying on a language model. It operates on a strongly typed `Order` object, which is guaranteed to be valid due to the TypeChat validation process. This approach simplifies the generation of a succinct and accurate summary suitable for user confirmation. ```typescript function printOrder(order: Order) { ``` -------------------------------- ### Define In-Memory Schema using Zod Source: https://github.com/microsoft/typechat/blob/main/site/src/docs/typescript/basic-usage.md This example shows an alternative method for defining the `SentimentResponse` schema using the Zod library. This allows for in-memory schema creation, eliminating the need to load a physical `.ts` file. It also exports a `SentimentSchema` object containing the Zod definition. ```ts import { z } from "zod"; export const SentimentResponse = z.object({ sentiment: z.enum(["negative", "neutral", "positive"]).describe("The sentiment of the text") }); export const SentimentSchema = { SentimentResponse }; ```