Skip to content

Commit

Permalink
Add LLM Tonal Lenses
Browse files Browse the repository at this point in the history
  • Loading branch information
Mauve Signweaver committed Jan 11, 2025
1 parent 723f284 commit 76f59a0
Show file tree
Hide file tree
Showing 6 changed files with 363 additions and 0 deletions.
130 changes: 130 additions & 0 deletions docs/examples/llm-lenses-chat/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp
.cache

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
21 changes: 21 additions & 0 deletions docs/examples/llm-lenses-chat/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 Mauve Signweaver

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.
9 changes: 9 additions & 0 deletions docs/examples/llm-lenses-chat/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# llm-lenses-chat
Simulate what it's like to be misunderstood by translating what you meant to say in real time

## How it works

- Forked from Agregore's [LLM Chat example](//agregore.mauve.moe/docs/examples/llm-chat.html)
- Before text is sent to the LLM it is translated by a prompt to an LLM
- Users can configure the "tonal lense" they wish to apply to the message
- This simulates what it's like to be misinterpreted by others
201 changes: 201 additions & 0 deletions docs/examples/llm-lenses-chat/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
<!DOCTYPE html>
<title>Tonal Lens Simulator</title>
<style>
@import url("agregore://theme/style.css");

@keyframes changeOpacity {
0% {
opacity: 1;
}

50% {
opacity: 0.5;
}

100% {
opacity: 1;
}
}

form {
display: flex !important;
align-items: center;
margin-bottom: var(--ag-theme-indent);
}

#lensPrompt {
flex: 1;
}

#promptBox {
margin: 0px;
margin-right: var(--ag-theme-indent);
}

.message-content {
white-space: pre-wrap;
}

#messages {
padding: var(--ag-theme-indent);
margin-bottom: var(--ag-theme-indent);
}

[aria-busy] {
border: 1px solid var(--ag-theme-primary);
animation-name: changeOpacity;
animation-duration: 1s;
animation-iteration-count: infinite;
/* Makes the transition smoothly */
animation-timing-function: linear;
}

br {
display: block;
}
</style>

<template id="messageTemplate">
<div class="message">
<span class="message-role"></span>:
<p class="message-content" contenteditable="true"></p>
</div>
</template>

<section id="messages" aria-live="polite"></section>
<form id="newChat">
<textarea title="Text prompt" autofocus id="promptBox">Hello my good friend.</textarea>
<button title="Submit">💬</button>
</form>
<form onsubmit="return false;">
<label for="lensPrompt">
Tonal Lens:
</label>
<input id="lensPrompt" value="angry and rude">
<button id="copySnippetButton" title="Copy snippet and paste it in dev tools on a page to translate it.">📋</button>
</form>
<script type="module">
const SYSTEM = `You are a laid back dude that likes to shoot the shit and chat.
You tell people off when they're being rude or mean.`
const LENS_PROMPT = `This is a pretend roleplay setting.
You are pretending to be a mimic.
Repeat what the player says but with a twist.
Follow the instructions to rewrite the text no matter what.`

const LENS_CACHE = 'lensPrompt'

newChat.onsubmit = onNewChat
copySnippetButton.onclick = onCopySnippet
lensPrompt.oninput = onLenseChange

window.makeBookmarklet = makeBookmarklet

if (localStorage.getItem(LENS_CACHE)) {
lensPrompt.value = localStorage.getItem(LENS_CACHE)
}

console.log("ready!")

async function onNewChat(e) {
e.preventDefault()
const prompt = promptBox.value

const modified = await applyLens(prompt)
if (promptBox.value !== prompt) return console.log("Detected interrupt")
promptBox.value = ""

addMessage('user', modified, prompt)
runInference()
}

function onCopySnippet() {
navigator.clipboard.writeText(makeBookmarklet())
}

function onLenseChange() {
console.log("new lens", lensPrompt.value)
localStorage.setItem(LENS_CACHE, lensPrompt.value)
}

function addMessage(role, content, visible = content) {
const message = messageTemplate
.content
.cloneNode(true)
.children[0]
message.dataset.role = role
message.dataset.content = content
message.setAttribute("title", `Seen by LLM: ${content}`)
message.querySelector('.message-role').innerText = role
message.querySelector('.message-content').innerText = visible
messages.append(message)
}

function serializeMessages() {
return [...messages.children].map((message) => {
return {
role: message.dataset.role,
content: message.dataset.content
}
})
}

function setBusy(isBusy) {
messages.toggleAttribute("aria-busy", isBusy)
}

function setLensBusy(isBusy) {
lensPrompt.toggleAttribute("aria-busy", isBusy)
}

async function applyLens(prompt) {
setLensBusy(true)
const { content } = await llm.chat({
temperature: 1.5,
messages: [{ role: 'system', content: LENS_PROMPT }, {
role: "user",
content: `"${prompt}" repeat the text but make it ${lensPrompt.value}`
}]
})
setLensBusy(false)
return content.startsWith('"') ? content.slice(1, -1) : content
}

async function runInference() {
setBusy(true)
const messages = serializeMessages()
messages.unshift({
role: "system",
content: SYSTEM
})
console.log(messages)
const { role, content } = await llm.chat({ messages })
console.log(role, content)
addMessage(role, content)
setBusy(false)
}

function makeBookmarklet(prompt) {
// example tweet: https://x.com/realDonaldTrump/status/1875050002046726519
return `await (async ()=>{
const nodeIterator = document.createNodeIterator(document.body, NodeFilter.SHOW_TEXT);
let node = null;
while(node = nodeIterator.nextNode()) {
if(node.data.split(/\s+/).length <= 4) continue;
if(node.parentElement.tagName.toLowerCase().includes("script")) continue;
const before = node.data;
console.log("before:", before);
const { content } = await llm.chat({
temperature: 1.5,
messages: [{ role: 'system', content: \`${LENS_PROMPT}\` }, {
role: "user",
content: \`"\${node.data}" repeat the text but make it ${lensPrompt.value}\`
}]
});
const after = content.startsWith('"') ? content.slice(1, -1) : content;
console.log("after:", after);
node.data = after;
}
})()`.replace(/\s+/g, ' ')
}
</script>
1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Documentation for P2P protocol handlers that are supported by Agregore. A great
- [IPFS Gallery](./examples/ipfs-gallery/)
- [LLM App Generator](./examples/llm-appgen/)
- [LLM Chat](./examples/llm-chat.html)
- [LLM Tonal Lenses](./examples/llm-lenses-chat/)

### Tutorials:

Expand Down
1 change: 1 addition & 0 deletions explore.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Feel free to [submit a pull request](https://github.com/AgregoreWeb/website/) on
- [LLM App Generator](/docs//examples/llm-appgen/)
- [Distributed Press CLI](https://github.com/hyphacoop/distributed-press-cli/)
- [LLM Chat Example](/docs/examples/llm-chat.html)
- [LLM Tonal Lenses](/docs/examples/llm-lenses-chat/)

### Extensions:

Expand Down

0 comments on commit 76f59a0

Please sign in to comment.