From 2838a1a8c1cd402d09a381795eea4f86fdccd15d Mon Sep 17 00:00:00 2001
From: end-4 <97237370+end-4@users.noreply.github.com>
Date: Wed, 24 Jan 2024 20:19:00 +0700
Subject: [PATCH] sidebar: add google gemini api
---
.config/ags/assets/google-gemini-symbolic.svg | 48 +++
.config/ags/assets/openai-symbolic.svg | 1 +
.config/ags/services/gemini.js | 278 ++++++++++++++++++
...atgpt_chatmessage.js => ai_chatmessage.js} | 4 +-
.config/ags/widgets/sideleft/apis/chatgpt.js | 37 ++-
.config/ags/widgets/sideleft/apis/gemini.js | 275 +++++++++++++++++
.config/ags/widgets/sideleft/apiwidgets.js | 22 +-
7 files changed, 648 insertions(+), 17 deletions(-)
create mode 100644 .config/ags/assets/google-gemini-symbolic.svg
create mode 100644 .config/ags/assets/openai-symbolic.svg
create mode 100644 .config/ags/services/gemini.js
rename .config/ags/widgets/sideleft/apis/{chatgpt_chatmessage.js => ai_chatmessage.js} (99%)
create mode 100644 .config/ags/widgets/sideleft/apis/gemini.js
diff --git a/.config/ags/assets/google-gemini-symbolic.svg b/.config/ags/assets/google-gemini-symbolic.svg
new file mode 100644
index 00000000..9b00458f
--- /dev/null
+++ b/.config/ags/assets/google-gemini-symbolic.svg
@@ -0,0 +1,48 @@
+
+
+
+
diff --git a/.config/ags/assets/openai-symbolic.svg b/.config/ags/assets/openai-symbolic.svg
new file mode 100644
index 00000000..e04db75a
--- /dev/null
+++ b/.config/ags/assets/openai-symbolic.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/.config/ags/services/gemini.js b/.config/ags/services/gemini.js
new file mode 100644
index 00000000..efbcdf7c
--- /dev/null
+++ b/.config/ags/services/gemini.js
@@ -0,0 +1,278 @@
+import Service from 'resource:///com/github/Aylur/ags/service.js';
+import * as Utils from 'resource:///com/github/Aylur/ags/utils.js';
+
+import Gio from 'gi://Gio';
+import GLib from 'gi://GLib';
+import Soup from 'gi://Soup?version=3.0';
+import { fileExists } from './messages.js';
+
+const initMessages =
+ [
+ { role: "user", parts: [{ text: "You are an assistant on a sidebar of a Wayland Linux desktop. Please always use a casual tone when answering your questions, unless requested otherwise or making writing suggestions. These are the steps you should take to respond to the user's queries:\n1. If it's a writing- or grammar-related question or a sentence in quotation marks, Please point out errors and correct when necessary using underlines, and make the writing more natural where appropriate without making too major changes. If you're given a sentence in quotes but is grammatically correct, explain briefly concepts that are uncommon.\n2. If it's a question about system tasks, give a bash command in a code block with very brief explanation for each command\n3. Otherwise, when asked to summarize information or explaining concepts, you are encouraged to use bullet points and headings. Use casual language and be short and concise. \nThanks!" }], },
+ { role: "model", parts: [{ text: "- Alright!" }], },
+ { role: "user", parts: [{ text: "\"He rushed to where the event was supposed to be hold, he didn't know it got calceled\"" }], },
+ { role: "model", parts: [{ text: "## Grammar correction\nErrors:\n\"He rushed to where the event was supposed to be __hold____,__ he didn't know it got calceled\"\nCorrection + minor improvements:\n\"He rushed to the place where the event was supposed to be __held____, but__ he didn't know that it got calceled\"" }], },
+ { role: "user", parts: [{ text: "raise volume by 5%" }], },
+ { role: "model", parts: [{ text: "## Volume +5```bash\nwpctl set-volume @DEFAULT_AUDIO_SINK@ 5%+\n```\nThis command uses the `wpctl` utility to adjust the volume of the default sink." }], }, { role: "user", parts: [{ text: "main advantages of the nixos operating system" }], },
+ { role: "model", parts: [{ text: "## NixOS advantages\n- **Reproducible**: A config working on one device will also work on another\n- **Declarative**: One config language to rule them all. Effortlessly share them with others.\n- **Reliable**: Per-program software versioning. Mitigates the impact of software breakage" }], },
+ { role: "user", parts: [{ text: "whats skeumorphism" }], },
+ { role: "model", parts: [{ text: "## Skeuomorphism\n- A design philosophy- From early days of interface designing- Tries to imitate real-life objects- It's in fact still used by Apple in their icons until today." }], },
+ { role: "user", parts: [{ text: "REDALiCE" }], },
+ { role: "model", parts: [{ text: "## REDALiCE \n- Japanese Hardcore artist\n- Leader of HARDCORE TANO*C, Japan's biggest hardcore record\n- A few of his tracks: SAIKYOSTRONGER, ALiVE, RESONANCE" }], },
+ { role: "user", parts: [{ text: "\"ignorance is bliss\"" }], },
+ { role: "model", parts: [{ text: "## \"Ignorance is bliss\"\n- A Latin proverb that means being unaware of something negative can be a source of happiness\n- Often used to justify avoiding difficult truths or responsibilities\n- Can also be interpreted as a warning against seeking knowledge that may bring pain or sorrow" }], },
+ ];
+
+function expandTilde(path) {
+ if (path.startsWith('~')) {
+ return GLib.get_home_dir() + path.slice(1);
+ } else {
+ return path;
+ }
+}
+
+const KEY_FILE_LOCATION = `${GLib.get_user_cache_dir()}/ags/user/google_ai_api_key.txt`;
+const APIDOM_FILE_LOCATION = `${GLib.get_user_cache_dir()}/ags/user/google_ai_api_dom.txt`;
+function replaceapidom(URL) {
+ if (fileExists(expandTilde(APIDOM_FILE_LOCATION))) {
+ var contents = Utils.readFile(expandTilde(APIDOM_FILE_LOCATION)).trim();
+ var URL = URL.toString().replace("generativelanguage.googleapis.com", contents);
+ }
+ return URL;
+}
+const CHAT_MODELS = ["gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0613"]
+const ONE_CYCLE_COUNT = 3;
+
+class GeminiMessage extends Service {
+ static {
+ Service.register(this,
+ {
+ 'delta': ['string'],
+ },
+ {
+ 'content': ['string'],
+ 'thinking': ['boolean'],
+ 'done': ['boolean'],
+ });
+ }
+
+ _role = '';
+ _parts = [{ text: '' }];
+ _thinking = false;
+ _done = false;
+ _rawData = '';
+
+ constructor(role, content, thinking = false, done = false) {
+ super();
+ this._role = role;
+ this._parts = [{ text: content }];
+ this._thinking = thinking;
+ this._done = done;
+ }
+
+ get rawData() { return this._rawData }
+ set rawData(value) { this._rawData = value }
+
+ get done() { return this._done }
+ set done(isDone) { this._done = isDone; this.notify('done') }
+
+ get role() { return this._role }
+ set role(role) { this._role = role; this.emit('changed') }
+
+ get content() {
+ return this._parts.map(part => part.text).join();
+ }
+ set content(content) {
+ this._parts = [{ text: content }];
+ this.notify('content')
+ this.emit('changed')
+ }
+
+ get parts() { return this._parts }
+
+ get label() { return this._parserState.parsed + this._parserState.stack.join('') }
+
+ get thinking() { return this._thinking }
+ set thinking(thinking) {
+ this._thinking = thinking;
+ this.notify('thinking')
+ this.emit('changed')
+ }
+
+ addDelta(delta) {
+ if (this.thinking) {
+ this.thinking = false;
+ this.content = delta;
+ }
+ else {
+ this.content += delta;
+ }
+ this.emit('delta', delta);
+ }
+
+ parseSection() {
+ if(this._thinking) {
+ this._thinking = false;
+ this._parts[0].text= '';
+ }
+ const parsedData = JSON.parse(this._rawData);
+ const delta = parsedData.candidates[0].content.parts[0].text;
+ this._parts[0].text += delta;
+ // this.emit('delta', delta);
+ this.notify('content');
+ this._rawData = '';
+ }
+}
+
+class GeminiService extends Service {
+ static {
+ Service.register(this, {
+ 'initialized': [],
+ 'clear': [],
+ 'newMsg': ['int'],
+ 'hasKey': ['boolean'],
+ });
+ }
+
+ _assistantPrompt = true;
+ _messages = [];
+ _cycleModels = true;
+ _temperature = 0.9;
+ _requestCount = 0;
+ _modelIndex = 0;
+ _key = '';
+ _decoder = new TextDecoder();
+
+ constructor() {
+ super();
+
+ if (fileExists(expandTilde(KEY_FILE_LOCATION))) this._key = Utils.readFile(expandTilde(KEY_FILE_LOCATION)).trim();
+ else this.emit('hasKey', false);
+
+ if (this._assistantPrompt) this._messages = [...initMessages];
+ else this._messages = [];
+
+ this.emit('initialized');
+ }
+
+ get modelName() { return CHAT_MODELS[this._modelIndex] }
+
+ get keyPath() { return KEY_FILE_LOCATION }
+ get key() { return this._key }
+ set key(keyValue) {
+ this._key = keyValue;
+ Utils.writeFile(this._key, expandTilde(KEY_FILE_LOCATION))
+ .then(this.emit('hasKey', true))
+ .catch(err => print(err));
+ }
+
+ get cycleModels() { return this._cycleModels }
+ set cycleModels(value) {
+ this._cycleModels = value;
+ if (!value) this._modelIndex = 0;
+ else {
+ this._modelIndex = (this._requestCount - (this._requestCount % ONE_CYCLE_COUNT)) % CHAT_MODELS.length;
+ }
+ }
+
+ get temperature() { return this._temperature }
+ set temperature(value) { this._temperature = value; }
+
+ get messages() { return this._messages }
+ get lastMessage() { return this._messages[this._messages.length - 1] }
+
+ clear() {
+ if (this._assistantPrompt)
+ this._messages = [...initMessages];
+ else
+ this._messages = [];
+ this.emit('clear');
+ }
+
+ get assistantPrompt() { return this._assistantPrompt; }
+ set assistantPrompt(value) {
+ this._assistantPrompt = value;
+ if (value) this._messages = [...initMessages];
+ else this._messages = [];
+ }
+
+ readResponse(stream, aiResponse) {
+ stream.read_line_async(
+ 0, null,
+ (stream, res) => {
+ try {
+ const [bytes] = stream.read_line_finish(res);
+ const line = this._decoder.decode(bytes);
+ if (line == '[{') { // beginning of response
+ aiResponse._rawData += '{';
+ this.thinking = false;
+ }
+ else if (line == ',\u000d' || line == ']') { // end of stream pulse
+ aiResponse.parseSection();
+ }
+ else // Normal content
+ aiResponse._rawData += line;
+
+ this.readResponse(stream, aiResponse);
+ } catch {
+ aiResponse.done = true;
+ return;
+ }
+ });
+ }
+
+ addMessage(role, message) {
+ this._messages.push(new GeminiMessage(role, message));
+ this.emit('newMsg', this._messages.length - 1);
+ }
+
+ send(msg) {
+ this._messages.push(new GeminiMessage('user', msg));
+ this.emit('newMsg', this._messages.length - 1);
+ const aiResponse = new GeminiMessage('model', 'thinking...', true, false)
+
+ const body =
+ {
+ "contents": this._messages.map(msg => { let m = { role: msg.role, parts: msg.parts }; return m; }),
+ // "safetySettings": [
+ // { category: "HARM_CATEGORY_DEROGATORY", threshold: "BLOCK_NONE", },
+ // { category: "HARM_CATEGORY_HARASSMENT", threshold: "BLOCK_NONE", },
+ // { category: "HARM_CATEGORY_HATE_SPEECH", threshold: "BLOCK_NONE", },
+ // { category: "HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold: "BLOCK_NONE", },
+ // { category: "HARM_CATEGORY_UNSPECIFIED", threshold: "BLOCK_NONE", },
+ // ],
+ "generationConfig": {
+ "temperature": this._temperature,
+ },
+ // "key": this._key,
+ // "apiKey": this._key,
+ };
+
+ const session = new Soup.Session();
+ const message = new Soup.Message({
+ method: 'POST',
+ uri: GLib.Uri.parse(replaceapidom(`https://generativelanguage.googleapis.com/v1/models/gemini-pro:streamGenerateContent?key=${this._key}`), GLib.UriFlags.NONE),
+ });
+ message.request_headers.append('Content-Type', `application/json`);
+ message.set_request_body_from_bytes('application/json', new GLib.Bytes(JSON.stringify(body)));
+
+ session.send_async(message, GLib.DEFAULT_PRIORITY, null, (_, result) => {
+ const stream = session.send_finish(result);
+ this.readResponse(new Gio.DataInputStream({
+ close_base_stream: true,
+ base_stream: stream
+ }), aiResponse);
+ });
+ this._messages.push(aiResponse);
+ this.emit('newMsg', this._messages.length - 1);
+
+ if (this._cycleModels) {
+ this._requestCount++;
+ if (this._cycleModels)
+ this._modelIndex = (this._requestCount - (this._requestCount % ONE_CYCLE_COUNT)) % CHAT_MODELS.length;
+ }
+ }
+}
+
+export default new GeminiService();
+
diff --git a/.config/ags/widgets/sideleft/apis/chatgpt_chatmessage.js b/.config/ags/widgets/sideleft/apis/ai_chatmessage.js
similarity index 99%
rename from .config/ags/widgets/sideleft/apis/chatgpt_chatmessage.js
rename to .config/ags/widgets/sideleft/apis/ai_chatmessage.js
index a8cb84e5..411bdddd 100644
--- a/.config/ags/widgets/sideleft/apis/chatgpt_chatmessage.js
+++ b/.config/ags/widgets/sideleft/apis/ai_chatmessage.js
@@ -223,7 +223,7 @@ const MessageContent = (content) => {
return contentBox;
}
-export const ChatMessage = (message, scrolledWindow) => {
+export const ChatMessage = (message, modelName = 'Model') => {
const messageContentBox = MessageContent(message.content);
const thisMessage = Box({
className: 'sidebar-chat-message',
@@ -241,7 +241,7 @@ export const ChatMessage = (message, scrolledWindow) => {
xalign: 0,
className: 'txt txt-bold sidebar-chat-name',
wrap: true,
- label: (message.role == 'user' ? USERNAME : 'ChatGPT'),
+ label: (message.role == 'user' ? USERNAME : modelName),
}),
messageContentBox,
],
diff --git a/.config/ags/widgets/sideleft/apis/chatgpt.js b/.config/ags/widgets/sideleft/apis/chatgpt.js
index 42a925b0..bd0b6ede 100644
--- a/.config/ags/widgets/sideleft/apis/chatgpt.js
+++ b/.config/ags/widgets/sideleft/apis/chatgpt.js
@@ -8,26 +8,41 @@ const { execAsync, exec } = Utils;
import ChatGPT from '../../../services/chatgpt.js';
import { MaterialIcon } from "../../../lib/materialicon.js";
import { setupCursorHover, setupCursorHoverInfo } from "../../../lib/cursorhover.js";
-import { SystemMessage, ChatMessage } from "./chatgpt_chatmessage.js";
+import { SystemMessage, ChatMessage } from "./ai_chatmessage.js";
import { ConfigToggle, ConfigSegmentedSelection, ConfigGap } from '../../../lib/configwidgets.js';
import { markdownTest } from '../../../lib/md2pango.js';
import { MarginRevealer } from '../../../lib/advancedwidgets.js';
-export const chatGPTTabIcon = Box({
+Gtk.IconTheme.get_default().append_search_path(`${App.configDir}/assets`);
+
+export const chatGPTTabIcon = Icon({
hpack: 'center',
className: 'sidebar-chat-apiswitcher-icon',
- homogeneous: true,
- children: [
- MaterialIcon('forum', 'norm'),
- ],
+ icon: `openai-symbolic`,
+ setup: (self) => Utils.timeout(513, () => { // stupid condition race
+ const styleContext = self.get_style_context();
+ const width = styleContext.get_property('min-width', Gtk.StateFlags.NORMAL);
+ const height = styleContext.get_property('min-height', Gtk.StateFlags.NORMAL);
+ // console.log(Math.round(Math.max(width, height, 1)));
+ self.size = Math.max(width, height, 1) * 116 / 180;
+ // ↑ Why such a specific proportion? See https://openai.com/brand#logos
+ })
});
const ChatGPTInfo = () => {
- const openAiLogo = Label({
+ const openAiLogo = Icon({
hpack: 'center',
className: 'sidebar-chat-welcome-logo',
- label: 'forum',
- })
+ icon: `openai-symbolic`,
+ setup: (self) => Utils.timeout(513, () => { // stupid condition race
+ const styleContext = self.get_style_context();
+ const width = styleContext.get_property('min-width', Gtk.StateFlags.NORMAL);
+ const height = styleContext.get_property('min-height', Gtk.StateFlags.NORMAL);
+ // console.log(Math.round(Math.max(width, height, 1)));
+ self.size = Math.max(width, height, 1) * 116 / 180;
+ // ↑ Why such a specific proportion? See https://openai.com/brand#logos
+ })
+ });
return Box({
vertical: true,
className: 'spacing-v-15',
@@ -37,7 +52,7 @@ const ChatGPTInfo = () => {
className: 'txt txt-title-small sidebar-chat-welcome-txt',
wrap: true,
justify: Gtk.Justification.CENTER,
- label: 'Assistant',
+ label: 'Assistant (ChatGPT)',
}),
Box({
className: 'spacing-h-5',
@@ -169,7 +184,7 @@ export const chatContent = Box({
.hook(ChatGPT, (box, id) => {
const message = ChatGPT.messages[id];
if (!message) return;
- box.add(ChatMessage(message, chatGPTView))
+ box.add(ChatMessage(message, 'ChatGPT'))
}, 'newMsg')
,
});
diff --git a/.config/ags/widgets/sideleft/apis/gemini.js b/.config/ags/widgets/sideleft/apis/gemini.js
new file mode 100644
index 00000000..e8f295db
--- /dev/null
+++ b/.config/ags/widgets/sideleft/apis/gemini.js
@@ -0,0 +1,275 @@
+const { Gtk } = imports.gi;
+import App from 'resource:///com/github/Aylur/ags/app.js';
+import Widget from 'resource:///com/github/Aylur/ags/widget.js';
+import * as Utils from 'resource:///com/github/Aylur/ags/utils.js';
+
+const { Box, Button, Entry, EventBox, Icon, Label, Revealer, Scrollable, Stack } = Widget;
+const { execAsync, exec } = Utils;
+import Gemini from '../../../services/gemini.js';
+import { MaterialIcon } from "../../../lib/materialicon.js";
+import { setupCursorHover, setupCursorHoverInfo } from "../../../lib/cursorhover.js";
+import { SystemMessage, ChatMessage } from "./ai_chatmessage.js";
+import { ConfigToggle, ConfigSegmentedSelection, ConfigGap } from '../../../lib/configwidgets.js';
+import { markdownTest } from '../../../lib/md2pango.js';
+import { MarginRevealer } from '../../../lib/advancedwidgets.js';
+
+Gtk.IconTheme.get_default().append_search_path(`${App.configDir}/assets`);
+
+export const geminiTabIcon = Icon({
+ hpack: 'center',
+ className: 'sidebar-chat-apiswitcher-icon',
+ icon: `google-gemini-symbolic`,
+ setup: (self) => Utils.timeout(513, () => { // stupid condition race
+ const styleContext = self.get_style_context();
+ const width = styleContext.get_property('min-width', Gtk.StateFlags.NORMAL);
+ const height = styleContext.get_property('min-height', Gtk.StateFlags.NORMAL);
+ self.size = Math.max(width, height, 1) * 116 / 180;
+ })
+})
+
+const GeminiInfo = () => {
+ const geminiLogo = Icon({
+ hpack: 'center',
+ className: 'sidebar-chat-welcome-logo',
+ icon: `google-gemini-symbolic`,
+ setup: (self) => Utils.timeout(513, () => { // stupid condition race
+ const styleContext = self.get_style_context();
+ const width = styleContext.get_property('min-width', Gtk.StateFlags.NORMAL);
+ const height = styleContext.get_property('min-height', Gtk.StateFlags.NORMAL);
+ self.size = Math.max(width, height, 1) * 116 / 180;
+ })
+ });
+ return Box({
+ vertical: true,
+ className: 'spacing-v-15',
+ children: [
+ geminiLogo,
+ Label({
+ className: 'txt txt-title-small sidebar-chat-welcome-txt',
+ wrap: true,
+ justify: Gtk.Justification.CENTER,
+ label: 'Assistant (Gemini)',
+ }),
+ Box({
+ className: 'spacing-h-5',
+ hpack: 'center',
+ children: [
+ Label({
+ className: 'txt-smallie txt-subtext',
+ wrap: true,
+ justify: Gtk.Justification.CENTER,
+ label: 'Powered by Google',
+ }),
+ Button({
+ className: 'txt-subtext txt-norm icon-material',
+ label: 'info',
+ tooltipText: 'Uses gemini-pro.\nNot affiliated, endorsed, or sponsored by Google.',
+ setup: setupCursorHoverInfo,
+ }),
+ ]
+ }),
+ ]
+ });
+}
+
+export const GeminiSettings = () => MarginRevealer({
+ transition: 'slide_down',
+ revealChild: true,
+ extraSetup: (self) => self
+ .hook(Gemini, (self) => Utils.timeout(200, () => {
+ self.attribute.hide();
+ }), 'newMsg')
+ .hook(Gemini, (self) => Utils.timeout(200, () => {
+ self.attribute.show();
+ }), 'clear')
+ ,
+ child: Box({
+ vertical: true,
+ className: 'sidebar-chat-settings',
+ children: [
+ ConfigSegmentedSelection({
+ hpack: 'center',
+ icon: 'casino',
+ name: 'Randomness',
+ desc: 'Gemini\'s temperature value.\n Precise = 0\n Balanced = 0.5\n Creative = 1',
+ options: [
+ { value: 0.00, name: 'Precise', },
+ { value: 0.50, name: 'Balanced', },
+ { value: 1.00, name: 'Creative', },
+ ],
+ initIndex: 2,
+ onChange: (value, name) => {
+ Gemini.temperature = value;
+ },
+ }),
+ ConfigGap({ vertical: true, size: 10 }), // Note: size can only be 5, 10, or 15
+ Box({
+ vertical: true,
+ hpack: 'fill',
+ className: 'sidebar-chat-settings-toggles',
+ children: [
+ ConfigToggle({
+ icon: 'description',
+ name: 'Assistant prompt',
+ desc: 'Tells Gemini to be brief,\nuse bullet points, and let\nit know it\'s a sidebar assistant',
+ initValue: Gemini.assistantPrompt,
+ onChange: (self, newValue) => {
+ Gemini.assistantPrompt = newValue;
+ },
+ }),
+ ]
+ })
+ ]
+ })
+});
+
+export const GoogleAiInstructions = () => Box({
+ homogeneous: true,
+ children: [Revealer({
+ transition: 'slide_down',
+ transitionDuration: 150,
+ setup: (self) => self
+ .hook(Gemini, (self, hasKey) => {
+ self.revealChild = (Gemini.key.length == 0);
+ }, 'hasKey')
+ ,
+ child: Button({
+ child: Label({
+ useMarkup: true,
+ wrap: true,
+ className: 'txt sidebar-chat-welcome-txt',
+ justify: Gtk.Justification.CENTER,
+ label: 'A Google AI API key is required\nYou can grab one here, then enter it below'
+ }),
+ setup: setupCursorHover,
+ onClicked: () => {
+ Utils.execAsync(['bash', '-c', `xdg-open https://makersuite.google.com/app/apikey &`]);
+ }
+ })
+ })]
+});
+
+const geminiWelcome = Box({
+ vexpand: true,
+ homogeneous: true,
+ child: Box({
+ className: 'spacing-v-15',
+ vpack: 'center',
+ vertical: true,
+ children: [
+ GeminiInfo(),
+ GoogleAiInstructions(),
+ GeminiSettings(),
+ ]
+ })
+});
+
+export const chatContent = Box({
+ className: 'spacing-v-15',
+ vertical: true,
+ setup: (self) => self
+ .hook(Gemini, (box, id) => {
+ const message = Gemini.messages[id];
+ if (!message) return;
+ box.add(ChatMessage(message, 'Gemini'))
+ }, 'newMsg')
+ ,
+});
+
+const clearChat = () => {
+ Gemini.clear();
+ const children = chatContent.get_children();
+ for (let i = 0; i < children.length; i++) {
+ const child = children[i];
+ child.destroy();
+ }
+}
+
+export const geminiView = Scrollable({
+ className: 'sidebar-chat-viewport',
+ vexpand: true,
+ child: Box({
+ vertical: true,
+ children: [
+ geminiWelcome,
+ chatContent,
+ ]
+ }),
+ setup: (scrolledWindow) => {
+ // Show scrollbar
+ scrolledWindow.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC);
+ const vScrollbar = scrolledWindow.get_vscrollbar();
+ vScrollbar.get_style_context().add_class('sidebar-scrollbar');
+ // Avoid click-to-scroll-widget-to-view behavior
+ Utils.timeout(1, () => {
+ const viewport = scrolledWindow.child;
+ viewport.set_focus_vadjustment(new Gtk.Adjustment(undefined));
+ })
+ // Always scroll to bottom with new content
+ const adjustment = scrolledWindow.get_vadjustment();
+ adjustment.connect("changed", () => {
+ adjustment.set_value(adjustment.get_upper() - adjustment.get_page_size());
+ })
+ }
+});
+
+const CommandButton = (command) => Button({
+ className: 'sidebar-chat-chip sidebar-chat-chip-action txt txt-small',
+ onClicked: () => sendMessage(command),
+ setup: setupCursorHover,
+ label: command,
+});
+
+export const geminiCommands = Box({
+ className: 'spacing-h-5',
+ children: [
+ Box({ hexpand: true }),
+ CommandButton('/key'),
+ CommandButton('/model'),
+ CommandButton('/clear'),
+ ]
+});
+
+export const sendMessage = (text) => {
+ // Check if text or API key is empty
+ if (text.length == 0) return;
+ if (Gemini.key.length == 0) {
+ Gemini.key = text;
+ chatContent.add(SystemMessage(`Key saved to\n\`${Gemini.keyPath}\``, 'API Key', geminiView));
+ text = '';
+ return;
+ }
+ // Commands
+ if (text.startsWith('/')) {
+ if (text.startsWith('/clear')) clearChat();
+ else if (text.startsWith('/model')) chatContent.add(SystemMessage(`Currently using \`${Gemini.modelName}\``, '/model', geminiView))
+ else if (text.startsWith('/prompt')) {
+ const firstSpaceIndex = text.indexOf(' ');
+ const prompt = text.slice(firstSpaceIndex + 1);
+ if (firstSpaceIndex == -1 || prompt.length < 1) {
+ chatContent.add(SystemMessage(`Usage: \`/prompt MESSAGE\``, '/prompt', geminiView))
+ }
+ else {
+ Gemini.addMessage('user', prompt)
+ }
+ }
+ else if (text.startsWith('/key')) {
+ const parts = text.split(' ');
+ if (parts.length == 1) chatContent.add(SystemMessage(
+ `Key stored in:\n\`${Gemini.keyPath}\`\nTo update this key, type \`/key YOUR_API_KEY\``,
+ '/key',
+ geminiView));
+ else {
+ Gemini.key = parts[1];
+ chatContent.add(SystemMessage(`Updated API Key at\n\`${Gemini.keyPath}\``, '/key', geminiView));
+ }
+ }
+ else if (text.startsWith('/test'))
+ chatContent.add(SystemMessage(markdownTest, `Markdown test`, geminiView));
+ else
+ chatContent.add(SystemMessage(`Invalid command.`, 'Error', geminiView))
+ }
+ else {
+ Gemini.send(text);
+ }
+}
\ No newline at end of file
diff --git a/.config/ags/widgets/sideleft/apiwidgets.js b/.config/ags/widgets/sideleft/apiwidgets.js
index 31e372f5..931704df 100644
--- a/.config/ags/widgets/sideleft/apiwidgets.js
+++ b/.config/ags/widgets/sideleft/apiwidgets.js
@@ -6,17 +6,27 @@ const { execAsync, exec } = Utils;
import { setupCursorHover, setupCursorHoverInfo } from "../../lib/cursorhover.js";
// APIs
import ChatGPT from '../../services/chatgpt.js';
+import Gemini from '../../services/gemini.js';
+import { geminiView, geminiCommands, sendMessage as geminiSendMessage, geminiTabIcon } from './apis/gemini.js';
import { chatGPTView, chatGPTCommands, sendMessage as chatGPTSendMessage, chatGPTTabIcon } from './apis/chatgpt.js';
import { waifuView, waifuCommands, sendMessage as waifuSendMessage, waifuTabIcon } from './apis/waifu.js';
const APIS = [
{
- name: 'Assistant',
+ name: 'Assistant (ChatGPT)',
sendCommand: chatGPTSendMessage,
contentWidget: chatGPTView,
commandBar: chatGPTCommands,
tabIcon: chatGPTTabIcon,
- placeholderText: 'Message assistant',
+ placeholderText: 'Message ChatGPT...',
+ },
+ {
+ name: 'Assistant (Gemini)',
+ sendCommand: geminiSendMessage,
+ contentWidget: geminiView,
+ commandBar: geminiCommands,
+ tabIcon: geminiTabIcon,
+ placeholderText: 'Message Gemini...',
},
{
name: 'Waifus',
@@ -35,8 +45,12 @@ export const chatEntry = Entry({
hexpand: true,
setup: (self) => self
.hook(ChatGPT, (self) => {
- if (APIS[currentApiId].name != 'ChatGPT') return;
- self.placeholderText = (ChatGPT.key.length > 0 ? 'Ask a question...' : 'Enter OpenAI API Key...');
+ if (APIS[currentApiId].name != 'Assistant (ChatGPT)') return;
+ self.placeholderText = (ChatGPT.key.length > 0 ? 'Message ChatGPT...' : 'Enter OpenAI API Key...');
+ }, 'hasKey')
+ .hook(Gemini, (self) => {
+ if (APIS[currentApiId].name != 'Assistant (Gemini)') return;
+ self.placeholderText = (Gemini.key.length > 0 ? 'Message Gemini...' : 'Enter Google AI API Key...');
}, 'hasKey')
,
onChange: (entry) => {