Skip to content

Commit

Permalink
feat: assistant add prompt templates #454 (#847)
Browse files Browse the repository at this point in the history
  • Loading branch information
mikbry committed Apr 30, 2024
1 parent 61e25c2 commit a06fada
Show file tree
Hide file tree
Showing 7 changed files with 183 additions and 12 deletions.
11 changes: 8 additions & 3 deletions webapp/components/views/AssistantsStore/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,14 @@ function AssistantsStore() {
}
}
newAssistant = createAssistant(assistant.name, { ...assistant, targets, readonly: true });
}
if (newAssistant.hidden) {
} else {
newAssistant.hidden = false;
updateAssistant(newAssistant);
updateAssistant({
...newAssistant,
...assistant,
targets: newAssistant.targets,
readonly: true,
});
}
router.push(`${Ui.Page.Threads}/?assistant=${assistant.id}`);
};
Expand All @@ -107,6 +111,7 @@ function AssistantsStore() {
() => collection.filter((assistant) => search(query, assistant)),
[collection, query],
);

return (
<Threads onSelectMenu={() => {}} onShouldDelete={() => {}} onResizeExplorer={() => {}}>
<ResizablePanel id="assistant-store">
Expand Down
118 changes: 118 additions & 0 deletions webapp/components/views/Threads/Conversation/Onboarding.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
// Copyright 2024 mik
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { PromptTemplate, Ui } from '@/types';
import { MenuAction } from '@/types/ui';
import useTranslation from '@/hooks/useTranslation';
import EmptyView from '@/components/common/EmptyView';
import Opla from '@/components/icons/Opla';
import { useAssistantStore } from '@/stores';
import AvatarView from '@/components/common/AvatarView';
import PromptsGrid from './PromptsGrid';

export type OnboardingProps = {
selectedAssistantId: string | undefined;
selectedModelName: string | undefined;
hasModels: boolean;
disabled: boolean;
onSelectMenu: (menu: MenuAction, data: string) => void;
onPromptSelected: (prompt: PromptTemplate) => void;
};

function Onboarding({
selectedAssistantId,
selectedModelName,
hasModels,
disabled,
onSelectMenu,
onPromptSelected,
}: OnboardingProps) {
const { t } = useTranslation();
const { getAssistant } = useAssistantStore();

const assistant = getAssistant(selectedAssistantId);

let actions: Ui.MenuItem[] | undefined;
let buttonLabel: string | undefined;
let description = t(
"Welcome to Opla! Our platform leverages the power of your device to deliver personalized AI assistance. To kick things off, you'll need to install a model or an assistant. Think of it like choosing your conversation partner. If you've used ChatGPT before, you'll feel right at home here. Remember, this step is essential to begin your journey with Opla. Let's get started!",
);
if (assistant) {
description = assistant?.description || t('Opla works using your machine processing power.');
} else if (selectedModelName) {
buttonLabel = t('Start a conversation');
description = t('Opla works using your machine processing power.');
} else if (hasModels) {
description = t('Opla works using your machine processing power.');
} else {
actions = [
{
label: t('Choose an assistant'),
onSelect: (data: string) => onSelectMenu(MenuAction.ChooseAssistant, data),
value: 'choose_assistant',
description:
'Opt for a specialized AI agent or GPT to navigate and enhance your daily activities. These assistants can utilize both local models and external services like OpenAI, offering versatile support.',
},
{
label: t('Install a local model'),
onSelect: (data: string) => onSelectMenu(MenuAction.InstallModel, data),
value: 'install_model',
variant: 'outline',
description:
'Incorporate an open-source Large Language Model (LLM) such as Gemma or LLama2 directly onto your device. Dive into the world of advanced generative AI and unlock new experimental possibilities.',
},
{
label: t('Use OpenAI'),
onSelect: (data: string) => onSelectMenu(MenuAction.ConfigureOpenAI, data),
value: 'configure_openai',
variant: 'ghost',
description:
'Integrate using your OpenAI API key to import ChatGPT conversations and tap into the extensive capabilities of OpenAI. Experience the contrast with local AI solutions. Remember, ChatGPT operates remotely and at a cost!',
},
];
}

return (
<div className="flex grow flex-col">
<EmptyView
className="m-2 flex grow"
title={
assistant?.title ||
assistant?.name ||
t('Empower Your Productivity with Local AI Assistants')
}
description={description}
buttonLabel={disabled ? buttonLabel : undefined}
icon={
assistant ? (
<AvatarView avatar={assistant.avatar} className="h-10 w-10" />
) : (
<Opla className="h-10 w-10 animate-pulse" />
)
}
actions={actions}
/>
{(selectedAssistantId || selectedModelName) && (
<PromptsGrid
assistantPrompts={assistant ? assistant?.promptTemplates || [] : undefined}
onPromptSelected={onPromptSelected}
disabled={disabled}
className="pb-4"
/>
)}
</div>
);
}

export default Onboarding;
8 changes: 7 additions & 1 deletion webapp/components/views/Threads/Conversation/PromptsGrid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,20 @@ import PromptCard from '../../../common/PromptCard';

function PromptsGrid({
className,
assistantPrompts,
onPromptSelected,
disabled,
}: {
className?: string;
assistantPrompts: PromptTemplate[] | undefined;
onPromptSelected: (prompt: PromptTemplate) => void;
disabled: boolean;
}) {
const [prompts] = useFetch<PromptTemplate[]>('https://opla.github.io/prompts/default.json');
const [defaultPrompts] = useFetch<PromptTemplate[]>(
'https://opla.github.io/prompts/default.json',
);

const prompts = assistantPrompts || defaultPrompts;

return (
<div
Expand Down
24 changes: 17 additions & 7 deletions webapp/components/views/Threads/Conversation/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,20 @@
// limitations under the License.

import { useEffect, useState } from 'react';
import EmptyView from '@/components/common/EmptyView';
import useTranslation from '@/hooks/useTranslation';
// import EmptyView from '@/components/common/EmptyView';
// import useTranslation from '@/hooks/useTranslation';
import { KeyedScrollPosition } from '@/hooks/useScroll';
import Opla from '@/components/icons/Opla';
// import Opla from '@/components/icons/Opla';
import { AvatarRef, Conversation, Message, MessageImpl, PromptTemplate, Ui } from '@/types';
// import logger from '@/utils/logger';
import useBackend from '@/hooks/useBackendContext';
import { MenuAction, Page, ViewName } from '@/types/ui';
import logger from '@/utils/logger';
import ConversationList from './ConversationList';
import PromptsGrid from './PromptsGrid';
// import PromptsGrid from './PromptsGrid';
import { useConversationContext } from './ConversationContext';
import { usePromptContext } from '../Prompt/PromptContext';
import Onboarding from './Onboarding';

export type ConversationPanelProps = {
selectedConversation: Conversation | undefined;
Expand All @@ -47,15 +48,14 @@ export function ConversationPanel({
selectedConversation,
selectedAssistantId,
selectedModelName,

modelItems,
disabled,
onDeleteMessage,
onDeleteAssets,
onSelectMenu,
onCopyMessage,
}: ConversationPanelProps) {
const { t } = useTranslation();
// const { t } = useTranslation();
const { config, setSettings } = useBackend();
const {
selectedMessageId,
Expand Down Expand Up @@ -120,7 +120,7 @@ export function ConversationPanel({

const showEmptyChat = !conversationId || !messages || messages.length === 0;
if (showEmptyChat) {
let actions: Ui.MenuItem[] | undefined;
/* let actions: Ui.MenuItem[] | undefined;
let buttonLabel: string | undefined;
let description = t(
"Welcome to Opla! Our platform leverages the power of your device to deliver personalized AI assistance. To kick things off, you'll need to install a model or an assistant. Think of it like choosing your conversation partner. If you've used ChatGPT before, you'll feel right at home here. Remember, this step is essential to begin your journey with Opla. Let's get started!",
Expand Down Expand Up @@ -177,6 +177,16 @@ export function ConversationPanel({
/>
)}
</div>
); */
return (
<Onboarding
selectedAssistantId={selectedAssistantId}
selectedModelName={selectedModelName}
hasModels={modelItems.length > 0}
disabled={disabled}
onSelectMenu={onSelectMenu}
onPromptSelected={handlePromptTemplateSelected}
/>
);
}
return (
Expand Down
4 changes: 3 additions & 1 deletion webapp/native/src/data/assistant/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use serde::{ self, Deserialize, Serialize };
use serde_with::{ serde_as, OneOrMany, formats::PreferOne };
use crate::data::{ option_date_format, option_string_or_struct };

use super::{ Avatar, Entity, Preset, Resource };
use super::{ Avatar, Entity, Preset, PromptTemplates, Resource };

#[serde_as]
#[serde_with::skip_serializing_none]
Expand Down Expand Up @@ -90,4 +90,6 @@ pub struct Assistant {
pub system: Option<String>,

pub targets: Option<Vec<Preset>>,

pub prompt_templates: Option<Vec<PromptTemplates>>,
}
17 changes: 17 additions & 0 deletions webapp/native/src/data/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

use chrono::{ DateTime, Utc };
use serde::{ self, Deserialize, Deserializer, Serialize };
use serde_with::{ serde_as, OneOrMany, formats::PreferOne };
use std::{collections::HashMap, fmt};
use std::marker::PhantomData;
use std::str::FromStr;
Expand Down Expand Up @@ -51,6 +52,22 @@ pub struct Preset {
pub parameters: Option<HashMap<String, Option<PresetParameter>>>,
}

#[serde_as]
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PromptTemplates {
pub id: Option<String>,
pub title: String,
pub icon: Option<Avatar>,
#[serde(with = "option_date_format", skip_serializing_if = "Option::is_none", default)]
pub created_at: Option<DateTime<Utc>>,
#[serde(with = "option_date_format", skip_serializing_if = "Option::is_none", default)]
pub updated_at: Option<DateTime<Utc>>,
pub value: Option<String>,
#[serde_as(deserialize_as = "Option<OneOrMany<_, PreferOne>>")]
pub tags: Option<Vec<String>>,
}

#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Avatar {
Expand Down
13 changes: 13 additions & 0 deletions webapp/utils/misc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,16 @@ export const getFilename = (path: string) => {
const p = path.replace(/\\/g, '/');
return p.split('/').pop();
};

export const fetchJson = () => {
const abortController = new AbortController();
const fetchData = async (endpoint: string, options: RequestInit) => {
const response = await fetch(endpoint, {
...options,
signal: abortController.signal,
});
const newData = await response.json();
return newData;
};
return [fetchData, abortController];
};

0 comments on commit a06fada

Please sign in to comment.