Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prompt cell output can be saved to variables #52

Merged
merged 2 commits into from
Jan 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/libro-prompt-cell/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,10 @@
"@difizen/libro-codemirror": "^0.1.14",
"@difizen/libro-common": "^0.1.14",
"@difizen/libro-core": "^0.1.14",
"@ant-design/icons": "^5.1.0",
"@difizen/mana-l10n": "latest",
"@difizen/mana-app": "latest",
"classnames": "^2.3.2",
"highlight.js": "^11.8.0",
"marked": "^5.1.1",
"marked-highlight": "^2.0.1",
Expand Down
5 changes: 5 additions & 0 deletions packages/libro-prompt-cell/src/index.less
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
.libro-prompt-cell-header {
display: flex;
align-items: center;
}

.libro-llm-hljs {
overflow-x: auto;
white-space: pre-wrap !important;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { singleton } from '@difizen/mana-app';

export interface PromptDecodedFormatter extends DefaultDecodedFormatter {
modelType?: string;
variableName?: string;
}

@singleton({ contrib: FormatterContribution })
Expand All @@ -29,6 +30,7 @@ export class FormatterPromptMagicContribution
const promptObj = {
model_name: source.modelType || 'chatgpt',
prompt: source.value,
variable_name: source.variableName,
};
const encodeValue = `%%prompt \n${JSON.stringify(promptObj)}`;
return {
Expand All @@ -41,14 +43,15 @@ export class FormatterPromptMagicContribution

decode = (formatterValue: DefaultEncodedFormatter) => {
const value = concatMultilineString(formatterValue.source);

if (value.startsWith('%%prompt \n')) {
const run = value.split('%%prompt \n')[1];
const runValue = JSON.parse(run);
const codeValue = runValue.prompt;
const modelType = runValue.model_name;
const variableName = runValue.variable_name;
return {
value: codeValue,
variableName,
modelType,
};
}
Expand Down
4 changes: 4 additions & 0 deletions packages/libro-prompt-cell/src/prompt-cell-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ export class LibroPromptCellModel
kernelExecuting = false;

modelType: string;

@prop()
variableName: string;

@prop()
executing: boolean;
@prop()
Expand Down
132 changes: 104 additions & 28 deletions packages/libro-prompt-cell/src/prompt-cell-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,29 +38,61 @@ import { Deferred } from '@difizen/mana-app';
import { Select, Tag } from 'antd';
import React, { useEffect, useState } from 'react';

import type { LibroPromptCellModel } from './prompt-cell-model.js';
import { LibroPromptCellModel } from './prompt-cell-model.js';
import { PromptScript } from './prompt-cell-script.js';
import { VariableNameInput } from './variable-handler/index.js';
import './index.less';

export interface IChatSelectionItem {
export interface ChatItem {
name: string;
type: string;
order: number;
key: string;
}
export interface ChatTypeOptions {
order?: number;
color?: string;
}

const ChatItemOptions = (type: string): ChatTypeOptions => {
switch (type) {
case 'LLM':
return {
order: 1,
color: 'blue',
};
case 'VARIABLE':
return {
order: 2,
color: 'red',
};
case 'API':
return {
order: 3,
color: 'green',
};
case 'CUSTOM':
return {
order: 4,
color: undefined,
};
default:
return {
order: undefined,
color: undefined,
};
}
};

const SelectionItemLabel: React.FC<{ item: IChatSelectionItem }> = (props: {
item: IChatSelectionItem;
const SelectionItemLabel: React.FC<{ item: ChatItem }> = (props: {
item: ChatItem;
}) => {
const item = props.item;
const colorMap: Record<string, any> = {
VARIABLE: 'red',
LLM: 'blue',
API: 'green',
CUSTOM: undefined,
};

return (
<span className="libro-prompt-cell-selection-label">
<Tag
color={colorMap[item.type] || undefined}
color={ChatItemOptions(item.type).color}
className="libro-prompt-cell-header-selection-type"
>
{item.type}
Expand All @@ -69,7 +101,7 @@ const SelectionItemLabel: React.FC<{ item: IChatSelectionItem }> = (props: {
</span>
);
};
const CellEditor: React.FC = () => {
const CellEditorRaw: React.FC = () => {
const instance = useInject<LibroPromptCellView>(ViewInstance);
useEffect(() => {
if (instance.editorView?.editor) {
Expand All @@ -79,20 +111,22 @@ const CellEditor: React.FC = () => {
return <>{instance.editorView && <ViewRender view={instance.editorView} />}</>;
};

export const CellEditorMemo = React.memo(CellEditor);
export const CellEditor = React.memo(CellEditorRaw);

const PropmtEditorViewComponent = React.forwardRef<HTMLDivElement>(
function MaxPropmtEditorViewComponent(props, ref) {
const instance = useInject<LibroPromptCellView>(ViewInstance);
const [selectedModel, setSelectedModel] = useState<string>('暂无内置模型');
useEffect(() => {
// TODO: Data initialization should not depend on view initialization, which causes limitations in usage scenarios and multiple renderings.
instance.model.variableName = instance.model.decodeObject['variableName'];
instance
.updateChatList()
.then(() => {
const len = instance.selection.length;
const len = instance.chatItems.length;
if (len > 0) {
instance.model.decodeObject = {
modelType: instance.selection[len - 1].name,
modelType: instance.chatItems[len - 1].key,
...instance.model.decodeObject,
};
setSelectedModel(instance.model.decodeObject['modelType']);
Expand All @@ -108,11 +142,7 @@ const PropmtEditorViewComponent = React.forwardRef<HTMLDivElement>(
}, []);

const handleChange = (value: string) => {
instance.model.modelType = value;
instance.model.decodeObject = {
...instance.model.decodeObject,
modelType: value,
};
instance.handleModelNameChange(value);
setSelectedModel(value);
};

Expand All @@ -129,15 +159,20 @@ const PropmtEditorViewComponent = React.forwardRef<HTMLDivElement>(
value={selectedModel}
style={{ width: 160 }}
onChange={handleChange}
options={instance.selection.map(instance.toSelectionOption)}
options={instance.sortedChatItems.map(instance.toSelectionOption)}
bordered={false}
onFocus={async () => {
await instance.updateChatList();
}}
/>
</div>
<VariableNameInput
value={instance.model.variableName}
checkVariableNameAvailable={instance.checkVariableNameAvailable}
handleVariableNameChange={instance.handleVariableNameChange}
/>
</div>
<CellEditorMemo />
<CellEditor />
</div>
);
},
Expand All @@ -152,7 +187,21 @@ export class LibroPromptCellView extends LibroExecutableCellView {
declare model: LibroPromptCellModel;

@prop()
selection: IChatSelectionItem[] = [];
chatItems: ChatItem[] = [];

get sortedChatItems(): ChatItem[] {
return [...this.chatItems].sort((a, b) => {
if (a.type !== b.type) {
const aOrder = ChatItemOptions(a.type).order || 0;
const bOrder = ChatItemOptions(b.type).order || 0;
if (aOrder === bOrder && aOrder === 0) {
return a.type.localeCompare(b.type);
}
return aOrder - bOrder;
}
return a.order - b.order;
});
}

viewManager: ViewManager;

Expand Down Expand Up @@ -420,14 +469,17 @@ export class LibroPromptCellView extends LibroExecutableCellView {

updateChatList = async () => {
return this.fetch(
{ code: this.promptScript.toList, store_history: false },
{
code: this.promptScript.toList,
store_history: false,
},
this.handleQueryResponse,
);
};

toSelectionOption = (item: IChatSelectionItem) => {
toSelectionOption = (item: ChatItem) => {
return {
value: item.name,
value: item.key,
label: <SelectionItemLabel item={item} />,
};
};
Expand All @@ -443,7 +495,7 @@ export class LibroPromptCellView extends LibroExecutableCellView {
content = content.replace(/\\"/g, '"').replace(/\\'/g, "'");
}

this.selection = JSON.parse(content) as IChatSelectionItem[];
this.chatItems = JSON.parse(content) as ChatItem[];
break;
}
case 'stream': {
Expand All @@ -454,11 +506,35 @@ export class LibroPromptCellView extends LibroExecutableCellView {
contentStream = contentStream.replace(/\\"/g, '"').replace(/\\'/g, "'");
}

this.selection = JSON.parse(contentStream) as IChatSelectionItem[];
this.chatItems = JSON.parse(contentStream) as ChatItem[];
break;
}
default:
break;
}
};

checkVariableNameAvailable = (variableName: string) => {
return (
this.parent.model.cells.findIndex(
(cell) =>
cell.model instanceof LibroPromptCellModel &&
cell.model.variableName === variableName,
) > -1
);
};
handleModelNameChange = (key: string) => {
this.model.decodeObject = {
...this.model.decodeObject,
modelType: key,
};
this.model.modelType = key;
};
handleVariableNameChange = (variableName: string) => {
this.model.decodeObject = {
...this.model.decodeObject,
variableName: variableName,
};
this.model.variableName = variableName;
};
}
46 changes: 46 additions & 0 deletions packages/libro-prompt-cell/src/variable-handler/index.less
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
.libro-variable-name-input {
border-left: 1px solid var(--mana-color-border);

svg {
margin-left: 4px;
}

&-label {
padding-left: 16px;
color: var(--mana-libro-cell-header-title);
font-weight: 400;
font-size: 14px;
font-family: SFProText;
line-height: 36px;
letter-spacing: 0;
}

&-input {
width: 120px;
height: 32px;
border: 1px solid #d6d8da;
border-radius: 6px;
box-shadow: unset;
}

&-popover {
vertical-align: middle;
}

&-warning-text {
margin-top: 4px;
color: #faad14;
}

&-actions {
padding: 2px 0;

span + span {
margin-left: 8px;
}

span {
color: #1890ff;
}
}
}
1 change: 1 addition & 0 deletions packages/libro-prompt-cell/src/variable-handler/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './variable-name-input.js';
Loading