chatlab


Namechatlab JSON
Version 2.1.0 PyPI version JSON
download
home_pagehttps://github.com/rgbkrk/chatlab
SummaryChat Plugin Experiments, Simplified. Give all the power to the models in your life.
upload_time2024-03-04 23:04:53
maintainer
docs_urlNone
authorKyle Kelley
requires_python>=3.10,<4.0
licenseBSD-3-Clause
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # ChatLab

**Chat Experiments, Simplified**

💬🔬

ChatLab is a Python package that makes it easy to experiment with OpenAI's chat models. It provides a simple interface for chatting with the models and a way to register functions that can be called from the chat model.

Best yet, it's interactive in the notebook!

## Notebooks to get started with

* [Learning the Basics](./notebooks/basics.ipynb)
* [Recommend and Visualize Color Palettes](./notebooks/color-picker.ipynb)
* [Introduction to the Function Registry](./notebooks/function-registry.ipynb)
* [Creating Knowledge Graphs with Pydantic](./notebooks/knowledge-graph.ipynb)
* [Direct Parallel Function Calling](./notebooks/parallel-function-calling.ipynb)
* [Let the Model do some Data Science](./notebooks/the-data-science-helper.ipynb)


## Introduction

```python
import chatlab
import random

def flip_a_coin():
    '''Returns heads or tails'''
    return random.choice(['heads', 'tails'])

chat = chatlab.Chat()
chat.register(flip_a_coin)

await chat("Please flip a coin for me")
```

<details style="background:#DDE6ED;color:#27374D;padding:.5rem 1rem;borderRadius:5px">
<summary>&nbsp;𝑓&nbsp; Ran `flip_a_coin`
</summary>
<br />

Input:

```json
{}
```

Output:

```json
"tails"
```

</details>

```markdown
It landed on tails!
```

In the notebook, text will stream into a Markdown output and function inputs and outputs are a nice collapsible display, like with ChatGPT Plugins.

TODO: Include GIF/mp4 of this in action

### Installation

```bash
pip install chatlab
```

### Configuration

You'll need to set your `OPENAI_API_KEY` environment variable. You can find your API key on your [OpenAI account page](https://platform.openai.com/account/api-keys). I recommend setting it in an `.env` file when working locally.

On hosted notebook environments, set it in your Secrets to keep it safe from prying LLM eyes.

## What can `Chat`s enable _you_ to do?

💬

Where `Chat`s take it next level is with _Chat Functions_. You can

-   declare a function
-   register the function in your `Chat`
-   watch as Chat Models call your functions!

You may recall this kind of behavior from ChatGPT Plugins. Now, you can take this even further with your own custom code.

As an example, let's give the large language models the ability to tell time.

```python
from datetime import datetime
from pytz import timezone, all_timezones, utc
from typing import Optional
from pydantic import BaseModel

def what_time(tz: Optional[str] = None):
    '''Current time, defaulting to UTC'''
    if tz is None:
        pass
    elif tz in all_timezones:
        tz = timezone(tz)
    else:
        return 'Invalid timezone'

    return datetime.now(tz).strftime('%I:%M %p')

class WhatTime(BaseModel):
    tz: Optional[str] = None
```

Let's break this down.

`what_time` is the function we're going to provide access to. Its docstring forms the `description` for the model while the schema comes from the pydantic `BaseModel` called `WhatTime`.

```python
import chatlab

chat = chatlab.Chat()

# Register our function
chat.register(what_time, WhatTime)
```

After that, we can call `chat` with direct strings (which are turned into user messages) or using simple message makers from `chatlab` named `user` and `system`.

```python
await chat("What time is it?")
```

<details style="background:#DDE6ED;color:#27374D;padding:.5rem 1rem;borderRadius:5px">
<summary>&nbsp;𝑓&nbsp; Ran `what_time`
</summary>
<br />

Input:

```json
{}
```

Output:

```json
"11:19 AM"
```

</details>

```markdown
The current time is 11:19 AM.
```

## Interface

The `chatlab` package exports

### `Chat`

The `Chat` class is the main way to chat using OpenAI's models. It keeps a history of your chat in `Chat.messages`.

#### `Chat.submit`

`submit` is how you send all the currently built up messages over to OpenAI. Markdown output will display responses from the `assistant`.

```python
await chat.submit('What would a parent who says "I have to play zone defense" mean? ')
# Markdown response inline
chat.messages
```

```js
[{'role': 'user',
  'content': 'What does a parent of three kids mean by "I have to play zone defense"?'},
 {'role': 'assistant',
  'content': 'When a parent of three kids says "I have to play zone defense," it means that they...
```

#### `Chat.register`

You can register functions with `Chat.register` to make them available to the chat model. The function's docstring becomes the description of the function while the schema is derived from the `pydantic.BaseModel` passed in.

```python
from pydantic import BaseModel

class WhatTime(BaseModel):
    tz: Optional[str] = None

def what_time(tz: Optional[str] = None):
    '''Current time, defaulting to UTC'''
    if tz is None:
        pass
    elif tz in all_timezones:
        tz = timezone(tz)
    else:
        return 'Invalid timezone'

    return datetime.now(tz).strftime('%I:%M %p')

chat.register(what_time, WhatTime)
```

#### `Chat.messages`

The raw messages sent and received to OpenAI. If you hit a token limit, you can remove old messages from the list to make room for more.

```python
chat.messages = chat.messages[-100:]
```

### Messaging

#### `human`/`user`

These functions create a message from the user to the chat model.

```python
from chatlab import human

human("How are you?")
```

```json
{ "role": "user", "content": "How are you?" }
```

#### `narrate`/`system`

`system` messages, also called `narrate` in `chatlab`, allow you to steer the model in a direction. You can use these to provide context without being seen by the user. One common use is to include it as initial context for the conversation.

```python
from chatlab import narrate

narrate("You are a large bird")
```

```json
{ "role": "system", "content": "You are a large bird" }
```

## Development

This project uses poetry for dependency management. To get started, clone the repo and run

```bash
poetry install -E dev -E test
```

We use `ruff` and `mypy`.

## Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/rgbkrk/chatlab",
    "name": "chatlab",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.10,<4.0",
    "maintainer_email": "",
    "keywords": "",
    "author": "Kyle Kelley",
    "author_email": "rgbkrk@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/79/7a/13f95c7ea392cad1586a9348dad2b46598da82bbf7032943be794e835788/chatlab-2.1.0.tar.gz",
    "platform": null,
    "description": "# ChatLab\n\n**Chat Experiments, Simplified**\n\n\ud83d\udcac\ud83d\udd2c\n\nChatLab is a Python package that makes it easy to experiment with OpenAI's chat models. It provides a simple interface for chatting with the models and a way to register functions that can be called from the chat model.\n\nBest yet, it's interactive in the notebook!\n\n## Notebooks to get started with\n\n* [Learning the Basics](./notebooks/basics.ipynb)\n* [Recommend and Visualize Color Palettes](./notebooks/color-picker.ipynb)\n* [Introduction to the Function Registry](./notebooks/function-registry.ipynb)\n* [Creating Knowledge Graphs with Pydantic](./notebooks/knowledge-graph.ipynb)\n* [Direct Parallel Function Calling](./notebooks/parallel-function-calling.ipynb)\n* [Let the Model do some Data Science](./notebooks/the-data-science-helper.ipynb)\n\n\n## Introduction\n\n```python\nimport chatlab\nimport random\n\ndef flip_a_coin():\n    '''Returns heads or tails'''\n    return random.choice(['heads', 'tails'])\n\nchat = chatlab.Chat()\nchat.register(flip_a_coin)\n\nawait chat(\"Please flip a coin for me\")\n```\n\n<details style=\"background:#DDE6ED;color:#27374D;padding:.5rem 1rem;borderRadius:5px\">\n<summary>&nbsp;\ud835\udc53&nbsp; Ran `flip_a_coin`\n</summary>\n<br />\n\nInput:\n\n```json\n{}\n```\n\nOutput:\n\n```json\n\"tails\"\n```\n\n</details>\n\n```markdown\nIt landed on tails!\n```\n\nIn the notebook, text will stream into a Markdown output and function inputs and outputs are a nice collapsible display, like with ChatGPT Plugins.\n\nTODO: Include GIF/mp4 of this in action\n\n### Installation\n\n```bash\npip install chatlab\n```\n\n### Configuration\n\nYou'll need to set your `OPENAI_API_KEY` environment variable. You can find your API key on your [OpenAI account page](https://platform.openai.com/account/api-keys). I recommend setting it in an `.env` file when working locally.\n\nOn hosted notebook environments, set it in your Secrets to keep it safe from prying LLM eyes.\n\n## What can `Chat`s enable _you_ to do?\n\n\ud83d\udcac\n\nWhere `Chat`s take it next level is with _Chat Functions_. You can\n\n-   declare a function\n-   register the function in your `Chat`\n-   watch as Chat Models call your functions!\n\nYou may recall this kind of behavior from ChatGPT Plugins. Now, you can take this even further with your own custom code.\n\nAs an example, let's give the large language models the ability to tell time.\n\n```python\nfrom datetime import datetime\nfrom pytz import timezone, all_timezones, utc\nfrom typing import Optional\nfrom pydantic import BaseModel\n\ndef what_time(tz: Optional[str] = None):\n    '''Current time, defaulting to UTC'''\n    if tz is None:\n        pass\n    elif tz in all_timezones:\n        tz = timezone(tz)\n    else:\n        return 'Invalid timezone'\n\n    return datetime.now(tz).strftime('%I:%M %p')\n\nclass WhatTime(BaseModel):\n    tz: Optional[str] = None\n```\n\nLet's break this down.\n\n`what_time` is the function we're going to provide access to. Its docstring forms the `description` for the model while the schema comes from the pydantic `BaseModel` called `WhatTime`.\n\n```python\nimport chatlab\n\nchat = chatlab.Chat()\n\n# Register our function\nchat.register(what_time, WhatTime)\n```\n\nAfter that, we can call `chat` with direct strings (which are turned into user messages) or using simple message makers from `chatlab` named `user` and `system`.\n\n```python\nawait chat(\"What time is it?\")\n```\n\n<details style=\"background:#DDE6ED;color:#27374D;padding:.5rem 1rem;borderRadius:5px\">\n<summary>&nbsp;\ud835\udc53&nbsp; Ran `what_time`\n</summary>\n<br />\n\nInput:\n\n```json\n{}\n```\n\nOutput:\n\n```json\n\"11:19 AM\"\n```\n\n</details>\n\n```markdown\nThe current time is 11:19 AM.\n```\n\n## Interface\n\nThe `chatlab` package exports\n\n### `Chat`\n\nThe `Chat` class is the main way to chat using OpenAI's models. It keeps a history of your chat in `Chat.messages`.\n\n#### `Chat.submit`\n\n`submit` is how you send all the currently built up messages over to OpenAI. Markdown output will display responses from the `assistant`.\n\n```python\nawait chat.submit('What would a parent who says \"I have to play zone defense\" mean? ')\n# Markdown response inline\nchat.messages\n```\n\n```js\n[{'role': 'user',\n  'content': 'What does a parent of three kids mean by \"I have to play zone defense\"?'},\n {'role': 'assistant',\n  'content': 'When a parent of three kids says \"I have to play zone defense,\" it means that they...\n```\n\n#### `Chat.register`\n\nYou can register functions with `Chat.register` to make them available to the chat model. The function's docstring becomes the description of the function while the schema is derived from the `pydantic.BaseModel` passed in.\n\n```python\nfrom pydantic import BaseModel\n\nclass WhatTime(BaseModel):\n    tz: Optional[str] = None\n\ndef what_time(tz: Optional[str] = None):\n    '''Current time, defaulting to UTC'''\n    if tz is None:\n        pass\n    elif tz in all_timezones:\n        tz = timezone(tz)\n    else:\n        return 'Invalid timezone'\n\n    return datetime.now(tz).strftime('%I:%M %p')\n\nchat.register(what_time, WhatTime)\n```\n\n#### `Chat.messages`\n\nThe raw messages sent and received to OpenAI. If you hit a token limit, you can remove old messages from the list to make room for more.\n\n```python\nchat.messages = chat.messages[-100:]\n```\n\n### Messaging\n\n#### `human`/`user`\n\nThese functions create a message from the user to the chat model.\n\n```python\nfrom chatlab import human\n\nhuman(\"How are you?\")\n```\n\n```json\n{ \"role\": \"user\", \"content\": \"How are you?\" }\n```\n\n#### `narrate`/`system`\n\n`system` messages, also called `narrate` in `chatlab`, allow you to steer the model in a direction. You can use these to provide context without being seen by the user. One common use is to include it as initial context for the conversation.\n\n```python\nfrom chatlab import narrate\n\nnarrate(\"You are a large bird\")\n```\n\n```json\n{ \"role\": \"system\", \"content\": \"You are a large bird\" }\n```\n\n## Development\n\nThis project uses poetry for dependency management. To get started, clone the repo and run\n\n```bash\npoetry install -E dev -E test\n```\n\nWe use `ruff` and `mypy`.\n\n## Contributing\n\nPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.\n\n",
    "bugtrack_url": null,
    "license": "BSD-3-Clause",
    "summary": "Chat Plugin Experiments, Simplified. Give all the power to the models in your life.",
    "version": "2.1.0",
    "project_urls": {
        "Homepage": "https://github.com/rgbkrk/chatlab"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "dbe56a725c3f3b21900e76829fb960192998d73230814cb6f56f94e02c8806d9",
                "md5": "c97af14502d162e0fd9ed38c9b431d9e",
                "sha256": "9460bd2f2c8056efb13ed0b166740aae48efca4bdcb23d018eff02bc2d80faf8"
            },
            "downloads": -1,
            "filename": "chatlab-2.1.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "c97af14502d162e0fd9ed38c9b431d9e",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10,<4.0",
            "size": 29547,
            "upload_time": "2024-03-04T23:04:51",
            "upload_time_iso_8601": "2024-03-04T23:04:51.689904Z",
            "url": "https://files.pythonhosted.org/packages/db/e5/6a725c3f3b21900e76829fb960192998d73230814cb6f56f94e02c8806d9/chatlab-2.1.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "797a13f95c7ea392cad1586a9348dad2b46598da82bbf7032943be794e835788",
                "md5": "15f6159761c36910a3c95cd5e328c454",
                "sha256": "3a08d33d98cc4988d475b450b1bebfd2ec8a541327b93028cd4cee21a43ae01c"
            },
            "downloads": -1,
            "filename": "chatlab-2.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "15f6159761c36910a3c95cd5e328c454",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10,<4.0",
            "size": 32219,
            "upload_time": "2024-03-04T23:04:53",
            "upload_time_iso_8601": "2024-03-04T23:04:53.588258Z",
            "url": "https://files.pythonhosted.org/packages/79/7a/13f95c7ea392cad1586a9348dad2b46598da82bbf7032943be794e835788/chatlab-2.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-03-04 23:04:53",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "rgbkrk",
    "github_project": "chatlab",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "chatlab"
}
        
Elapsed time: 0.20220s