Suggest based on title from bookmarklet
This commit is contained in:
58
main.go
58
main.go
@@ -26,6 +26,7 @@ type ShortLinks struct {
|
|||||||
|
|
||||||
domainAliases map[string]string
|
domainAliases map[string]string
|
||||||
writableDomains map[string]bool
|
writableDomains map[string]bool
|
||||||
|
responseFormat *oaiResponseFormat
|
||||||
}
|
}
|
||||||
|
|
||||||
type setResponse struct {
|
type setResponse struct {
|
||||||
@@ -34,6 +35,11 @@ type setResponse struct {
|
|||||||
URL string `json:"url"`
|
URL string `json:"url"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type suggestRequest struct {
|
||||||
|
Shorts []string `json:"shorts,omitempty"`
|
||||||
|
Title string `json:"title,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
type suggestResponse struct {
|
type suggestResponse struct {
|
||||||
Shorts []string `json:"shorts"`
|
Shorts []string `json:"shorts"`
|
||||||
Domain string `json:"domain"`
|
Domain string `json:"domain"`
|
||||||
@@ -96,6 +102,26 @@ func NewShortLinks(db *sql.DB, domainAliases map[string]string, writableDomains
|
|||||||
|
|
||||||
domainAliases: domainAliases,
|
domainAliases: domainAliases,
|
||||||
writableDomains: writableDomains,
|
writableDomains: writableDomains,
|
||||||
|
responseFormat: &oaiResponseFormat{
|
||||||
|
Type: "json_schema",
|
||||||
|
JSONSchema: map[string]any{
|
||||||
|
"name": "suggest_response",
|
||||||
|
"strict": true,
|
||||||
|
"schema": map[string]any{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]any{
|
||||||
|
"shorts": map[string]any{
|
||||||
|
"type": "array",
|
||||||
|
"items": map[string]any{
|
||||||
|
"type": "string",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"required": []string{"shorts"},
|
||||||
|
"additionalProperties": false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
sl.mux.HandleFunc("GET /{$}", sl.serveRoot)
|
sl.mux.HandleFunc("GET /{$}", sl.serveRoot)
|
||||||
@@ -157,6 +183,7 @@ func (sl *ShortLinks) serveRootWithShort(w http.ResponseWriter, r *http.Request,
|
|||||||
"short": short,
|
"short": short,
|
||||||
"host": sl.getDomain(r.Host),
|
"host": sl.getDomain(r.Host),
|
||||||
"long": r.Form.Get("long"),
|
"long": r.Form.Get("long"),
|
||||||
|
"title": r.Form.Get("title"),
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
sendError(w, http.StatusInternalServerError, "error executing template: %s", err)
|
sendError(w, http.StatusInternalServerError, "error executing template: %s", err)
|
||||||
@@ -238,33 +265,32 @@ func (sl *ShortLinks) serveSuggest(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if !r.Form.Has("shorts") {
|
if !r.Form.Has("shorts") && !r.Form.Has("title") {
|
||||||
sendError(w, http.StatusBadRequest, "shorts= param required")
|
sendError(w, http.StatusBadRequest, "shorts= or title= param required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
user := strings.Join(r.Form["shorts"], "\n")
|
in := suggestRequest{
|
||||||
|
Shorts: r.Form["shorts"],
|
||||||
|
Title: r.Form.Get("title"),
|
||||||
|
}
|
||||||
|
|
||||||
comp, err := sl.oai.completeChat(
|
out := &suggestResponse{}
|
||||||
"You are an assistant helping a user choose useful short names for a URL shortener. The request contains a list recents names chosen by the user, separated by newlines, with the most recent names first. Respond with only a list of possible suggestions for additional short names, separated by newlines. In descending order of preference, suggestions should include: plural/singular variations, 2 and 3 letter abbreivations, conceptual variations, other variations that are likely to be useful. Your bar for suggestions should be relatively high; responding with a shorter list of high quality suggestions is preferred.",
|
|
||||||
user,
|
err = sl.oai.completeChat(
|
||||||
|
"You are an assistant helping a user choose useful short names for a URL shortener. The request contains JSON object where the optional `shorts` key contains a list of recent names chosen by the user, with the most recent names first, and the optional `title` key contains a title for the URL. Respond with only a JSON object where the `shorts` key contains a list of possible suggestions for additional short names. In descending order of preference, suggestions should include: plural/singular variations, 2 and 3 letter abbreivations, conceptual variations, other variations that are likely to be useful. Your bar for suggestions should be relatively high; responding with a shorter list of high quality suggestions is preferred.",
|
||||||
|
in,
|
||||||
|
sl.responseFormat,
|
||||||
|
out,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
sendError(w, http.StatusInternalServerError, "oai.completeChat: %s", err)
|
sendError(w, http.StatusInternalServerError, "oai.completeChat: %s", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
shorts := []string{}
|
out.Domain = sl.getDomain(r.Host)
|
||||||
for _, short := range strings.Split(comp, "\n") {
|
|
||||||
if short != "" {
|
|
||||||
shorts = append(shorts, strings.TrimSpace(short))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
sendJSON(w, suggestResponse{
|
sendJSON(w, out)
|
||||||
Shorts: shorts,
|
|
||||||
Domain: sl.getDomain(r.Host),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (sl *ShortLinks) serveHelp(w http.ResponseWriter, r *http.Request) {
|
func (sl *ShortLinks) serveHelp(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|||||||
46
openai.go
46
openai.go
@@ -15,8 +15,14 @@ type oaiClient struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type oaiRequest struct {
|
type oaiRequest struct {
|
||||||
Model string `json:"model"`
|
Model string `json:"model"`
|
||||||
Messages []oaiMessage `json:"messages"`
|
Messages []oaiMessage `json:"messages"`
|
||||||
|
ResponseFormat *oaiResponseFormat `json:"response_format"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type oaiResponseFormat struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
JSONSchema map[string]interface{} `json:"json_schema"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type oaiMessage struct {
|
type oaiMessage struct {
|
||||||
@@ -48,23 +54,28 @@ func newOAIClientFromEnv() (*oaiClient, error) {
|
|||||||
return newOAIClient(apiKey), nil
|
return newOAIClient(apiKey), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (oai *oaiClient) completeChat(system, user string) (string, error) {
|
func (oai *oaiClient) completeChat(system string, in any, responseFormat *oaiResponseFormat, out any) error {
|
||||||
buf := &bytes.Buffer{}
|
user, err := json.Marshal(in)
|
||||||
err := json.NewEncoder(buf).Encode(&oaiRequest{
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
reqBody, err := json.Marshal(&oaiRequest{
|
||||||
Model: "gpt-4o",
|
Model: "gpt-4o",
|
||||||
Messages: []oaiMessage{
|
Messages: []oaiMessage{
|
||||||
{Role: "system", Content: system},
|
{Role: "system", Content: system},
|
||||||
{Role: "user", Content: user},
|
{Role: "user", Content: string(user)},
|
||||||
},
|
},
|
||||||
|
ResponseFormat: responseFormat,
|
||||||
})
|
})
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
req, err := http.NewRequest("POST", "https://api.openai.com/v1/chat/completions", buf)
|
req, err := http.NewRequest("POST", "https://api.openai.com/v1/chat/completions", bytes.NewReader(reqBody))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", oai.apiKey))
|
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", oai.apiKey))
|
||||||
@@ -72,23 +83,28 @@ func (oai *oaiClient) completeChat(system, user string) (string, error) {
|
|||||||
|
|
||||||
resp, err := oai.c.Do(req)
|
resp, err := oai.c.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
if resp.StatusCode != 200 {
|
if resp.StatusCode != 200 {
|
||||||
body, _ := io.ReadAll(resp.Body)
|
body, _ := io.ReadAll(resp.Body)
|
||||||
return "", fmt.Errorf("%s", string(body))
|
return fmt.Errorf("%s", string(body))
|
||||||
}
|
}
|
||||||
|
|
||||||
dec := json.NewDecoder(resp.Body)
|
dec := json.NewDecoder(resp.Body)
|
||||||
var res oaiResponse
|
res := &oaiResponse{}
|
||||||
|
|
||||||
err = dec.Decode(&res)
|
err = dec.Decode(res)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return res.Choices[0].Message.Content, nil
|
err = json.Unmarshal([]byte(res.Choices[0].Message.Content), out)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -211,6 +211,7 @@ a {
|
|||||||
<a href="javascript:(async function() {
|
<a href="javascript:(async function() {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
params.set('long', location.href);
|
params.set('long', location.href);
|
||||||
|
params.set('title', document.title);
|
||||||
|
|
||||||
window.open(`https://{{ .writeHost }}/?${params.toString()}`);
|
window.open(`https://{{ .writeHost }}/?${params.toString()}`);
|
||||||
})();">{{ .readHost }}</a>
|
})();">{{ .readHost }}</a>
|
||||||
|
|||||||
@@ -62,6 +62,8 @@ sl-icon[name="check-square-fill"] {
|
|||||||
/>
|
/>
|
||||||
<script type="module" src="https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.18.0/cdn/shoelace-autoloader.js"></script>
|
<script type="module" src="https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.18.0/cdn/shoelace-autoloader.js"></script>
|
||||||
<script>
|
<script>
|
||||||
|
let title = '{{ .title }}';
|
||||||
|
|
||||||
function setInputIcon(val, icon) {
|
function setInputIcon(val, icon) {
|
||||||
if (val.length > 0) {
|
if (val.length > 0) {
|
||||||
icon.setAttribute('name', 'square');
|
icon.setAttribute('name', 'square');
|
||||||
@@ -171,6 +173,10 @@ async function set(short, long) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
suggest(shorts, title);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function suggest(shorts, title) {
|
||||||
try {
|
try {
|
||||||
resp = await fetch('./', {
|
resp = await fetch('./', {
|
||||||
method: 'QUERY',
|
method: 'QUERY',
|
||||||
@@ -179,6 +185,7 @@ async function set(short, long) {
|
|||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
shorts: shorts,
|
shorts: shorts,
|
||||||
|
title: title,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -186,7 +193,9 @@ async function set(short, long) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const short of (await resp.json()).shorts) {
|
const data = await resp.json();
|
||||||
|
|
||||||
|
for (const short of data.shorts) {
|
||||||
appendShortItem(short, long);
|
appendShortItem(short, long);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -275,6 +284,7 @@ document.addEventListener('DOMContentLoaded', async () => {
|
|||||||
clearAlerts();
|
clearAlerts();
|
||||||
setInputIcons();
|
setInputIcons();
|
||||||
document.getElementById('tree').replaceChildren();
|
document.getElementById('tree').replaceChildren();
|
||||||
|
title = '';
|
||||||
|
|
||||||
if (longPaste) {
|
if (longPaste) {
|
||||||
longPaste = false;
|
longPaste = false;
|
||||||
@@ -310,6 +320,14 @@ document.addEventListener('DOMContentLoaded', async () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
setInputIcons();
|
setInputIcons();
|
||||||
|
|
||||||
|
const short = document.getElementById('short').value;
|
||||||
|
|
||||||
|
if (short != '') {
|
||||||
|
suggest([short], title);
|
||||||
|
} else if (title != '') {
|
||||||
|
suggest([], title);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
</head>
|
</head>
|
||||||
|
|||||||
Reference in New Issue
Block a user