Skip to content

Commit

Permalink
feat: AI improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
BigJk committed Sep 14, 2024
1 parent ed2ad84 commit 7043b8e
Show file tree
Hide file tree
Showing 14 changed files with 215 additions and 84 deletions.
23 changes: 23 additions & 0 deletions database/badger/badger.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,3 +232,26 @@ func (b *Badger) SetKey(key string, value string) error {
return txn.Set([]byte("KV_"+key), []byte(value))
})
}

func (b *Badger) DeleteKey(key string) error {
return dropSingle(b.db, "KV_"+key)
}

func (b *Badger) GetKeysPrefix(prefix string) ([]string, error) {
var keys []string
err := b.db.View(func(txn *badger.Txn) error {
opts := badger.DefaultIteratorOptions
opts.PrefetchSize = 10
it := txn.NewIterator(opts)
defer it.Close()

prefix := []byte("KV_" + prefix)
for it.Seek(prefix); it.ValidForPrefix(prefix); it.Next() {
item := it.Item()
k := item.Key()
keys = append(keys, strings.TrimPrefix(string(k), "KV_"))
}
return nil
})
return keys, err
}
8 changes: 8 additions & 0 deletions database/cloud/cloud.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,3 +226,11 @@ func (c *Cloud) GetKey(key string) (string, error) {
func (c *Cloud) SetKey(key string, value string) error {
return errors.New("not implemented")
}

func (c *Cloud) DeleteKey(key string) error {
return errors.New("not implemented")
}

func (c *Cloud) GetKeysPrefix(prefix string) ([]string, error) {
return nil, errors.New("not implemented")
}
2 changes: 2 additions & 0 deletions database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,6 @@ type Database interface {

GetKey(key string) (string, error)
SetKey(key string, value string) error
DeleteKey(key string) error
GetKeysPrefix(prefix string) ([]string, error)
}
18 changes: 18 additions & 0 deletions database/memory/memory.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,3 +169,21 @@ func (m *Memory) SetKey(key string, value string) error {
m.kv[key] = value
return nil
}

func (m *Memory) DeleteKey(key string) error {
delete(m.kv, key)
return nil
}

func (m *Memory) GetKeysPrefix(prefix string) ([]string, error) {
var keys []string
for k := range m.kv {
if len(prefix) > len(k) {
continue
}
if k[:len(prefix)] == prefix {
keys = append(keys, k)
}
}
return keys, nil
}
8 changes: 8 additions & 0 deletions database/storm/storm.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,3 +194,11 @@ func (s *Storm) GetKey(key string) (string, error) {
func (s *Storm) SetKey(key, value string) error {
return errors.New("not implemented")
}

func (s *Storm) DeleteKey(key string) error {
return errors.New("not implemented")
}

func (s *Storm) GetKeysPrefix(prefix string) ([]string, error) {
return nil, errors.New("not implemented")
}
1 change: 1 addition & 0 deletions frontend/src/js/core/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ export const SYNC_LOCAL_TO_CLOUD = 'syncLocalToCloud';
export const AI_GENERATE = 'aiPrompt';
export const AI_MODELS = 'aiModels';
export const AI_PROVIDERS = 'aiProviders';
export const AI_INVALIDATE_CACHE = 'aiInvalidateCached';

// File Browser
export const GET_FILES = 'getFiles';
Expand Down
14 changes: 7 additions & 7 deletions frontend/src/js/core/templating.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,13 +90,13 @@ const rngScript = (seed: any) => `
<script>
window.random = new Math.seedrandom('${seed}');
Math.random = window.random;
rpgDiceRoller.NumberGenerator.generator.engine = {
next () {
return Math.abs(window.random.int32());
},
};
window.dice = new rpgDiceRoller.DiceRoller();
</script>
`;
Expand All @@ -109,26 +109,26 @@ const aiScript = `
<script>
const aiEnabled = {{ aiEnabled }};
const aiToken = '{{ aiToken }}';
const aiPrompt = (system, user) => {
if(!aiEnabled) {
// Try and see if the response was cached
const request = new XMLHttpRequest();
request.open("POST", "http://127.0.0.1:7123/api/aiCached", false); // Synchronous request
request.send(JSON.stringify([system, user, aiToken]));
if(request.status === 200) {
return JSON.parse(request.responseText);
}
// Don't execute AI
return "AI content disabled.";
}
const request = new XMLHttpRequest();
request.open("POST", "http://127.0.0.1:7123/api/aiPrompt", false); // Synchronous request
request.send(JSON.stringify([system, user, aiToken]));
if(request.status === 200) {
return JSON.parse(request.responseText);
} else {
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/js/types/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ type Settings = {
syncKey: string;
syncEnabled: boolean;
aiEnabled: boolean;
aiAlwaysAllow: boolean;
aiApiKey: string;
aiProvider: string;
aiModel: string;
Expand Down Expand Up @@ -49,6 +50,7 @@ export function createEmptySettings(): Settings {
syncKey: '',
syncEnabled: false,
aiEnabled: false,
aiAlwaysAllow: false,
aiApiKey: '',
aiProvider: '',
aiModel: '',
Expand Down
79 changes: 61 additions & 18 deletions frontend/src/js/ui/components/print-preview-template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@ import m from 'mithril';
import { cloneDeep, debounce, isEqual } from 'lodash-es';

import Entry from 'js/types/entry';
import Generator from 'js/types/generator';
import Generator, { seed } from 'js/types/generator';
import Template from 'js/types/template';
import * as API from 'js/core/api';
import store, { settings } from 'js/core/store';
import { addEntryMeta, containsAi, render } from 'js/core/templating';

import Button from 'js/ui/shoelace/button';
import Checkbox from 'js/ui/shoelace/checkbox';
import IconButton from 'js/ui/shoelace/icon-button';

import Icon from 'js/ui/components/atomic/icon';
import Tooltip from 'js/ui/components/atomic/tooltip';
import Flex from 'js/ui/components/layout/flex';
import PrintPreview from 'js/ui/components/print-preview';

Expand Down Expand Up @@ -37,7 +40,8 @@ export default (): m.Component<PrintPreviewTemplateProps> => {
let lastProps: PrintPreviewTemplateProps | null = null;
let loading = false;
let lastRendered = '';
let aiEnabled = false;
let aiEnabled = settings.value.aiAlwaysAllow;
let allowReRender = 0;

const getTemplate = (attrs: PrintPreviewTemplateProps) => {
if (attrs.template) {
Expand All @@ -51,7 +55,7 @@ export default (): m.Component<PrintPreviewTemplateProps> => {

const updateLastRendered = debounce((attrs: PrintPreviewTemplateProps) => {
if (
!aiEnabled &&
!allowReRender &&
lastProps !== null &&
isEqual(lastProps.template, attrs.template) &&
isEqual(lastProps.it, attrs.it) &&
Expand All @@ -62,6 +66,11 @@ export default (): m.Component<PrintPreviewTemplateProps> => {
return;
}

allowReRender--;
if (allowReRender < 0) {
allowReRender = 0;
}

lastProps = cloneDeep(attrs);
loading = true;
m.redraw();
Expand All @@ -80,6 +89,11 @@ export default (): m.Component<PrintPreviewTemplateProps> => {
})
.then((html) => {
lastRendered = html;

if (aiEnabled) {
lastRendered += `<!-- ${seed()} -->`;
}

if (attrs.onRendered) attrs.onRendered(html);
if (attrs.onError) attrs.onError([]);
})
Expand All @@ -91,8 +105,6 @@ export default (): m.Component<PrintPreviewTemplateProps> => {
loading = false;
m.redraw();
});

aiEnabled = false;
}, 500);

return {
Expand Down Expand Up @@ -127,18 +139,49 @@ export default (): m.Component<PrintPreviewTemplateProps> => {
m('div.f8.o-50', 'Execution requires permission!'),
]),
]),
m(
Button,
{
size: 'sm',
intend: 'primary',
onClick: () => {
store.actions.setRandomAIToken();
aiEnabled = true;
},
},
'Allow or Re-Roll',
),
m(Flex, { gap: 2, items: 'center' }, [
m(
Tooltip,
{ content: 'Allow' },
m(Checkbox, {
checked: aiEnabled,
onChange: (val) => {
aiEnabled = val;
if (aiEnabled) {
if (attrs.generator && attrs.config.seed) {
store.actions.setAIToken(attrs.config.seed);
} else {
store.actions.setRandomAIToken();
}
}
allowReRender = 1;
},
}),
),
aiEnabled
? m(
Tooltip,
{ content: 'Re-Roll' },
m(
IconButton,
{
icon: 'refresh',
size: 'sm',
intend: 'primary',
onClick: () => {
API.exec(API.AI_INVALIDATE_CACHE, store.value.ai.token)
.then(() => {
allowReRender = 1;
m.redraw();
})
.catch(console.error);
},
},
'',
),
)
: null,
]),
]),
),
)
Expand Down
Loading

0 comments on commit 7043b8e

Please sign in to comment.