ChatGPTHandler

ChatGPTHandler is an interface to OpenAI’s chat API that maintains message history.

ChatGPTHandler

This is a minimal configuration. Replace the key with your OpenAI API key (help).

url:
  chatgpthandler:
    pattern: /$YAMLURL/chat
    handler: ChatGPTHandler
    kwargs:
      key: sz-....

This opens a WebSocket connection to /chat. You can send messages to it using:

const url = location.href.replace(/^http/, "ws").replace(/\/[^/]*$/, "/chat");
const ws = new WebSocket(url);
ws.onopen = () => ws.send("What rhymes with silk?");
ws.onmessage = (message) => console.log(message.data);

This sends a question “What rhymes with silk?” to OpenAI, and logs the response to the console.

milk, bilk, ilk, wilk, filk
<!doctype html>
<form>
  <input id="input" value="What rhymes with milk?" /> <button>Send</button>
</form>
<pre id="output"></pre>
<script type="module">
  const ws = new WebSocket(
    location.href.replace(/^http/, "ws") + "chatgpt?stream",
  );
  const input = document.querySelector("#input");
  const output = document.querySelector("#output");
  ws.onmessage = (event) =>
    output.insertAdjacentHTML("beforeend", event.data || "\n\n");
  document.querySelector("form").addEventListener(
    "submit",
    (e) => {
      e.preventDefault();
      ws.send(input.value);
      output.insertAdjacentHTML("beforeend", `\n${input.value}\n\n`);
    },
    false,
  );
</script>

ChatGPTHandler configuration

You can use the following parameters:

ChatGPTHandler parameter substitution

Any of the configurations can be a Python expression that uses handler. For example:

url:
  chatgpthandler:
    pattern: /$YAMLURL/chat
    handler: ChatGPTHandler
    kwargs:
      key: {function: handler.get_arg('key)}
      model: {function: handler.get_arg('model', 'gpt-3.5-turbo')}

This lets the front-end pass the key and model to use. For example:

ChatGPTHandler history

By default, ChatGPTHandler stores the entire conversation history from the time the WebSocket is opened. This history is sent to OpenAI with every message.

To limit the number of messages (e.g. to reduce the number of tokens processed), use max_history. For example:

url:
  chatgpthandler:
    pattern: /$YAMLURL/chat
    handler: ChatGPTHandler
    kwargs:
      key: sz-....
      max_history: 5

This stores and sends only the last 5 messages to OpenAI.

ChatGPTHandler streaming

ChatGPTHandler transforms