Skip to content

Commit

Permalink
add optional parameters cards
Browse files Browse the repository at this point in the history
  • Loading branch information
DoraDong-2023 committed Dec 27, 2023
1 parent a12be41 commit 4173948
Show file tree
Hide file tree
Showing 9 changed files with 74 additions and 17 deletions.
Binary file modified chatbot_ui_biomania/.DS_Store
Binary file not shown.
Binary file modified chatbot_ui_biomania/components/Chat/.DS_Store
Binary file not shown.
8 changes: 8 additions & 0 deletions chatbot_ui_biomania/components/Chat/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ interface Props {
}
export const Chat = memo(({ stopConversationRef }: Props) => {
const { t } = useTranslation('chat');
const [optionalParams, setOptionalParams] = useState<string>('');
// From OptionalCard
const handleOptionalParamsChange = (newParams: Record<string, any>) => {
const optionalParamsString = JSON.stringify(newParams);
setOptionalParams(optionalParamsString);
};
const {
state: {
selectedConversation,
Expand Down Expand Up @@ -179,6 +185,7 @@ export const Chat = memo(({ stopConversationRef }: Props) => {
lib_alias: updatedConversation.lib_alias,
conversation_started: isFirstMessageInConversation,
session_id: updatedConversation.id,
optionalParams: optionalParams,
};
console.log("updatedConversation", updatedConversation)
const endpoint = "api/chat";
Expand Down Expand Up @@ -346,6 +353,7 @@ export const Chat = memo(({ stopConversationRef }: Props) => {
stopConversationRef,
attachedFiles,
selectedConversation,
optionalParams,
],
);
const handleFileUpload = useCallback(
Expand Down
58 changes: 48 additions & 10 deletions chatbot_ui_biomania/components/Chat/ProgressCards/OptionalCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,27 +15,53 @@ interface ParamInfo {

interface OptionalCardProps {
params: Record<string, ParamInfo>;
onParamsChange: (newParams: Record<string, any>) => void;
}

const OptionalCard: React.FC<OptionalCardProps> = ({ params }) => {
const OptionalCard: React.FC<OptionalCardProps> = ({ params, onParamsChange }) => {
const [activeParam, setActiveParam] = useState<string | null>(null);
const [inputValue, setInputValue] = useState('');
const [editedValues, setEditedValues] = useState<Record<string, any>>({});
const labelContainerRef = useRef<HTMLDivElement>(null);

useEffect(() => {
if (Object.keys(params).length > 0) {
setActiveParam(Object.keys(params)[0]);
const firstParam = Object.keys(params)[0];
// Set activeParam to the first param only if it's not already set
// or if it's not in the editedValues
setActiveParam(prev => prev && editedValues[prev] !== undefined ? prev : firstParam);
}
}, [params]);
}, [params, editedValues]);

// 从 localStorage 初始化 editedValues
useEffect(() => {
const savedValues = localStorage.getItem('editedValues');
if (savedValues) {
setEditedValues(JSON.parse(savedValues));
}
}, []);
useEffect(() => {
localStorage.setItem('editedValues', JSON.stringify(editedValues));
}, [editedValues]);

const handleParamClick = (param: string) => {
if (activeParam && editedValues[activeParam] !== undefined) {
const newParams = { ...params };
newParams[activeParam].default = editedValues[activeParam];
onParamsChange(newParams);
}
setActiveParam(param);
};

const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(event.target.value);
setEditedValues({ ...editedValues, [activeParam!]: event.target.value });
};


const handleInputBlur = () => {
if (activeParam && editedValues[activeParam] !== undefined) {
onParamsChange({ ...params, [activeParam]: { ...params[activeParam], default: editedValues[activeParam] } });
}
};

const scroll = (direction: 'left' | 'right') => {
if (labelContainerRef.current) {
const scrollAmount = direction === 'left' ? -100 : 100;
Expand Down Expand Up @@ -72,14 +98,26 @@ const OptionalCard: React.FC<OptionalCardProps> = ({ params }) => {
<Typography variant="body2" sx={{ fontSize: '0.8rem', marginBottom: '2px' }}>
Description: {params[activeParam].description}
</Typography>
<Typography variant="body2" sx={{ fontSize: '0.8rem', marginBottom: '2px', color: 'grey' }}>
Default: {params[activeParam].default}
</Typography>
<Box display="flex" alignItems="center">
<Typography variant="body2" sx={{ fontSize: '0.8rem', marginRight: '8px', marginBottom: '2px' }}>
Type: {params[activeParam].type}. Input:
</Typography>
<TextField
value={inputValue}
onChange={handleInputChange}
sx={{ flexGrow: 1, marginBottom: '2px', input: { padding: '2px 10px' } }}
value={editedValues[activeParam] !== undefined ? editedValues[activeParam] : params[activeParam].default}
onChange={handleInputChange}
onBlur={handleInputBlur}
sx={{
flexGrow: 1,
marginBottom: '2px',
input: {
padding: '2px 10px',
color: 'grey', // Setting the text color to grey
fontSize: '0.8rem' // Setting a smaller font size
}
}}
/>
</Box>
</div>
Expand All @@ -88,4 +126,4 @@ const OptionalCard: React.FC<OptionalCardProps> = ({ params }) => {
);
};

export default OptionalCard;
export default OptionalCard;
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ const processObjs = (progressJson: any): BaseUsage[] => {
return ret;
}

const generateCards = (progressJson: any) => {
const generateCards = (progressJson: any, setOptionalCardData: (data: Record<string, any>) => void) => {
var progressObjs: BaseUsage[] = processObjs(progressJson);
var lastdepth = 0;
var reactNOdeBacktrack = [];
Expand Down Expand Up @@ -298,6 +298,9 @@ const generateCards = (progressJson: any) => {
<OptionalCard
key={generate_random_id()}
params={root.json}
onParamsChange={(newParams) => {
setOptionalCardData(newParams);
}}
/>
);
} else if (root.block_id.includes("textcollapse")) {
Expand Down Expand Up @@ -373,6 +376,9 @@ const ProgressCardController = (props: ProgressCardControllerProps) => {
const [snackbarOpen, setSnackbarOpen] = useState(false);
const [snackbarContent, setSnackbarContent] = useState("");
const [collapsed, setCollapsed] = useState(true);
const [optionalCardData, setOptionalCardData] = useState({});


const handleSnackbarClose = () => {
setSnackbarOpen(false);
}
Expand All @@ -382,7 +388,7 @@ const ProgressCardController = (props: ProgressCardControllerProps) => {
if (!props.progressJson || props.progressJson.length === 0) {
return null;
}
var temp = generateCards(props.progressJson);
var temp = generateCards(props.progressJson, setOptionalCardData);
var cards = temp.cards;
var toolRecommendations = temp.toolRecommendations;
return (
Expand Down
4 changes: 2 additions & 2 deletions chatbot_ui_biomania/pages/api/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ export const config = {
};
const handler = async (req: Request): Promise<Response> => {
try {
const { top_k, method, messages, files, Lib, new_lib_github_url, new_lib_doc_url, conversation_started, api_html,lib_alias,session_id } = (await req.json()) as ChatBody;
const { top_k, method, messages, files, Lib, new_lib_github_url, new_lib_doc_url, conversation_started, api_html,lib_alias,session_id,optionalParams } = (await req.json()) as ChatBody;

let messagesToSend: Message[] = [];

for (let i = messages.length - 1; i >= 0; i--) {
const message = messages[i];
messagesToSend = [message, ...messagesToSend];
}
const stream = await BioMANIAStream(method.method, messagesToSend, top_k, Lib, files, new_lib_github_url, new_lib_doc_url, api_html,lib_alias,conversation_started,session_id);
const stream = await BioMANIAStream(method.method, messagesToSend, top_k, Lib, files, new_lib_github_url, new_lib_doc_url, api_html,lib_alias,conversation_started,session_id,optionalParams);

return new Response(stream);
} catch (error) {
Expand Down
1 change: 1 addition & 0 deletions chatbot_ui_biomania/types/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ export interface ChatBody {
lib_alias: string;
conversation_started: boolean;
session_id:string;
optionalParams:string;
}
export interface Conversation {
id: string;
Expand Down
4 changes: 3 additions & 1 deletion chatbot_ui_biomania/utils/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export const BioMANIAStream = async (
lib_alias: string,
conversation_started: boolean,
session_id:string,
optionalParams:string,
) => {
// streamed response
const response = await fetch(streamUrl, {
Expand All @@ -44,7 +45,8 @@ export const BioMANIAStream = async (
api_html: api_html,
lib_alias: lib_alias,
conversation_started: conversation_started,
session_id:session_id
session_id:session_id,
optionalParams:optionalParams,
}),
headers: {
'Content-Type': 'application/json'
Expand Down
6 changes: 4 additions & 2 deletions src/deploy/inference_dialog_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -1172,10 +1172,12 @@ def run_pipeline_after_entering_params(self, user_input):
print('len(optional_param)', len(optional_param))
[callback.on_tool_start() for callback in self.callbacks]
[callback.on_tool_end() for callback in self.callbacks]
if False:
if False: # TODO: if True, to debug the optional card showing
if len(optional_param)>0:
print('producing optional param card')
[callback.on_agent_action(block_id="optional-"+str(self.indexxxx),task=convert_bool_values(correct_bool_values(optional_param)),task_title="Executed code",) for callback in self.callbacks]
[callback.on_agent_action(block_id="log-"+str(self.indexxxx),task="Do you want to modify the optional parameters? You can leave it unchange if you don't want to modify the default value.",task_title="Optional cards",) for callback in self.callbacks]
self.indexxxx+=1
[callback.on_agent_action(block_id="optional-"+str(self.indexxxx),task=convert_bool_values(correct_bool_values(optional_param)),task_title="Optional cards",) for callback in self.callbacks]
self.indexxxx+=1
else:
pass
Expand Down

0 comments on commit 4173948

Please sign in to comment.