Skip to content

Commit

Permalink
Adds custom array and text controls
Browse files Browse the repository at this point in the history
  • Loading branch information
jacoblee93 authored and dqbd committed Oct 19, 2023
1 parent 4878d83 commit a54d7df
Show file tree
Hide file tree
Showing 14 changed files with 6,002 additions and 2,851 deletions.
21 changes: 16 additions & 5 deletions examples/chain/server.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
#!/usr/bin/env python
"""Example LangChain server exposes a chain composed of a prompt and an LLM."""
from typing import Any, Dict, List, Optional

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from langchain.chat_models import ChatOpenAI
from langchain.prompts import PromptTemplate

# from typing_extensions import TypedDict
from langchain.pydantic_v1 import BaseModel
from langchain.schema.output_parser import StrOutputParser
from langchain.schema.runnable import ConfigurableField
from typing_extensions import TypedDict
from langchain.schema.runnable import ConfigurableField, RunnablePassthrough

from langserve import add_routes

Expand All @@ -17,15 +21,20 @@
default_key="medium_temp",
)
prompt = PromptTemplate.from_template(
"tell me a joke about {topic}"
"tell me a joke about {topic}.\nChat history: {chat_history}"
).configurable_fields(
template=ConfigurableField(
id="prompt",
name="Prompt",
description="The prompt to use. Must contain {topic}",
)
)
chain = prompt | model | StrOutputParser()
chain = (
RunnablePassthrough.assign(chat_history=(lambda x: "\n".join(x)))
| prompt
| model
| StrOutputParser()
)

app = FastAPI(
title="LangChain Server",
Expand All @@ -47,11 +56,13 @@
# The input type is automatically inferred from the runnable
# interface; however, if you want to override it, you can do so
# by passing in the input_type argument to add_routes.
class ChainInput(TypedDict):
class ChainInput(BaseModel):
"""The input to the chain."""

topic: str
"""The topic of the joke."""
chat_history: List[str]
tester: Optional[Dict[str, Any]] = None


add_routes(app, chain, input_type=ChainInput, config_keys=["configurable"])
Expand Down
2 changes: 2 additions & 0 deletions langserve/playground/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,5 @@ dist-ssr
*.njsproj
*.sln
*.sw?

.yarn
2 changes: 2 additions & 0 deletions langserve/playground/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,14 @@
"dayjs": "^1.11.10",
"fast-json-patch": "^3.1.1",
"json-schema-defaults": "^0.4.0",
"lodash": "^4.17.21",
"lz-string": "^1.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"vaul": "^0.7.3"
},
"devDependencies": {
"@types/lodash": "^4.14.200",
"@types/react": "^18.2.15",
"@types/react-dom": "^18.2.7",
"@typescript-eslint/eslint-plugin": "^6.0.0",
Expand Down
6 changes: 5 additions & 1 deletion langserve/playground/src/App.css
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,14 @@
@apply focus-within:border-ls-blue focus-within:outline focus-within:outline-4 focus-within:outline-ls-blue/20;
}

.control > label {
.control > label, .control h6 {
@apply text-xs uppercase font-semibold text-ls-gray-100;
}

.control div .MuiGrid-item {
@apply pt-0;
}

.control > select {
@apply -ml-1;
}
Expand Down
11 changes: 8 additions & 3 deletions langserve/playground/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import {
IntegerCell,
NumberCell,
SliderCell,
TextAreaCell,
// TextAreaCell,
TimeCell,
booleanCellTester,
dateCellTester,
Expand All @@ -54,6 +54,8 @@ import {
import { useSchemas } from "./useSchemas";
import { RunState, useStreamLog } from "./useStreamLog";
import { JsonFormsCore } from "@jsonforms/core";
import CustomArrayControlRenderer, { materialArrayControlTester } from "./components/CustomArrayControlRenderer";
import CustomTextAreaCell from "./components/CustomTextAreaCell";

dayjs.extend(relativeDate);
dayjs.extend(utc);
Expand All @@ -75,6 +77,9 @@ const renderers = [
{ tester: materialAllOfControlTester, renderer: MaterialAllOfRenderer },
{ tester: materialAnyOfControlTester, renderer: MaterialAnyOfRenderer },
{ tester: materialOneOfControlTester, renderer: MaterialOneOfRenderer },

// custom renderers
{ tester: materialArrayControlTester, renderer: CustomArrayControlRenderer }
];

const cells = [
Expand All @@ -85,8 +90,8 @@ const cells = [
{ tester: integerCellTester, cell: IntegerCell },
{ tester: numberCellTester, cell: NumberCell },
{ tester: sliderCellTester, cell: SliderCell },
{ tester: textAreaCellTester, cell: TextAreaCell },
{ tester: textCellTester, cell: TextAreaCell },
{ tester: textAreaCellTester, cell: CustomTextAreaCell },
{ tester: textCellTester, cell: CustomTextAreaCell },
{ tester: timeCellTester, cell: TimeCell },
];

Expand Down
86 changes: 86 additions & 0 deletions langserve/playground/src/components/CustomArrayControlRenderer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// From https://github.com/eclipsesource/jsonforms/blob/44070b325121ad7173082fdf33be079f42ef96c4/packages/material/src/complex/MaterialArrayControlRenderer.tsx
/*
The MIT License
Copyright (c) 2017-2019 EclipseSource Munich
https://github.com/eclipsesource/jsonforms
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import React, { useCallback, useState } from 'react';
import {
ArrayLayoutProps,
RankedTester,
isObjectArrayControl,
isPrimitiveArrayControl,
or,
rankWith,
} from '@jsonforms/core';
import { withJsonFormsArrayLayoutProps } from '@jsonforms/react';
import { MaterialTableControl } from './MaterialTableControl';
import { Hidden } from '@mui/material';
import { DeleteDialog } from './DeleteDialog';

export const MaterialArrayControlRenderer = (props: ArrayLayoutProps) => {
const [open, setOpen] = useState(false);
const [path, setPath] = useState(undefined);
const [rowData, setRowData] = useState(undefined);
const { removeItems, visible } = props;

const openDeleteDialog = useCallback(
(p: string, rowIndex: number) => {
setOpen(true);
setPath(p);
setRowData(rowIndex);
},
[setOpen, setPath, setRowData]
);
const deleteCancel = useCallback(() => setOpen(false), [setOpen]);
const deleteConfirm = useCallback(() => {
const p = path.substring(0, path.lastIndexOf('.'));
removeItems(p, [rowData])();
setOpen(false);
}, [setOpen, path, rowData]);
const deleteClose = useCallback(() => setOpen(false), [setOpen]);

return (
<div className="control mt-4 mb-4">
<Hidden xsUp={!visible}>
<MaterialTableControl {...props} openDeleteDialog={openDeleteDialog} />
<DeleteDialog
open={open}
onCancel={deleteCancel}
onConfirm={deleteConfirm}
onClose={deleteClose}
acceptText={props.translations.deleteDialogAccept}
declineText={props.translations.deleteDialogDecline}
title={props.translations.deleteDialogTitle}
message={props.translations.deleteDialogMessage}
/>
</Hidden>
</div>
);
};

export const materialArrayControlTester: RankedTester = rankWith(
999,
or(isObjectArrayControl, isPrimitiveArrayControl)
);

export default withJsonFormsArrayLayoutProps(MaterialArrayControlRenderer);
65 changes: 65 additions & 0 deletions langserve/playground/src/components/CustomTextAreaCell.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// From https://github.com/eclipsesource/jsonforms/blob/master/packages/vanilla-renderers/src/cells/TextAreaCell.tsx

/*
The MIT License
Copyright (c) 2017-2019 EclipseSource Munich
https://github.com/eclipsesource/jsonforms
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import React from 'react';
import {
CellProps,
isMultiLineControl,
RankedTester,
rankWith,
} from '@jsonforms/core';
import { withJsonFormsCellProps } from '@jsonforms/react';
import { withVanillaCellProps, type VanillaRendererProps } from '@jsonforms/vanilla-renderers';
import merge from 'lodash/merge';

export const TextAreaCell = (props: CellProps & VanillaRendererProps) => {
const { data, className, id, enabled, config, uischema, path, handleChange } =
props;
const appliedUiSchemaOptions = merge({}, config, uischema.options);
console.log(config, uischema);
return (
<textarea
value={data || ''}
onChange={(ev) =>
handleChange(path, ev.target.value === '' ? undefined : ev.target.value)
}
className={className + " control"}
style={{width: "100%", fontSize: "18px"}}
id={id}
disabled={!enabled}
autoFocus={appliedUiSchemaOptions.focus}
placeholder={appliedUiSchemaOptions.placeholder}
/>
);
};

/**
* Tester for a multi-line string control.
* @type {RankedTester}
*/
export const textAreaCellTester: RankedTester = rankWith(2, isMultiLineControl);

export default withJsonFormsCellProps(withVanillaCellProps(TextAreaCell));
84 changes: 84 additions & 0 deletions langserve/playground/src/components/DeleteDialog.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
The MIT License
Copyright (c) 2017-2019 EclipseSource Munich
https://github.com/eclipsesource/jsonforms
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import React from 'react';
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
} from '@mui/material';

export interface DeleteDialogProps {
open: boolean;
onClose(): void;
onConfirm(): void;
onCancel(): void;
title: string;
message: string;
acceptText: string;
declineText: string;
}

export interface WithDeleteDialogSupport {
openDeleteDialog(path: string, data: number): void;
}

export const DeleteDialog = React.memo(function DeleteDialog({
open,
onClose,
onConfirm,
onCancel,
title,
message,
acceptText,
declineText,
}: DeleteDialogProps) {
return (
<Dialog
open={open}
keepMounted
onClose={onClose}
aria-labelledby='alert-dialog-confirmdelete-title'
aria-describedby='alert-dialog-confirmdelete-description'
>
<DialogTitle id='alert-dialog-confirmdelete-title'>{title}</DialogTitle>
<DialogContent>
<DialogContentText id='alert-dialog-confirmdelete-description'>
{message}
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={onCancel} color='primary'>
{declineText}
</Button>
<Button onClick={onConfirm} color='primary'>
{acceptText}
</Button>
</DialogActions>
</Dialog>
);
});
Loading

0 comments on commit a54d7df

Please sign in to comment.