# simpleaichat
```py3
from simpleaichat import AIChat
ai = AIChat(system="Write a fancy GitHub README based on the user-provided project name.")
ai("simpleaichat")
```
simpleaichat is a Python package for easily interfacing with chat apps like ChatGPT and GPT-4 with robust features and minimal code complexity. This tool has many features optimized for working with ChatGPT as fast and as cheap as possible, but still much more capable of modern AI tricks than most implementations:
- Create and run chats with only a few lines of code!
- Optimized workflows which minimize the amount of tokens used, reducing costs and latency.
- Run multiple independent chats at once.
- Minimal codebase: no code dives to figure out what's going on under the hood needed!
- Chat streaming responses and the ability to use tools.
- Async support, including for streaming and tools.
- Ability to create more complex yet clear workflows if needed, such as Agents. (Demo soon!)
- Coming soon: more chat model support (PaLM, Claude)!
Here's some fun, hackable examples on how simpleaichat works:
- Creating a [Python coding assistant](examples/notebooks/simpleaichat_coding.ipynb) without any unnecessary accompanying output, allowing 5x faster generation at 1/3rd the cost. ([Colab](https://colab.research.google.com/github/minimaxir/simpleaichat/blob/main/examples/notebooks/simpleaichat_coding.ipynb))
- Allowing simpleaichat to [provide inline tips](examples/notebooks/chatgpt_inline_tips.ipynb) following ChatGPT usage guidelines. ([Colab](https://colab.research.google.com/github/minimaxir/simpleaichat/blob/main/examples/notebooks/chatgpt_inline_tips.ipynb))
- Async interface for [conducting many chats](examples/notebooks/simpleaichat_async.ipynb) in the time it takes to receive one AI message. ([Colab](https://colab.research.google.com/github/minimaxir/simpleaichat/blob/main/examples/notebooks/simpleaichat_async.ipynb))
- Create your own Tabletop RPG (TTRPG) setting and campaign by using [advanced structured data models](examples/notebooks/schema_ttrpg.ipynb). ([Colab](https://colab.research.google.com/github/minimaxir/simpleaichat/blob/main/examples/notebooks/schema_ttrpg.ipynb))
## Installation
simpleaichat can be installed [from PyPI](https://pypi.org/project/simpleaichat/):
```sh
pip3 install simpleaichat
```
## Quick, Fun Demo
You can demo chat-apps very quickly with simpleaichat! First, you will need to get an OpenAI API key, and then with one line of code:
```py3
from simpleaichat import AIChat
AIChat(api_key="sk-...")
```
And with that, you'll be thrust directly into an interactive chat!
![](docs/helloworld.png)
This AI chat will mimic the behavior of OpenAI's webapp, but on your local computer!
You can also pass the API key by storing it in an `.env` file with a `OPENAI_API_KEY` field in the working directory (recommended), or by setting the environment variable of `OPENAI_API_KEY` directly to the API key.
But what about creating your own custom conversations? That's where things get fun. Just input whatever person, place or thing, fictional or nonfictional, that you want to chat with!
```py3
AIChat("GLaDOS") # assuming API key loaded via methods above
```
![](docs/glados.png)
But that's not all! You can customize exactly how they behave too with additional commands!
```py3
AIChat("GLaDOS", "Speak in the style of a Seinfeld monologue")
```
![](docs/gladoseinfeld.png)
```py3
AIChat("Ronald McDonald", "Speak using only emoji")
```
![](docs/clownemoji.png)
Need some socialization immediately? Once simpleaichat is installed, you can also start these chats directly from the command line!
```sh
simpleaichat
simpleaichat "GlaDOS"
simpleaichat "GLaDOS" "Speak in the style of a Seinfeld monologue"
```
## Building AI-based Apps
The trick with working with new chat-based apps that wasn't readily available with earlier iterations of GPT-3 is the addition of the system prompt: a different class of prompt that guides the AI behavior throughout the entire conversation. In fact, the chat demos above are actually using [system prompt tricks](https://github.com/minimaxir/simpleaichat/blob/main/PROMPTS.md#interactive-chat) behind the scenes! OpenAI has also released an official guide for [system prompt best practices](https://platform.openai.com/docs/guides/gpt-best-practices) to building AI apps.
For developers, you can instantiate a programmatic instance of `AIChat` by explicitly specifying a system prompt, or by disabling the console.
```py3
ai = AIChat(system="You are a helpful assistant.")
ai = AIChat(console=False) # same as above
```
You can also pass in a `model` parameter, such as `model="gpt-4"` if you have access to GPT-4, or `model="gpt-3.5-turbo-16k"` for a larger-context-window ChatGPT.
You can then feed the new `ai` class with user input, and it will return and save the response from ChatGPT:
```py3
response = ai("What is the capital of California?")
print(response)
```
```
The capital of California is Sacramento.
```
Alternatively, you can stream responses by token with a generator if the text generation itself is too slow:
```py3
for chunk in ai.stream("What is the capital of California?", params={"max_tokens": 5}):
response_td = chunk["response"] # dict contains "delta" for the new token and "response"
print(response_td)
```
```
The
The capital
The capital of
The capital of California
The capital of California is
```
Further calls to the `ai` object will continue the chat, automatically incorporating previous information from the conversation.
```py3
response = ai("When was it founded?")
print(response)
```
```
Sacramento was founded on February 27, 1850.
```
You can also save chat sessions (as CSV or JSON) and load them later. The API key is not saved so you will have to provide that when loading.
```py3
ai.save_session() # CSV, will only save messages
ai.save_session(format="json", minify=True) # JSON
ai.load_session("my.csv")
ai.load_session("my.json")
```
### Functions
A large number of popular venture-capital-funded ChatGPT apps don't actually use the "chat" part of the model. Instead, they just use the system prompt/first user prompt as a form of natural language programming. You can emulate this behavior by passing a new system prompt when generating text, and not saving the resulting messages.
The `AIChat` class is a manager of chat _sessions_, which means you can have multiple independent chats or functions happening! The examples above use a default session, but you can create new ones by specifying a `id` when calling `ai`.
```py3
json = '{"title": "An array of integers.", "array": [-1, 0, 1]}'
functions = [
"Format the user-provided JSON as YAML.",
"Write a limerick based on the user-provided JSON.",
"Translate the user-provided JSON from English to French."
]
params = {"temperature": 0.0, "max_tokens": 100} # a temperature of 0.0 is deterministic
# We namespace the function by `id` so it doesn't affect other chats.
# Settings set during session creation will apply to all generations from the session,
# but you can change them per-generation, as is the case with the `system` prompt here.
ai = AIChat(id="function", params=params, save_messages=False)
for function in functions:
output = ai(json, id="function", system=function)
print(output)
```
```txt
title: "An array of integers."
array:
- -1
- 0
- 1
```
```txt
An array of integers so neat,
With values that can't be beat,
From negative to positive one,
It's a range that's quite fun,
This JSON is really quite sweet!
```
```txt
{"titre": "Un tableau d'entiers.", "tableau": [-1, 0, 1]}
```
Newer versions of ChatGPT also support "[function calling](https://platform.openai.com/docs/guides/gpt/function-calling)", but the real benefit of that feature is the ability for ChatGPT to support structured input and/or output, which now opens up a wide variety of applications! simpleaichat streamlines the workflow to allow you to just pass an `input_schema` and/or an `output_schema`.
You can construct a schema using a [pydantic](https://docs.pydantic.dev/latest/) BaseModel.
```py3
from pydantic import BaseModel, Field
ai = AIChat(
console=False,
save_messages=False, # with schema I/O, messages are never saved
model="gpt-3.5-turbo-0613",
params={"temperature": 0.0},
)
class get_event_metadata(BaseModel):
"""Event information"""
description: str = Field(description="Description of event")
city: str = Field(description="City where event occured")
year: int = Field(description="Year when event occured")
month: str = Field(description="Month when event occured")
# returns a dict, with keys ordered as in the schema
ai("First iPhone announcement", output_schema=get_event_metadata)
```
```txt
{'description': 'The first iPhone was announced by Apple Inc.',
'city': 'San Francisco',
'year': 2007,
'month': 'January'}
```
See the [TTRPG Generator Notebook](examples/notebooks/schema_ttrpg.ipynb) for a more elaborate demonstration of schema capabilities.
### Tools
One of the most recent aspects of interacting with ChatGPT is the ability for the model to use "tools." As popularized by [LangChain](https://github.com/hwchase17/langchain), tools allow the model to decide when to use custom functions, which can extend beyond just the chat AI itself, for example retrieving recent information from the internet not present in the chat AI's training data. This workflow is analogous to ChatGPT Plugins.
Parsing the model output to invoke tools typically requires a number of shennanigans, but simpleaichat uses [a neat trick](https://github.com/minimaxir/simpleaichat/blob/main/PROMPTS.md#tools) to make it fast and reliable! Additionally, the specified tools return a `context` for ChatGPT to draw from for its final response, and tools you specify can return a dictionary which you can also populate with arbitrary metadata for debugging and postprocessing. Each generation returns a dictionary with the `response` and the `tool` function used, which can be used to set up workflows akin to [LangChain](https://github.com/hwchase17/langchain)-style Agents, e.g. recursively feed input to the model until it determines it does not need to use any more tools.
You will need to specify functions with docstrings which provide hints for the AI to select them:
```py3
from simpleaichat.utils import wikipedia_search, wikipedia_search_lookup
# This uses the Wikipedia Search API.
# Results from it are nondeterministic, your mileage will vary.
def search(query):
"""Search the internet."""
wiki_matches = wikipedia_search(query, n=3)
return {"context": ", ".join(wiki_matches), "titles": wiki_matches}
def lookup(query):
"""Lookup more information about a topic."""
page = wikipedia_search_lookup(query, sentences=3)
return page
params = {"temperature": 0.0, "max_tokens": 100}
ai = AIChat(params=params, console=False)
ai("San Francisco tourist attractions", tools=[search, lookup])
```
```txt
{'context': "Fisherman's Wharf, San Francisco, Tourist attractions in the United States, Lombard Street (San Francisco)",
'titles': ["Fisherman's Wharf, San Francisco",
'Tourist attractions in the United States',
'Lombard Street (San Francisco)'],
'tool': 'search',
'response': "There are many popular tourist attractions in San Francisco, including Fisherman's Wharf and Lombard Street. Fisherman's Wharf is a bustling waterfront area known for its seafood restaurants, souvenir shops, and sea lion sightings. Lombard Street, on the other hand, is a famous winding street with eight hairpin turns that attract visitors from all over the world. Both of these attractions are must-sees for anyone visiting San Francisco."}
```
```py3
ai("Lombard Street?", tools=[search, lookup])
```
```
{'context': 'Lombard Street is an east–west street in San Francisco, California that is famous for a steep, one-block section with eight hairpin turns. Stretching from The Presidio east to The Embarcadero (with a gap on Telegraph Hill), most of the street\'s western segment is a major thoroughfare designated as part of U.S. Route 101. The famous one-block section, claimed to be "the crookedest street in the world", is located along the eastern segment in the Russian Hill neighborhood.',
'tool': 'lookup',
'response': 'Lombard Street is a famous street in San Francisco, California known for its steep, one-block section with eight hairpin turns. It stretches from The Presidio to The Embarcadero, with a gap on Telegraph Hill. The western segment of the street is a major thoroughfare designated as part of U.S. Route 101, while the famous one-block section, claimed to be "the crookedest street in the world", is located along the eastern segment in the Russian Hill'}
```
```py3
ai("Thanks for your help!", tools=[search, lookup])
```
```txt
{'response': "You're welcome! If you have any more questions or need further assistance, feel free to ask.",
'tool': None}
```
## Miscellaneous Notes
- Like [gpt-2-simple](https://github.com/minimaxir/gpt-2-simple) before it, the primary motivation behind releasing simpleaichat is to both democratize access to ChatGPT even more and also offer more transparency for non-engineers into how Chat AI-based apps work under the hood given the disproportionate amount of media misinformation about their capabilities. This is inspired by real-world experience from [my work with BuzzFeed](https://tech.buzzfeed.com/the-right-tools-for-the-job-c05de96e949e) in the domain, where after spending a long time working with the popular [LangChain](https://github.com/hwchase17/langchain), a more-simple implementation was both much easier to maintain and resulted in much better generations. I began focusing development on simpleaichat after reading a [Hacker News thread](https://news.ycombinator.com/item?id=35820931) filled with many similar complaints, indicating value for an easier-to-use interface for modern AI tricks.
- simpleaichat very intentionally avoids coupling features with common use cases where possible (e.g. Tools) in order to avoid software lock-in due to the difficulty implementing anything not explicitly mentioned in the project's documentation. The philosophy behind simpleaichat is to provide good demos, and let the user's creativity and business needs take priority instead of having to fit a round peg into a square hole like with LangChain.
- simpleaichat makes it easier to interface with Chat AIs, but it does not attempt to solve common technical and ethical problems inherent to large language models trained on the internet, including prompt injection and unintended plagiarism. The user should exercise good judgment when implementing simpleaichat. Use cases of simpleaichat which go against OpenAI's [usage policies](https://openai.com/policies/usage-policies) (including jailbreaking) will not be endorsed.
- simpleaichat intentionally does not use the "Agent" logical metaphor for tool workflows because it's become an AI hype buzzword heavily divorced from its origins. If needed be, you can emulate the Agent workflow with a `while` loop without much additional code, plus with the additional benefit of much more flexibility such as debugging.
- The session manager implements some sensible security defaults, such as using UUIDs as session ids by default, storing authentication information in a way to minimize unintentional leakage, and type enforcement via Pydantic. Your end-user application should still be aware of potential security issues, however.
- Although OpenAI's documentation says that system prompts are less effective than a user prompt constructed in a similar manner, in my experience it still does perform better for maintaining rules/a persona.
- Many examples of popular prompts use more conversational prompts, while the example prompts here use more consise and imperative prompts. This aspect of prompt engineering is still evolving, but in my experience commands do better with ChatGPT and with greater token efficieny. That's also why simpleaichat allows users to specify system prompts (and explicitly highlights what the default use) instead of relying on historical best practices.
- Token counts for async is not supported as OpenAI doesn't return token counts when streaming responses. In general, there may be some desync in token counts and usage for various use cases; I'm working on categorizing them.
- Outside of the explicit examples, none of this README uses AI-generated text. The introduction code example is just a joke, but it was too good of a real-world use case!
## Roadmap
- PaLM Chat (Bard) and Anthropic Claude support
- More fun/feature-filled CLI chat app based on Textual
- Simple example of using simpleaichat in a webapp
- Simple of example of using simpleaichat in a stateless manner (e.g. AWS Lambda functions)
## Maintainer/Creator
Max Woolf ([@minimaxir](https://minimaxir.com))
_Max's open-source projects are supported by his [Patreon](https://www.patreon.com/minimaxir) and [GitHub Sponsors](https://github.com/sponsors/minimaxir). If you found this project helpful, any monetary contributions to the Patreon are appreciated and will be put to good creative use._
## License
MIT
Raw data
{
"_id": null,
"home_page": "https://github.com/minimaxir/simpleaichat",
"name": "simpleaichat",
"maintainer": "",
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": "",
"keywords": "chatgpt,openai,text generation,ai",
"author": "Max Woolf",
"author_email": "max@minimaxir.com",
"download_url": "https://files.pythonhosted.org/packages/77/61/9234ca68320bfec00e48cc65478bfac3a18b01e08315458dbf9cf38e728d/simpleaichat-0.2.2.tar.gz",
"platform": null,
"description": "# simpleaichat\n\n```py3\nfrom simpleaichat import AIChat\n\nai = AIChat(system=\"Write a fancy GitHub README based on the user-provided project name.\")\nai(\"simpleaichat\")\n```\n\nsimpleaichat is a Python package for easily interfacing with chat apps like ChatGPT and GPT-4 with robust features and minimal code complexity. This tool has many features optimized for working with ChatGPT as fast and as cheap as possible, but still much more capable of modern AI tricks than most implementations:\n\n- Create and run chats with only a few lines of code!\n- Optimized workflows which minimize the amount of tokens used, reducing costs and latency.\n- Run multiple independent chats at once.\n- Minimal codebase: no code dives to figure out what's going on under the hood needed!\n- Chat streaming responses and the ability to use tools.\n- Async support, including for streaming and tools.\n- Ability to create more complex yet clear workflows if needed, such as Agents. (Demo soon!)\n- Coming soon: more chat model support (PaLM, Claude)!\n\nHere's some fun, hackable examples on how simpleaichat works:\n\n- Creating a [Python coding assistant](examples/notebooks/simpleaichat_coding.ipynb) without any unnecessary accompanying output, allowing 5x faster generation at 1/3rd the cost. ([Colab](https://colab.research.google.com/github/minimaxir/simpleaichat/blob/main/examples/notebooks/simpleaichat_coding.ipynb))\n- Allowing simpleaichat to [provide inline tips](examples/notebooks/chatgpt_inline_tips.ipynb) following ChatGPT usage guidelines. ([Colab](https://colab.research.google.com/github/minimaxir/simpleaichat/blob/main/examples/notebooks/chatgpt_inline_tips.ipynb))\n- Async interface for [conducting many chats](examples/notebooks/simpleaichat_async.ipynb) in the time it takes to receive one AI message. ([Colab](https://colab.research.google.com/github/minimaxir/simpleaichat/blob/main/examples/notebooks/simpleaichat_async.ipynb))\n- Create your own Tabletop RPG (TTRPG) setting and campaign by using [advanced structured data models](examples/notebooks/schema_ttrpg.ipynb). ([Colab](https://colab.research.google.com/github/minimaxir/simpleaichat/blob/main/examples/notebooks/schema_ttrpg.ipynb))\n\n## Installation\n\nsimpleaichat can be installed [from PyPI](https://pypi.org/project/simpleaichat/):\n\n```sh\npip3 install simpleaichat\n```\n\n## Quick, Fun Demo\n\nYou can demo chat-apps very quickly with simpleaichat! First, you will need to get an OpenAI API key, and then with one line of code:\n\n```py3\nfrom simpleaichat import AIChat\n\nAIChat(api_key=\"sk-...\")\n```\n\nAnd with that, you'll be thrust directly into an interactive chat!\n\n![](docs/helloworld.png)\n\nThis AI chat will mimic the behavior of OpenAI's webapp, but on your local computer!\n\nYou can also pass the API key by storing it in an `.env` file with a `OPENAI_API_KEY` field in the working directory (recommended), or by setting the environment variable of `OPENAI_API_KEY` directly to the API key.\n\nBut what about creating your own custom conversations? That's where things get fun. Just input whatever person, place or thing, fictional or nonfictional, that you want to chat with!\n\n```py3\nAIChat(\"GLaDOS\") # assuming API key loaded via methods above\n```\n\n![](docs/glados.png)\n\nBut that's not all! You can customize exactly how they behave too with additional commands!\n\n```py3\nAIChat(\"GLaDOS\", \"Speak in the style of a Seinfeld monologue\")\n```\n\n![](docs/gladoseinfeld.png)\n\n```py3\nAIChat(\"Ronald McDonald\", \"Speak using only emoji\")\n```\n\n![](docs/clownemoji.png)\n\nNeed some socialization immediately? Once simpleaichat is installed, you can also start these chats directly from the command line!\n\n```sh\nsimpleaichat\nsimpleaichat \"GlaDOS\"\nsimpleaichat \"GLaDOS\" \"Speak in the style of a Seinfeld monologue\"\n```\n\n## Building AI-based Apps\n\nThe trick with working with new chat-based apps that wasn't readily available with earlier iterations of GPT-3 is the addition of the system prompt: a different class of prompt that guides the AI behavior throughout the entire conversation. In fact, the chat demos above are actually using [system prompt tricks](https://github.com/minimaxir/simpleaichat/blob/main/PROMPTS.md#interactive-chat) behind the scenes! OpenAI has also released an official guide for [system prompt best practices](https://platform.openai.com/docs/guides/gpt-best-practices) to building AI apps.\n\nFor developers, you can instantiate a programmatic instance of `AIChat` by explicitly specifying a system prompt, or by disabling the console.\n\n```py3\nai = AIChat(system=\"You are a helpful assistant.\")\nai = AIChat(console=False) # same as above\n```\n\nYou can also pass in a `model` parameter, such as `model=\"gpt-4\"` if you have access to GPT-4, or `model=\"gpt-3.5-turbo-16k\"` for a larger-context-window ChatGPT.\n\nYou can then feed the new `ai` class with user input, and it will return and save the response from ChatGPT:\n\n```py3\nresponse = ai(\"What is the capital of California?\")\nprint(response)\n```\n\n```\nThe capital of California is Sacramento.\n```\n\nAlternatively, you can stream responses by token with a generator if the text generation itself is too slow:\n\n```py3\nfor chunk in ai.stream(\"What is the capital of California?\", params={\"max_tokens\": 5}):\n response_td = chunk[\"response\"] # dict contains \"delta\" for the new token and \"response\"\n print(response_td)\n```\n\n```\nThe\nThe capital\nThe capital of\nThe capital of California\nThe capital of California is\n```\n\nFurther calls to the `ai` object will continue the chat, automatically incorporating previous information from the conversation.\n\n```py3\nresponse = ai(\"When was it founded?\")\nprint(response)\n```\n\n```\nSacramento was founded on February 27, 1850.\n```\n\nYou can also save chat sessions (as CSV or JSON) and load them later. The API key is not saved so you will have to provide that when loading.\n\n```py3\nai.save_session() # CSV, will only save messages\nai.save_session(format=\"json\", minify=True) # JSON\n\nai.load_session(\"my.csv\")\nai.load_session(\"my.json\")\n```\n\n### Functions\n\nA large number of popular venture-capital-funded ChatGPT apps don't actually use the \"chat\" part of the model. Instead, they just use the system prompt/first user prompt as a form of natural language programming. You can emulate this behavior by passing a new system prompt when generating text, and not saving the resulting messages.\n\nThe `AIChat` class is a manager of chat _sessions_, which means you can have multiple independent chats or functions happening! The examples above use a default session, but you can create new ones by specifying a `id` when calling `ai`.\n\n```py3\njson = '{\"title\": \"An array of integers.\", \"array\": [-1, 0, 1]}'\nfunctions = [\n \"Format the user-provided JSON as YAML.\",\n \"Write a limerick based on the user-provided JSON.\",\n \"Translate the user-provided JSON from English to French.\"\n ]\nparams = {\"temperature\": 0.0, \"max_tokens\": 100} # a temperature of 0.0 is deterministic\n\n# We namespace the function by `id` so it doesn't affect other chats.\n# Settings set during session creation will apply to all generations from the session,\n# but you can change them per-generation, as is the case with the `system` prompt here.\nai = AIChat(id=\"function\", params=params, save_messages=False)\nfor function in functions:\n output = ai(json, id=\"function\", system=function)\n print(output)\n```\n\n```txt\ntitle: \"An array of integers.\"\narray:\n - -1\n - 0\n - 1\n```\n\n```txt\nAn array of integers so neat,\nWith values that can't be beat,\nFrom negative to positive one,\nIt's a range that's quite fun,\nThis JSON is really quite sweet!\n```\n\n```txt\n{\"titre\": \"Un tableau d'entiers.\", \"tableau\": [-1, 0, 1]}\n```\n\nNewer versions of ChatGPT also support \"[function calling](https://platform.openai.com/docs/guides/gpt/function-calling)\", but the real benefit of that feature is the ability for ChatGPT to support structured input and/or output, which now opens up a wide variety of applications! simpleaichat streamlines the workflow to allow you to just pass an `input_schema` and/or an `output_schema`.\n\nYou can construct a schema using a [pydantic](https://docs.pydantic.dev/latest/) BaseModel.\n\n```py3\nfrom pydantic import BaseModel, Field\n\nai = AIChat(\n console=False,\n save_messages=False, # with schema I/O, messages are never saved\n model=\"gpt-3.5-turbo-0613\",\n params={\"temperature\": 0.0},\n)\n\nclass get_event_metadata(BaseModel):\n \"\"\"Event information\"\"\"\n\n description: str = Field(description=\"Description of event\")\n city: str = Field(description=\"City where event occured\")\n year: int = Field(description=\"Year when event occured\")\n month: str = Field(description=\"Month when event occured\")\n\n# returns a dict, with keys ordered as in the schema\nai(\"First iPhone announcement\", output_schema=get_event_metadata)\n```\n\n```txt\n{'description': 'The first iPhone was announced by Apple Inc.',\n 'city': 'San Francisco',\n 'year': 2007,\n 'month': 'January'}\n```\n\nSee the [TTRPG Generator Notebook](examples/notebooks/schema_ttrpg.ipynb) for a more elaborate demonstration of schema capabilities.\n\n### Tools\n\nOne of the most recent aspects of interacting with ChatGPT is the ability for the model to use \"tools.\" As popularized by [LangChain](https://github.com/hwchase17/langchain), tools allow the model to decide when to use custom functions, which can extend beyond just the chat AI itself, for example retrieving recent information from the internet not present in the chat AI's training data. This workflow is analogous to ChatGPT Plugins.\n\nParsing the model output to invoke tools typically requires a number of shennanigans, but simpleaichat uses [a neat trick](https://github.com/minimaxir/simpleaichat/blob/main/PROMPTS.md#tools) to make it fast and reliable! Additionally, the specified tools return a `context` for ChatGPT to draw from for its final response, and tools you specify can return a dictionary which you can also populate with arbitrary metadata for debugging and postprocessing. Each generation returns a dictionary with the `response` and the `tool` function used, which can be used to set up workflows akin to [LangChain](https://github.com/hwchase17/langchain)-style Agents, e.g. recursively feed input to the model until it determines it does not need to use any more tools.\n\nYou will need to specify functions with docstrings which provide hints for the AI to select them:\n\n```py3\nfrom simpleaichat.utils import wikipedia_search, wikipedia_search_lookup\n\n# This uses the Wikipedia Search API.\n# Results from it are nondeterministic, your mileage will vary.\ndef search(query):\n \"\"\"Search the internet.\"\"\"\n wiki_matches = wikipedia_search(query, n=3)\n return {\"context\": \", \".join(wiki_matches), \"titles\": wiki_matches}\n\ndef lookup(query):\n \"\"\"Lookup more information about a topic.\"\"\"\n page = wikipedia_search_lookup(query, sentences=3)\n return page\n\nparams = {\"temperature\": 0.0, \"max_tokens\": 100}\nai = AIChat(params=params, console=False)\n\nai(\"San Francisco tourist attractions\", tools=[search, lookup])\n```\n\n```txt\n{'context': \"Fisherman's Wharf, San Francisco, Tourist attractions in the United States, Lombard Street (San Francisco)\",\n 'titles': [\"Fisherman's Wharf, San Francisco\",\n 'Tourist attractions in the United States',\n 'Lombard Street (San Francisco)'],\n 'tool': 'search',\n 'response': \"There are many popular tourist attractions in San Francisco, including Fisherman's Wharf and Lombard Street. Fisherman's Wharf is a bustling waterfront area known for its seafood restaurants, souvenir shops, and sea lion sightings. Lombard Street, on the other hand, is a famous winding street with eight hairpin turns that attract visitors from all over the world. Both of these attractions are must-sees for anyone visiting San Francisco.\"}\n```\n\n```py3\nai(\"Lombard Street?\", tools=[search, lookup])\n```\n\n```\n{'context': 'Lombard Street is an east\u2013west street in San Francisco, California that is famous for a steep, one-block section with eight hairpin turns. Stretching from The Presidio east to The Embarcadero (with a gap on Telegraph Hill), most of the street\\'s western segment is a major thoroughfare designated as part of U.S. Route 101. The famous one-block section, claimed to be \"the crookedest street in the world\", is located along the eastern segment in the Russian Hill neighborhood.',\n 'tool': 'lookup',\n 'response': 'Lombard Street is a famous street in San Francisco, California known for its steep, one-block section with eight hairpin turns. It stretches from The Presidio to The Embarcadero, with a gap on Telegraph Hill. The western segment of the street is a major thoroughfare designated as part of U.S. Route 101, while the famous one-block section, claimed to be \"the crookedest street in the world\", is located along the eastern segment in the Russian Hill'}\n```\n\n```py3\nai(\"Thanks for your help!\", tools=[search, lookup])\n```\n\n```txt\n{'response': \"You're welcome! If you have any more questions or need further assistance, feel free to ask.\",\n 'tool': None}\n```\n\n## Miscellaneous Notes\n\n- Like [gpt-2-simple](https://github.com/minimaxir/gpt-2-simple) before it, the primary motivation behind releasing simpleaichat is to both democratize access to ChatGPT even more and also offer more transparency for non-engineers into how Chat AI-based apps work under the hood given the disproportionate amount of media misinformation about their capabilities. This is inspired by real-world experience from [my work with BuzzFeed](https://tech.buzzfeed.com/the-right-tools-for-the-job-c05de96e949e) in the domain, where after spending a long time working with the popular [LangChain](https://github.com/hwchase17/langchain), a more-simple implementation was both much easier to maintain and resulted in much better generations. I began focusing development on simpleaichat after reading a [Hacker News thread](https://news.ycombinator.com/item?id=35820931) filled with many similar complaints, indicating value for an easier-to-use interface for modern AI tricks.\n - simpleaichat very intentionally avoids coupling features with common use cases where possible (e.g. Tools) in order to avoid software lock-in due to the difficulty implementing anything not explicitly mentioned in the project's documentation. The philosophy behind simpleaichat is to provide good demos, and let the user's creativity and business needs take priority instead of having to fit a round peg into a square hole like with LangChain.\n - simpleaichat makes it easier to interface with Chat AIs, but it does not attempt to solve common technical and ethical problems inherent to large language models trained on the internet, including prompt injection and unintended plagiarism. The user should exercise good judgment when implementing simpleaichat. Use cases of simpleaichat which go against OpenAI's [usage policies](https://openai.com/policies/usage-policies) (including jailbreaking) will not be endorsed.\n - simpleaichat intentionally does not use the \"Agent\" logical metaphor for tool workflows because it's become an AI hype buzzword heavily divorced from its origins. If needed be, you can emulate the Agent workflow with a `while` loop without much additional code, plus with the additional benefit of much more flexibility such as debugging.\n- The session manager implements some sensible security defaults, such as using UUIDs as session ids by default, storing authentication information in a way to minimize unintentional leakage, and type enforcement via Pydantic. Your end-user application should still be aware of potential security issues, however.\n- Although OpenAI's documentation says that system prompts are less effective than a user prompt constructed in a similar manner, in my experience it still does perform better for maintaining rules/a persona.\n- Many examples of popular prompts use more conversational prompts, while the example prompts here use more consise and imperative prompts. This aspect of prompt engineering is still evolving, but in my experience commands do better with ChatGPT and with greater token efficieny. That's also why simpleaichat allows users to specify system prompts (and explicitly highlights what the default use) instead of relying on historical best practices.\n- Token counts for async is not supported as OpenAI doesn't return token counts when streaming responses. In general, there may be some desync in token counts and usage for various use cases; I'm working on categorizing them.\n- Outside of the explicit examples, none of this README uses AI-generated text. The introduction code example is just a joke, but it was too good of a real-world use case!\n\n## Roadmap\n\n- PaLM Chat (Bard) and Anthropic Claude support\n- More fun/feature-filled CLI chat app based on Textual\n- Simple example of using simpleaichat in a webapp\n- Simple of example of using simpleaichat in a stateless manner (e.g. AWS Lambda functions)\n\n## Maintainer/Creator\n\nMax Woolf ([@minimaxir](https://minimaxir.com))\n\n_Max's open-source projects are supported by his [Patreon](https://www.patreon.com/minimaxir) and [GitHub Sponsors](https://github.com/sponsors/minimaxir). If you found this project helpful, any monetary contributions to the Patreon are appreciated and will be put to good creative use._\n\n## License\n\nMIT\n\n\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "A Python package for easily interfacing with chat apps, with robust features and minimal code complexity.",
"version": "0.2.2",
"project_urls": {
"Homepage": "https://github.com/minimaxir/simpleaichat"
},
"split_keywords": [
"chatgpt",
"openai",
"text generation",
"ai"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "77619234ca68320bfec00e48cc65478bfac3a18b01e08315458dbf9cf38e728d",
"md5": "aa42f4fc6c7649ec81a486acff97f352",
"sha256": "d25e9c9264f0c30d6e90f8e8839424e92680626aa190b8450b9fd4cd3cd73d55"
},
"downloads": -1,
"filename": "simpleaichat-0.2.2.tar.gz",
"has_sig": false,
"md5_digest": "aa42f4fc6c7649ec81a486acff97f352",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 23083,
"upload_time": "2023-07-24T01:43:27",
"upload_time_iso_8601": "2023-07-24T01:43:27.940410Z",
"url": "https://files.pythonhosted.org/packages/77/61/9234ca68320bfec00e48cc65478bfac3a18b01e08315458dbf9cf38e728d/simpleaichat-0.2.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2023-07-24 01:43:27",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "minimaxir",
"github_project": "simpleaichat",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "simpleaichat"
}