initial commit

This commit is contained in:
Jeff Epler 2023-11-08 08:50:05 -06:00
commit 06d3a4d952
No known key found for this signature in database
GPG key ID: D5BF15AB975AB4DE
7 changed files with 208 additions and 0 deletions

8
.gitignore vendored Normal file
View file

@ -0,0 +1,8 @@
# SPDX-FileCopyrightText: 2023 Jeff Epler <jepler@gmail.com>
#
# SPDX-License-Identifier: MIT
__pycache__
*.egg-info/
/build
/dist

41
.pre-commit-config.yaml Normal file
View file

@ -0,0 +1,41 @@
# SPDX-FileCopyrightText: 2020 Diego Elio Pettenò
#
# SPDX-License-Identifier: Unlicense
default_language_version:
python: python3
repos:
- repo: https://github.com/psf/black
rev: 23.1.0
hooks:
- id: black
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: check-yaml
- id: end-of-file-fixer
exclude: tests
- id: trailing-whitespace
exclude: tests
- repo: https://github.com/codespell-project/codespell
rev: v2.2.4
hooks:
- id: codespell
args: [-w]
- repo: https://github.com/fsfe/reuse-tool
rev: v1.1.2
hooks:
- id: reuse
- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
name: isort (python)
args: ['--profile', 'black']
- repo: https://github.com/pycqa/pylint
rev: v2.17.0
hooks:
- id: pylint
additional_dependencies: [chap]
args: ['--source-roots', 'src']

9
LICENSES/MIT.txt Normal file
View file

@ -0,0 +1,9 @@
MIT License
Copyright (c) <year> <copyright holders>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

10
LICENSES/Unlicense.txt Normal file
View file

@ -0,0 +1,10 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>

22
README.md Normal file
View file

@ -0,0 +1,22 @@
<!--
SPDX-FileCopyrightText: 2021 Jeff Epler
SPDX-License-Identifier: MIT
-->
# chap-backend-replay
A proof-of-concept backend plug-in for chap.
## Installation
If you installed chap with pip, then run `pip install chap-backend-replay`.
If you installed chap with pipx, then run `pipx inject chap chap-backend-replay`.
## Use
`chap --backend replay -B session:/full/path/to/existing-chap-session.json tui`
There are additional back-end parameters, use `chap --backend replay --help` to list them.

40
pyproject.toml Normal file
View file

@ -0,0 +1,40 @@
# SPDX-FileCopyrightText: 2021 Jeff Epler
#
# SPDX-License-Identifier: MIT
[build-system]
requires = [
"setuptools>=61",
"setuptools_scm[toml]>=6.0",
]
build-backend = "setuptools.build_meta"
[tool.setuptools]
package-dir = {"" = "src"}
[tool.setuptools.packages.find]
where = ["src"]
[project]
name="chap-backend-replay"
authors = [{name = "Jeff Epler", email = "jepler@gmail.com"}]
description = "Session-replaying backend for chap"
dynamic = ["readme","version"]
dependencies = [
"chap",
]
classifiers = [
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: Implementation :: PyPy",
"Programming Language :: Python :: Implementation :: CPython",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
]
[project.urls]
homepage = "https://github.com/jepler/chap-backend-replay"
repository = "https://github.com/jepler/chap-backend-replay"
[tool.setuptools_scm]
[tool.setuptools.dynamic]
readme = {file = ["README.md"], content-type="text/markdown"}

View file

@ -0,0 +1,78 @@
# SPDX-FileCopyrightText: 2023 Jeff Epler <jepler@gmail.com>
#
# SPDX-License-Identifier: MIT
import asyncio
import functools
import random
import os
from dataclasses import dataclass
import click
from ..session import Assistant, User, Session
def ipartition(s, sep=" "):
rest = s
while rest:
first, opt_sep, rest = rest.partition(sep)
yield (first, opt_sep)
class Replay:
@dataclass
class Parameters:
session: str = None
"""Complete path to an existing session file"""
delay_mu: float = 0.035
"""Average delay between tokens"""
delay_sigma: float = 0.02
"""Standard deviation of token delay"""
def __init__(self):
self.parameters = self.Parameters()
@property
@functools.cache
def _session(self):
if self.parameters.session is None:
raise click.BadParameter("Must specify -B session:/full/path/to/existing_session.json")
session_file = os.path.expanduser(self.parameters.session)
with open(session_file, "r", encoding="utf-8") as f:
return Session.from_json(f.read())
@property
@functools.cache
def _assistant_responses(self):
return [message for message in self._session.session if message.role == 'assistant']
@property
def system_message(self):
num_assistant_responses = len(self._assistant_responses)
return f"Replay of {self.parameters.session} with {num_assistant_responses} responses. The original session system message was:\n\n{self._session.session[0].content}"
async def aask(self, session, query):
data = self.ask(session, query)
for word, opt_sep in ipartition(data):
yield word + opt_sep
await asyncio.sleep(
random.gauss(self.parameters.delay_mu, self.parameters.delay_sigma)
)
def ask(
self, session, query, *, max_query_size=5, timeout=60
): # pylint: disable=unused-argument
if self._assistant_responses:
idx = sum(1 for message in session.session if message.role == 'assistant') % len(self._assistant_responses)
new_content = self._assistant_responses[idx].content
else:
new_content = "(No assistant responses in session)"
session.session.extend([User(query), Assistant(new_content)])
return new_content
def factory():
"""Replay an existing session file. Useful for testing."""
return Replay()