panel.chat Package#


chat Package#

Panel chat makes creating chat components easy#

Check out the widget gallery https://panel.holoviz.org/reference/index.html#chat for inspiration.

How to use Panel widgets in 3 simple steps#

  1. Define your function

>>> async def repeat_contents(contents, user, instance):
>>>     yield contents
  1. Define your widgets and callback.

>>> chat_interface = ChatInterface(callback=repeat_contents)
  1. Layout the chat interface in a template

>>> template = pn.template.FastListTemplate(
>>>     title="Panel Chat",
>>>     main=[chat_interface],
>>> )
>>> template.servable()

For more detail see the Reference Gallery guide. https://panel.holoviz.org/reference/chat/ChatInterface.html

class panel.chat.ChatAreaInput(*, disabled_enter, enter_sends, auto_grow, cols, max_rows, resizable, rows, description, max_length, placeholder, value, value_input, disabled, loading, align, aspect_ratio, css_classes, design, height, height_policy, margin, max_height, max_width, min_height, min_width, sizing_mode, styles, stylesheets, tags, visible, width, width_policy, name)[source]#

Bases: TextAreaInput

The ChatAreaInput allows entering any multiline string using a text input box, with the ability to press enter to submit the message.

Unlike TextAreaInput, the ChatAreaInput defaults to auto_grow=True and max_rows=10, and the value is not synced to the server until the enter key is pressed so bind on value_input if you need to access the existing value.

Lines are joined with the newline character n.

Reference: https://panel.holoviz.org/reference/chat/ChatAreaInput.html

Example:

>>> ChatAreaInput(max_rows=10)

Parameters inherited from:

panel.viewable.Layoutable: align, aspect_ratio, css_classes, design, min_width, min_height, max_width, max_height, styles, stylesheets, tags, width_policy, height_policy, sizing_mode, visible

panel.viewable.Viewable: loading

panel.widgets.base.Widget: height, margin, disabled

panel.widgets.input.TextInput: width, description, max_length, placeholder, value, value_input

panel.widgets.input.TextAreaInput: cols

auto_grow = param.Boolean(allow_refs=False, default=True, label=’Auto grow’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x141740bd0>)

Whether the text area should automatically grow vertically to accommodate the current text.

max_rows = param.Integer(allow_refs=False, default=10, inclusive_bounds=(True, True), label=’Max rows’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142081ad0>)

When combined with auto_grow this determines the maximum number of rows the input area can grow.

rows = param.Integer(allow_refs=False, default=1, inclusive_bounds=(True, True), label=’Rows’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1422da1d0>)

Number of rows in the text input field.

resizable = param.ObjectSelector(allow_refs=False, default=’height’, label=’Resizable’, names={}, nested_refs=False, objects=[‘both’, ‘width’, ‘height’, False], rx=<param.reactive.reactive_ops object at 0x141f17310>)

Whether the layout is interactively resizable, and if so in which dimensions: width, height, or both. Can only be set during initialization.

disabled_enter = param.Boolean(allow_refs=False, default=False, label=’Disabled enter’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1422db610>)

If True, disables sending the message by pressing the enter_sends key.

enter_sends = param.Boolean(allow_refs=False, default=True, label=’Enter sends’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x141f15250>)

If True, pressing the Enter key sends the message, if False it is sent by pressing the Ctrl+Enter.

clone(**params) Viewable[source]#

Makes a copy of the object sharing the same parameters.

Parameters:

params (Keyword arguments override the parameters on the clone.) –

Return type:

Cloned Viewable object

controls(parameters: List[str] = [], jslink: bool = True, **kwargs) Panel[source]#

Creates a set of widgets which allow manipulating the parameters on this instance. By default all parameters which support linking are exposed, but an explicit list of parameters can be provided.

Parameters:
  • parameters (list(str)) – An explicit list of parameters to return controls for.

  • jslink (bool) – Whether to use jslinks instead of Python based links. This does not allow using all types of parameters.

  • kwargs (dict) – Additional kwargs to pass to the Param pane(s) used to generate the controls widgets.

Return type:

A layout of the controls

embed(max_states: int = 1000, max_opts: int = 3, json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = False, states={}) None[source]#

Renders a static version of a panel in a notebook by evaluating the set of states defined by the widgets in the model. Note this will only work well for simple apps with a relatively small state space.

Parameters:
  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for JSON filename

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=False)) – Whether to report progress

  • states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

classmethod from_param(parameter: param.Parameter, onkeyup=False, **params) Viewable[source]#

Construct a widget from a Parameter and link the two bi-directionally.

Parameters:
  • parameter (param.Parameter) – A parameter to create the widget from.

  • onkeyup (boolean) – Whether to trigger events on every key press.

  • params (dict) – Keyword arguments to be passed to the widget constructor

Return type:

Widget instance linked to the supplied parameter

get_root(doc: Optional[Document] = None, comm: Optional[Comm] = None, preprocess: bool = True) Model[source]#

Returns the root model and applies pre-processing hooks

Parameters:
  • doc (bokeh.Document) – Bokeh document the bokeh model will be attached to.

  • comm (pyviz_comms.Comm) – Optional pyviz_comms when working in notebook

  • preprocess (boolean (default=True)) – Whether to run preprocessing hooks

Return type:

Returns the bokeh model corresponding to this panel object

jscallback(args: Dict[str, Any] = {}, **callbacks: str) Callback[source]#

Allows defining a JS callback to be triggered when a property changes on the source object. The keyword arguments define the properties that trigger a callback and the JS code that gets executed.

Parameters:
  • args (dict) – A mapping of objects to make available to the JS callback

  • **callbacks (dict) – A mapping between properties on the source model and the code to execute when that property changes

Returns:

callback – The Callback which can be used to disable the callback.

Return type:

Callback

Links properties on the this Reactive object to those on the target Reactive object in JS code.

Supports two modes, either specify a mapping between the source and target model properties as keywords or provide a dictionary of JS code snippets which maps from the source parameter to a JS code snippet which is executed when the property changes.

Parameters:
  • target (panel.viewable.Viewable | bokeh.model.Model | holoviews.core.dimension.Dimensioned) – The target to link the value to.

  • code (dict) – Custom code which will be executed when the widget value changes.

  • args (dict) – A mapping of objects to make available to the JS callback

  • bidirectional (boolean) – Whether to link source and target bi-directionally

  • **links (dict) – A mapping between properties on the source model and the target model property to link it to.

Returns:

link – The GenericLink which can be used unlink the widget and the target model.

Return type:

GenericLink

Links the parameters on this Reactive object to attributes on the target Parameterized object.

Supports two modes, either specify a mapping between the source and target object parameters as keywords or provide a dictionary of callbacks which maps from the source parameter to a callback which is triggered when the parameter changes.

Parameters:
  • target (param.Parameterized) – The target object of the link.

  • callbacks (dict | None) – Maps from a parameter in the source object to a callback.

  • bidirectional (bool) – Whether to link source and target bi-directionally

  • **links (dict) – Maps between parameters on this object to the parameters on the supplied object.

save(filename: str | os.PathLike | IO, title: Optional[str] = None, resources: bokeh.resources.Resources | None = None, template: str | jinja2.environment.Template | None = None, template_variables: Dict[str, Any] = {}, embed: bool = False, max_states: int = 1000, max_opts: int = 3, embed_json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = True, embed_states: Dict[Any, Any] = {}, as_png: bool | None = None, **kwargs) None[source]#

Saves Panel objects to file.

Parameters:
  • filename (str or file-like object) – Filename to save the plot to

  • title (string) – Optional title for the plot

  • resources (bokeh resources) – One of the valid bokeh.resources (e.g. CDN or INLINE)

  • template – passed to underlying io.save

  • template_variables – passed to underlying io.save

  • embed (bool) – Whether the state space should be embedded in the saved file.

  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • embed_json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for the auto-generated json directory

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=True)) – Whether to report progress

  • embed_states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

  • as_png (boolean (default=None)) – To save as a .png. If None save_png will be true if filename is string and ends with png.

select(selector: Optional[Union[type, Callable[[Viewable], bool]]] = None) List[Viewable][source]#

Iterates over the Viewable and any potential children in the applying the Selector.

Parameters:

selector (type or callable or None) – The selector allows selecting a subset of Viewables by declaring a type or callable function to filter by.

Returns:

viewables

Return type:

list(Viewable)

servable(title: Optional[str] = None, location: bool | 'Location' = True, area: str = 'main', target: Optional[str] = None) ServableMixin[source]#

Serves the object or adds it to the configured pn.state.template if in a panel serve context, writes to the DOM if in a pyodide context and returns the Panel object to allow it to display itself in a notebook context.

Parameters:
  • title (str) – A string title to give the Document (if served as an app)

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

  • area (str (deprecated)) – The area of a template to add the component too. Only has an effect if pn.config.template has been set.

  • target (str) – Target area to write to. If a template has been configured on pn.config.template this refers to the target area in the template while in pyodide this refers to the ID of the DOM node to write to.

Return type:

The Panel object itself

server_doc(doc: Optional[Document] = None, title: Optional[str] = None, location: bool | 'Location' = True) Document[source]#

Returns a serveable bokeh Document with the panel attached

Parameters:
  • doc (bokeh.Document (optional)) – The bokeh Document to attach the panel to as a root, defaults to bokeh.io.curdoc()

  • title (str) – A string title to give the Document

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

doc – The bokeh document the panel was attached to

Return type:

bokeh.Document

show(title: Optional[str] = None, port: int = 0, address: Optional[str] = None, websocket_origin: Optional[str] = None, threaded: bool = False, verbose: bool = True, open: bool = True, location: bool | 'Location' = True, **kwargs) StoppableThread' | 'Server[source]#

Starts a Bokeh server and displays the Viewable in a new tab.

Parameters:
  • title (str | None) – A string title to give the Document (if served as an app)

  • port (int (optional, default=0)) – Allows specifying a specific port

  • address (str) – The address the server should listen on for HTTP requests.

  • websocket_origin (str or list(str) (optional)) – A list of hosts that can connect to the websocket. This is typically required when embedding a server app in an external web site. If None, “localhost” is used.

  • threaded (boolean (optional, default=False)) – Whether to launch the Server on a separate thread, allowing interactive use.

  • verbose (boolean (optional, default=True)) – Whether to print the address and port

  • open (boolean (optional, default=True)) – Whether to open the server in a new browser tab

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

server – Returns the Bokeh server instance or the thread the server was launched on (if threaded=True)

Return type:

bokeh.server.Server or panel.io.server.StoppableThread

class panel.chat.ChatFeed(*objects, **params)[source]#

Bases: ListPanel

A widget to display a list of ChatMessage objects and interact with them.

This widget provides methods to: - Send (append) messages to the chat log. - Stream tokens to the latest ChatMessage in the chat log. - Execute callbacks when a user sends a message. - Undo a number of sent ChatMessage objects. - Clear the chat log of all ChatMessage objects.

Reference: https://panel.holoviz.org/reference/chat/ChatFeed.html

Example:

>>> async def say_welcome(contents, user, instance):
>>>    yield "Welcome!"
>>>    yield "Glad you're here!"
>>> chat_feed = ChatFeed(callback=say_welcome, header="Welcome Feed")
>>> chat_feed.send("Hello World!", user="New User", avatar="😊")

Parameters inherited from:

panel.viewable.Layoutable: align, aspect_ratio, css_classes, design, height, min_width, min_height, max_width, max_height, styles, stylesheets, tags, width, width_policy, height_policy, sizing_mode, visible

panel.viewable.Viewable: loading

panel.layout.base.ListPanel: scroll

margin = param.Margin(allow_None=True, allow_refs=True, default=5, label=’Margin’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14145e850>)

Allows to create additional space around the component. May be specified as a two-tuple of the form (vertical, horizontal) or a four-tuple (top, right, bottom, left).

objects = param.List(allow_refs=False, bounds=(0, None), default=[], label=’Objects’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1423307d0>)

The list of child objects that make up the layout.

auto_scroll_limit = param.Integer(allow_refs=False, bounds=(0, None), default=200, inclusive_bounds=(True, True), label=’Auto scroll limit’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142333e10>)

Max pixel distance from the latest object in the Column to activate automatic scrolling upon update. Setting to 0 disables auto-scrolling.

callback = param.Callable(allow_None=True, allow_refs=False, label=’Callback’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x140ae6e50>)

Callback to execute when a user sends a message or when respond is called. The signature must include the previous message value contents, the previous user name, and the component instance.

callback_exception = param.ObjectSelector(allow_refs=False, default=’summary’, label=’Callback exception’, names={}, nested_refs=False, objects=[‘raise’, ‘summary’, ‘verbose’, ‘ignore’], rx=<param.reactive.reactive_ops object at 0x142167290>)

How to handle exceptions raised by the callback. If “raise”, the exception will be raised. If “summary”, a summary will be sent to the chat feed. If “verbose”, the full traceback will be sent to the chat feed. If “ignore”, the exception will be ignored.

callback_user = param.String(allow_refs=False, default=’Assistant’, label=’Callback user’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x141869f50>)

The default user name to use for the message provided by the callback.

card_params = param.Dict(allow_refs=False, class_=<class ‘dict’>, default={}, label=’Card params’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14019a7d0>)

Params to pass to Card, like header, header_background, header_color, etc.

collapsible = param.Boolean(allow_refs=False, constant=True, default=False, label=’Collapsible’, nested_refs=False, readonly=True, rx=<param.reactive.reactive_ops object at 0x142167a10>)

Whether the Card should be expandable and collapsible.

disabled = param.Boolean(allow_refs=False, default=False, label=’Disabled’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142167710>)

Whether the feed is disabled.

message_params = param.Dict(allow_refs=False, class_=<class ‘dict’>, default={}, label=’Message params’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142167390>)

Params to pass to each ChatMessage, like reaction_icons, timestamp_format, show_avatar, show_user, and show_timestamp. Params passed that are not ChatFeed params will be forwarded into message_params.

header = param.Parameter(allow_None=True, allow_refs=False, label=’Header’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1420c0690>)

The header of the chat feed; commonly used for the title. Can be a string, pane, or widget.

help_text = param.String(allow_refs=False, default=’’, label=’Help text’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142167a10>)

If provided, initializes a chat message in the chat log using the provided help text as the message object and help as the user. This is useful for providing instructions, and will not be included in the serialize method by default.

placeholder_text = param.String(allow_refs=False, default=’’, label=’Placeholder text’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1421676d0>)

The text to display next to the placeholder icon.

placeholder_params = param.Dict(allow_refs=False, class_=<class ‘dict’>, default={‘user’: ‘ ‘, ‘reaction_icons’: {}, ‘show_copy_icon’: False, ‘show_timestamp’: False}, label=’Placeholder params’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142167a10>)

Params to pass to the placeholder ChatMessage, like reaction_icons, timestamp_format, show_avatar, show_user, show_timestamp.

placeholder_threshold = param.Number(allow_refs=False, bounds=(0, None), default=1, inclusive_bounds=(True, True), label=’Placeholder threshold’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142167b50>)

Min duration in seconds of buffering before displaying the placeholder. If 0, the placeholder will be disabled.

renderers = param.HookList(allow_refs=False, bounds=(0, None), default=[], label=’Renderers’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1420d35d0>)

A callable or list of callables that accept the value and return a Panel object to render the value. If a list is provided, will attempt to use the first renderer that does not raise an exception. If None, will attempt to infer the renderer from the value.

load_buffer = param.Integer(allow_refs=False, bounds=(0, None), default=50, inclusive_bounds=(True, True), label=’Load buffer’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142166e90>)

The number of objects loaded on each side of the visible objects. When scrolled halfway into the buffer, the feed will automatically load additional objects while unloading objects on the opposite side.

scroll_button_threshold = param.Integer(allow_refs=False, bounds=(0, None), default=100, inclusive_bounds=(True, True), label=’Scroll button threshold’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142167c10>)

Min pixel distance from the latest object in the Column to display the scroll button. Setting to 0 disables the scroll button.

show_activity_dot = param.Boolean(allow_refs=False, default=True, label=’Show activity dot’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1420c0690>)

Whether to show an activity dot on the ChatMessage while streaming the callback response.

view_latest = param.Boolean(allow_refs=False, default=True, label=’View latest’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1420d35d0>)

Whether to scroll to the latest object on init. If not enabled the view will be on the first object.

_placeholder = param.ClassSelector(allow_None=True, allow_refs=False, class_=<class ‘panel.chat.message.ChatMessage’>, label=’ placeholder’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1422817d0>)

The placeholder wrapped in a ChatMessage object; primarily to prevent recursion error in _update_placeholder.

_callback_state = param.ObjectSelector(allow_refs=False, label=’ callback state’, names={}, nested_refs=False, objects=[<CallbackState.IDLE: ‘idle’>, <CallbackState.RUNNING: ‘running’>, <CallbackState.GENERATING: ‘generating’>, <CallbackState.STOPPING: ‘stopping’>, <CallbackState.STOPPED: ‘stopped’>], rx=<param.reactive.reactive_ops object at 0x14019a7d0>)

The current state of the callback.

_callback_trigger = param.Event(allow_refs=False, default=False, label=’ callback trigger’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x141119c10>)

Triggers the callback to respond.

_disabled_stack = param.List(allow_refs=False, bounds=(0, None), default=[], label=’ disabled stack’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14019a7d0>)

The previous disabled state of the feed.

append(obj: Any) None[source]#

Appends an object to the layout.

Parameters:

(object) (obj) –

clear() List[Any][source]#

Clears the chat log and returns the messages that were cleared.

Return type:

The messages that were cleared.

clone(*objects: Any, **params: Any) ListLike[source]#

Makes a copy of the layout sharing the same parameters.

Parameters:
  • objects (Objects to add to the cloned layout.) –

  • params (Keyword arguments override the parameters on the clone.) –

Return type:

Cloned layout object

controls(parameters: List[str] = [], jslink: bool = True, **kwargs) Panel[source]#

Creates a set of widgets which allow manipulating the parameters on this instance. By default all parameters which support linking are exposed, but an explicit list of parameters can be provided.

Parameters:
  • parameters (list(str)) – An explicit list of parameters to return controls for.

  • jslink (bool) – Whether to use jslinks instead of Python based links. This does not allow using all types of parameters.

  • kwargs (dict) – Additional kwargs to pass to the Param pane(s) used to generate the controls widgets.

Return type:

A layout of the controls

embed(max_states: int = 1000, max_opts: int = 3, json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = False, states={}) None[source]#

Renders a static version of a panel in a notebook by evaluating the set of states defined by the widgets in the model. Note this will only work well for simple apps with a relatively small state space.

Parameters:
  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for JSON filename

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=False)) – Whether to report progress

  • states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

extend(objects: Iterable[Any]) None[source]#

Extends the objects on this layout with a list.

Parameters:

(list) (objects) –

get_root(doc: Optional[Document] = None, comm: Optional[Comm] = None, preprocess: bool = True) Model[source]#

Returns the root model and applies pre-processing hooks

Parameters:
  • doc (bokeh.Document) – Bokeh document the bokeh model will be attached to.

  • comm (pyviz_comms.Comm) – Optional pyviz_comms when working in notebook

  • preprocess (boolean (default=True)) – Whether to run preprocessing hooks

Return type:

Returns the bokeh model corresponding to this panel object

index(object) int[source]#

Returns the integer index of the supplied object in the list of objects.

Parameters:

(object) (obj) –

Returns:

index (int)

Return type:

Integer index of the object in the layout.

insert(index: int, obj: Any) None[source]#

Inserts an object in the layout at the specified index.

Parameters:
  • (int) (index) –

  • (object) (object) –

jscallback(args: Dict[str, Any] = {}, **callbacks: str) Callback[source]#

Allows defining a JS callback to be triggered when a property changes on the source object. The keyword arguments define the properties that trigger a callback and the JS code that gets executed.

Parameters:
  • args (dict) – A mapping of objects to make available to the JS callback

  • **callbacks (dict) – A mapping between properties on the source model and the code to execute when that property changes

Returns:

callback – The Callback which can be used to disable the callback.

Return type:

Callback

Links properties on the this Reactive object to those on the target Reactive object in JS code.

Supports two modes, either specify a mapping between the source and target model properties as keywords or provide a dictionary of JS code snippets which maps from the source parameter to a JS code snippet which is executed when the property changes.

Parameters:
  • target (panel.viewable.Viewable | bokeh.model.Model | holoviews.core.dimension.Dimensioned) – The target to link the value to.

  • code (dict) – Custom code which will be executed when the widget value changes.

  • args (dict) – A mapping of objects to make available to the JS callback

  • bidirectional (boolean) – Whether to link source and target bi-directionally

  • **links (dict) – A mapping between properties on the source model and the target model property to link it to.

Returns:

link – The GenericLink which can be used unlink the widget and the target model.

Return type:

GenericLink

Links the parameters on this Reactive object to attributes on the target Parameterized object.

Supports two modes, either specify a mapping between the source and target object parameters as keywords or provide a dictionary of callbacks which maps from the source parameter to a callback which is triggered when the parameter changes.

Parameters:
  • target (param.Parameterized) – The target object of the link.

  • callbacks (dict | None) – Maps from a parameter in the source object to a callback.

  • bidirectional (bool) – Whether to link source and target bi-directionally

  • **links (dict) – Maps between parameters on this object to the parameters on the supplied object.

pop(index: int) Viewable[source]#

Pops an item from the layout by index.

Parameters:

(int) (index) –

remove(obj: Viewable) None[source]#

Removes an object from the layout.

Parameters:

(object) (obj) –

respond()[source]#

Executes the callback with the latest message in the chat log.

reverse() None[source]#

Reverses the objects in the layout.

save(filename: str | os.PathLike | IO, title: Optional[str] = None, resources: bokeh.resources.Resources | None = None, template: str | jinja2.environment.Template | None = None, template_variables: Dict[str, Any] = {}, embed: bool = False, max_states: int = 1000, max_opts: int = 3, embed_json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = True, embed_states: Dict[Any, Any] = {}, as_png: bool | None = None, **kwargs) None[source]#

Saves Panel objects to file.

Parameters:
  • filename (str or file-like object) – Filename to save the plot to

  • title (string) – Optional title for the plot

  • resources (bokeh resources) – One of the valid bokeh.resources (e.g. CDN or INLINE)

  • template – passed to underlying io.save

  • template_variables – passed to underlying io.save

  • embed (bool) – Whether the state space should be embedded in the saved file.

  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • embed_json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for the auto-generated json directory

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=True)) – Whether to report progress

  • embed_states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

  • as_png (boolean (default=None)) – To save as a .png. If None save_png will be true if filename is string and ends with png.

select(selector=None)[source]#

Iterates over the ChatInterface and any potential children in the applying the selector.

Parameters:

selector (type or callable or None) – The selector allows selecting a subset of Viewables by declaring a type or callable function to filter by.

Returns:

viewables

Return type:

list(Viewable)

send(value: panel.chat.message.ChatMessage | dict | Any, user: str | None = None, avatar: str | bytes | _io.BytesIO | None = None, respond: bool = True) panel.chat.message.ChatMessage | None[source]#

Sends a value and creates a new message in the chat log.

If respond is True, additionally executes the callback, if provided.

Parameters:
  • value (ChatMessage | dict | Any) – The message contents to send.

  • user (str | None) – The user to send as; overrides the message message’s user if provided.

  • avatar (str | bytes | BytesIO | None) – The avatar to use; overrides the message message’s avatar if provided.

  • respond (bool) – Whether to execute the callback.

Return type:

The message that was created.

serialize(exclude_users: Optional[List[str]] = None, filter_by: Optional[Callable] = None, format: Literal['transformers'] = 'transformers', custom_serializer: Optional[Callable] = None, **serialize_kwargs)[source]#

Exports the chat log.

Parameters:
  • format (str) – The format to export the chat log as; currently only supports “transformers”.

  • exclude_users (list(str) | None) – A list of user (case insensitive names) to exclude from serialization. If not provided, defaults to [“help”]. This will be executed before filter_by.

  • filter_by (callable) – A function to filter the chat log by. The function must accept and return a list of ChatMessage objects.

  • custom_serializer (callable) – A custom function to format the ChatMessage’s object. The function must accept one positional argument, the ChatMessage object, and return a string. If not provided, uses the serialize method on ChatMessage.

  • **serialize_kwargs

    Additional keyword arguments to use for the specified format.

    • format=”transformers” role_names : dict(str, str | list(str)) | None

      A dictionary mapping the role to the ChatMessage’s user name. Defaults to {“user”: [“user”], “assistant”: [self.callback_user]} if not set. The keys and values are case insensitive as the strings will all be lowercased. The values can be a string or a list of strings, e.g. {“user”: “user”, “assistant”: [“executor”, “langchain”]}.

      default_rolestr

      The default role to use if the user name is not found in role_names. If this is set to None, raises a ValueError if the user name is not found.

Return type:

The chat log serialized in the specified format.

servable(title: Optional[str] = None, location: bool | 'Location' = True, area: str = 'main', target: Optional[str] = None) ServableMixin[source]#

Serves the object or adds it to the configured pn.state.template if in a panel serve context, writes to the DOM if in a pyodide context and returns the Panel object to allow it to display itself in a notebook context.

Parameters:
  • title (str) – A string title to give the Document (if served as an app)

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

  • area (str (deprecated)) – The area of a template to add the component too. Only has an effect if pn.config.template has been set.

  • target (str) – Target area to write to. If a template has been configured on pn.config.template this refers to the target area in the template while in pyodide this refers to the ID of the DOM node to write to.

Return type:

The Panel object itself

server_doc(doc: Optional[Document] = None, title: Optional[str] = None, location: bool | 'Location' = True) Document[source]#

Returns a serveable bokeh Document with the panel attached

Parameters:
  • doc (bokeh.Document (optional)) – The bokeh Document to attach the panel to as a root, defaults to bokeh.io.curdoc()

  • title (str) – A string title to give the Document

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

doc – The bokeh document the panel was attached to

Return type:

bokeh.Document

show(title: Optional[str] = None, port: int = 0, address: Optional[str] = None, websocket_origin: Optional[str] = None, threaded: bool = False, verbose: bool = True, open: bool = True, location: bool | 'Location' = True, **kwargs) StoppableThread' | 'Server[source]#

Starts a Bokeh server and displays the Viewable in a new tab.

Parameters:
  • title (str | None) – A string title to give the Document (if served as an app)

  • port (int (optional, default=0)) – Allows specifying a specific port

  • address (str) – The address the server should listen on for HTTP requests.

  • websocket_origin (str or list(str) (optional)) – A list of hosts that can connect to the websocket. This is typically required when embedding a server app in an external web site. If None, “localhost” is used.

  • threaded (boolean (optional, default=False)) – Whether to launch the Server on a separate thread, allowing interactive use.

  • verbose (boolean (optional, default=True)) – Whether to print the address and port

  • open (boolean (optional, default=True)) – Whether to open the server in a new browser tab

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

server – Returns the Bokeh server instance or the thread the server was launched on (if threaded=True)

Return type:

bokeh.server.Server or panel.io.server.StoppableThread

stop() bool[source]#

Cancels the current callback task if possible.

Return type:

Whether the task was successfully stopped or done.

stream(value: str | dict | panel.chat.message.ChatMessage, user: str | None = None, avatar: str | bytes | _io.BytesIO | None = None, message: panel.chat.message.ChatMessage | None = None, replace: bool = False) panel.chat.message.ChatMessage | None[source]#

Streams a token and updates the provided message, if provided. Otherwise creates a new message in the chat log, so be sure the returned message is passed back into the method, e.g. message = chat.stream(token, message=message).

This method is primarily for outputs that are not generators– notably LangChain. For most cases, use the send method instead.

Parameters:
  • value (str | dict | ChatMessage) – The new token value to stream.

  • user (str | None) – The user to stream as; overrides the message’s user if provided.

  • avatar (str | bytes | BytesIO | None) – The avatar to use; overrides the message’s avatar if provided.

  • message (ChatMessage | None) – The message to update.

  • replace (bool) – Whether to replace the existing text when streaming a string or dict.

Return type:

The message that was updated.

undo(count: int = 1) List[Any][source]#

Removes the last count of messages from the chat log and returns them.

Parameters:

count (int) – The number of messages to remove, starting from the last message.

Return type:

The messages that were removed.

class panel.chat.ChatInterface(*objects, **params)[source]#

Bases: ChatFeed

High level widget that contains the chat log and the chat input.

Reference: https://panel.holoviz.org/reference/chat/ChatInterface.html

Example:

>>> async def repeat_contents(contents, user, instance):
>>>     yield contents
>>> chat_interface = ChatInterface(
    callback=repeat_contents, widgets=[TextInput(), FileInput()]
)

Parameters inherited from:

panel.viewable.Layoutable: align, aspect_ratio, css_classes, design, height, min_width, min_height, max_width, max_height, styles, stylesheets, tags, width, width_policy, height_policy, sizing_mode, visible

panel.viewable.Viewable: loading

panel.layout.base.ListPanel: scroll

panel.chat.feed.ChatFeed: margin, objects, auto_scroll_limit, callback, callback_exception, callback_user, card_params, collapsible, disabled, message_params, header, help_text, placeholder_text, placeholder_params, placeholder_threshold, renderers, load_buffer, scroll_button_threshold, show_activity_dot, view_latest, _placeholder, _callback_state, _callback_trigger, _disabled_stack

auto_send_types = param.List(allow_refs=False, bounds=(0, None), default=[], label=’Auto send types’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142338250>)

The widget types to automatically send when the user presses enter or clicks away from the widget. If not provided, defaults to [TextInput].

avatar = param.ClassSelector(allow_None=True, allow_refs=False, class_=(<class ‘str’>, <class ‘_io.BytesIO’>, <class ‘bytes’>, <class ‘panel.pane.image.ImageBase’>), label=’Avatar’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142339410>)

The avatar to use for the user. Can be a single character text, an emoji, or anything supported by pn.pane.Image. If not set, uses the first character of the name.

reset_on_send = param.Boolean(allow_refs=False, default=True, label=’Reset on send’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142339110>)

Whether to reset the widget’s value after sending a message; has no effect for TextInput.

show_send = param.Boolean(allow_refs=False, default=True, label=’Show send’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142338890>)

Whether to show the send button.

show_stop = param.Boolean(allow_refs=False, default=True, label=’Show stop’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14233ba10>)

Whether to show the stop button temporarily replacing the send button during callback; has no effect if callback is not async.

show_rerun = param.Boolean(allow_refs=False, default=True, label=’Show rerun’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142339d50>)

Whether to show the rerun button.

show_undo = param.Boolean(allow_refs=False, default=True, label=’Show undo’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14233a150>)

Whether to show the undo button.

show_clear = param.Boolean(allow_refs=False, default=True, label=’Show clear’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14233a650>)

Whether to show the clear button.

show_button_name = param.Boolean(allow_None=True, allow_refs=False, label=’Show button name’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1423382d0>)

Whether to show the button name.

user = param.String(allow_refs=False, default=’User’, label=’User’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14233a650>)

Name of the ChatInterface user.

widgets = param.ClassSelector(allow_None=True, allow_refs=False, class_=(<class ‘panel.widgets.base.Widget’>, <class ‘list’>), label=’Widgets’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142339e90>)

Widgets to use for the input. If not provided, defaults to [TextInput].

button_properties = param.Dict(allow_refs=False, class_=<class ‘dict’>, default={}, label=’Button properties’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14233ba10>)

Allows addition of functionality or customization of buttons by supplying a mapping from the button name to a dictionary containing the icon, callback, post_callback, and/or js_on_click keys. If the button names correspond to default buttons (send, rerun, undo, clear), the default icon can be updated and if a callback key value pair is provided, the specified callback functionality runs before the existing one. For button names that don’t match existing ones, new buttons are created and must include a callback, post_callback, and/or js_on_click key. The provided callbacks should have a signature that accepts two positional arguments: instance (the ChatInterface instance) and event (the button click event). The js_on_click key should be a str or dict. If str, provide the JavaScript code; else if dict, it must have a code key, containing the JavaScript code to execute when the button is clicked, and optionally an args key, containing dictionary of arguments to pass to the JavaScript code.

_widgets = param.Dict(allow_refs=False, class_=<class ‘dict’>, default={}, label=’ widgets’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142339e90>)

The input widgets.

_input_container = param.ClassSelector(allow_None=True, allow_refs=False, class_=<class ‘panel.layout.base.Row’>, label=’ input container’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142339110>)

The input message row that wraps the input layout (Tabs / Row) to easily swap between Tabs and Rows, depending on number of widgets.

_input_layout = param.ClassSelector(allow_None=True, allow_refs=False, class_=(<class ‘panel.layout.base.Row’>, <class ‘panel.layout.tabs.Tabs’>), label=’ input layout’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142338890>)

The input layout that contains the input widgets.

_button_data = param.Dict(allow_refs=False, class_=<class ‘dict’>, default={}, label=’ button data’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142339110>)

Metadata and data related to the buttons.

_buttons = param.Dict(allow_refs=False, class_=<class ‘dict’>, default={}, label=’ buttons’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142338890>)

The rendered buttons.

property active: int#

The currently active input widget tab index; -1 if there is only one widget available which is not in a tab.

Return type:

The active input widget tab index.

property active_widget: Widget#

The currently active widget.

Return type:

The active widget.

append(obj: Any) None[source]#

Appends an object to the layout.

Parameters:

(object) (obj) –

clear() List[Any][source]#

Clears the chat log and returns the messages that were cleared.

Return type:

The messages that were cleared.

clone(*objects: Any, **params: Any) ListLike[source]#

Makes a copy of the layout sharing the same parameters.

Parameters:
  • objects (Objects to add to the cloned layout.) –

  • params (Keyword arguments override the parameters on the clone.) –

Return type:

Cloned layout object

controls(parameters: List[str] = [], jslink: bool = True, **kwargs) Panel[source]#

Creates a set of widgets which allow manipulating the parameters on this instance. By default all parameters which support linking are exposed, but an explicit list of parameters can be provided.

Parameters:
  • parameters (list(str)) – An explicit list of parameters to return controls for.

  • jslink (bool) – Whether to use jslinks instead of Python based links. This does not allow using all types of parameters.

  • kwargs (dict) – Additional kwargs to pass to the Param pane(s) used to generate the controls widgets.

Return type:

A layout of the controls

embed(max_states: int = 1000, max_opts: int = 3, json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = False, states={}) None[source]#

Renders a static version of a panel in a notebook by evaluating the set of states defined by the widgets in the model. Note this will only work well for simple apps with a relatively small state space.

Parameters:
  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for JSON filename

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=False)) – Whether to report progress

  • states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

extend(objects: Iterable[Any]) None[source]#

Extends the objects on this layout with a list.

Parameters:

(list) (objects) –

get_root(doc: Optional[Document] = None, comm: Optional[Comm] = None, preprocess: bool = True) Model[source]#

Returns the root model and applies pre-processing hooks

Parameters:
  • doc (bokeh.Document) – Bokeh document the bokeh model will be attached to.

  • comm (pyviz_comms.Comm) – Optional pyviz_comms when working in notebook

  • preprocess (boolean (default=True)) – Whether to run preprocessing hooks

Return type:

Returns the bokeh model corresponding to this panel object

index(object) int[source]#

Returns the integer index of the supplied object in the list of objects.

Parameters:

(object) (obj) –

Returns:

index (int)

Return type:

Integer index of the object in the layout.

insert(index: int, obj: Any) None[source]#

Inserts an object in the layout at the specified index.

Parameters:
  • (int) (index) –

  • (object) (object) –

jscallback(args: Dict[str, Any] = {}, **callbacks: str) Callback[source]#

Allows defining a JS callback to be triggered when a property changes on the source object. The keyword arguments define the properties that trigger a callback and the JS code that gets executed.

Parameters:
  • args (dict) – A mapping of objects to make available to the JS callback

  • **callbacks (dict) – A mapping between properties on the source model and the code to execute when that property changes

Returns:

callback – The Callback which can be used to disable the callback.

Return type:

Callback

Links properties on the this Reactive object to those on the target Reactive object in JS code.

Supports two modes, either specify a mapping between the source and target model properties as keywords or provide a dictionary of JS code snippets which maps from the source parameter to a JS code snippet which is executed when the property changes.

Parameters:
  • target (panel.viewable.Viewable | bokeh.model.Model | holoviews.core.dimension.Dimensioned) – The target to link the value to.

  • code (dict) – Custom code which will be executed when the widget value changes.

  • args (dict) – A mapping of objects to make available to the JS callback

  • bidirectional (boolean) – Whether to link source and target bi-directionally

  • **links (dict) – A mapping between properties on the source model and the target model property to link it to.

Returns:

link – The GenericLink which can be used unlink the widget and the target model.

Return type:

GenericLink

Links the parameters on this Reactive object to attributes on the target Parameterized object.

Supports two modes, either specify a mapping between the source and target object parameters as keywords or provide a dictionary of callbacks which maps from the source parameter to a callback which is triggered when the parameter changes.

Parameters:
  • target (param.Parameterized) – The target object of the link.

  • callbacks (dict | None) – Maps from a parameter in the source object to a callback.

  • bidirectional (bool) – Whether to link source and target bi-directionally

  • **links (dict) – Maps between parameters on this object to the parameters on the supplied object.

pop(index: int) Viewable[source]#

Pops an item from the layout by index.

Parameters:

(int) (index) –

remove(obj: Viewable) None[source]#

Removes an object from the layout.

Parameters:

(object) (obj) –

respond()[source]#

Executes the callback with the latest message in the chat log.

reverse() None[source]#

Reverses the objects in the layout.

save(filename: str | os.PathLike | IO, title: Optional[str] = None, resources: bokeh.resources.Resources | None = None, template: str | jinja2.environment.Template | None = None, template_variables: Dict[str, Any] = {}, embed: bool = False, max_states: int = 1000, max_opts: int = 3, embed_json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = True, embed_states: Dict[Any, Any] = {}, as_png: bool | None = None, **kwargs) None[source]#

Saves Panel objects to file.

Parameters:
  • filename (str or file-like object) – Filename to save the plot to

  • title (string) – Optional title for the plot

  • resources (bokeh resources) – One of the valid bokeh.resources (e.g. CDN or INLINE)

  • template – passed to underlying io.save

  • template_variables – passed to underlying io.save

  • embed (bool) – Whether the state space should be embedded in the saved file.

  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • embed_json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for the auto-generated json directory

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=True)) – Whether to report progress

  • embed_states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

  • as_png (boolean (default=None)) – To save as a .png. If None save_png will be true if filename is string and ends with png.

select(selector=None)[source]#

Iterates over the ChatInterface and any potential children in the applying the selector.

Parameters:

selector (type or callable or None) – The selector allows selecting a subset of Viewables by declaring a type or callable function to filter by.

Returns:

viewables

Return type:

list(Viewable)

send(value: panel.chat.message.ChatMessage | dict | Any, user: str | None = None, avatar: str | bytes | _io.BytesIO | None = None, respond: bool = True) panel.chat.message.ChatMessage | None[source]#

Sends a value and creates a new message in the chat log.

If respond is True, additionally executes the callback, if provided.

Parameters:
  • value (ChatMessage | dict | Any) – The message contents to send.

  • user (str | None) – The user to send as; overrides the message message’s user if provided. Will default to the user parameter.

  • avatar (str | bytes | BytesIO | None) – The avatar to use; overrides the message message’s avatar if provided. Will default to the avatar parameter.

  • respond (bool) – Whether to execute the callback.

Return type:

The message that was created.

serialize(exclude_users: Optional[List[str]] = None, filter_by: Optional[Callable] = None, format: Literal['transformers'] = 'transformers', custom_serializer: Optional[Callable] = None, **serialize_kwargs)[source]#

Exports the chat log.

Parameters:
  • format (str) – The format to export the chat log as; currently only supports “transformers”.

  • exclude_users (list(str) | None) – A list of user (case insensitive names) to exclude from serialization. If not provided, defaults to [“help”]. This will be executed before filter_by.

  • filter_by (callable) – A function to filter the chat log by. The function must accept and return a list of ChatMessage objects.

  • custom_serializer (callable) – A custom function to format the ChatMessage’s object. The function must accept one positional argument, the ChatMessage object, and return a string. If not provided, uses the serialize method on ChatMessage.

  • **serialize_kwargs

    Additional keyword arguments to use for the specified format.

    • format=”transformers” role_names : dict(str, str | list(str)) | None

      A dictionary mapping the role to the ChatMessage’s user name. Defaults to {“user”: [“user”], “assistant”: [self.callback_user]} if not set. The keys and values are case insensitive as the strings will all be lowercased. The values can be a string or a list of strings, e.g. {“user”: “user”, “assistant”: [“executor”, “langchain”]}.

      default_rolestr

      The default role to use if the user name is not found in role_names. If this is set to None, raises a ValueError if the user name is not found.

Return type:

The chat log serialized in the specified format.

servable(title: Optional[str] = None, location: bool | 'Location' = True, area: str = 'main', target: Optional[str] = None) ServableMixin[source]#

Serves the object or adds it to the configured pn.state.template if in a panel serve context, writes to the DOM if in a pyodide context and returns the Panel object to allow it to display itself in a notebook context.

Parameters:
  • title (str) – A string title to give the Document (if served as an app)

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

  • area (str (deprecated)) – The area of a template to add the component too. Only has an effect if pn.config.template has been set.

  • target (str) – Target area to write to. If a template has been configured on pn.config.template this refers to the target area in the template while in pyodide this refers to the ID of the DOM node to write to.

Return type:

The Panel object itself

server_doc(doc: Optional[Document] = None, title: Optional[str] = None, location: bool | 'Location' = True) Document[source]#

Returns a serveable bokeh Document with the panel attached

Parameters:
  • doc (bokeh.Document (optional)) – The bokeh Document to attach the panel to as a root, defaults to bokeh.io.curdoc()

  • title (str) – A string title to give the Document

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

doc – The bokeh document the panel was attached to

Return type:

bokeh.Document

show(title: Optional[str] = None, port: int = 0, address: Optional[str] = None, websocket_origin: Optional[str] = None, threaded: bool = False, verbose: bool = True, open: bool = True, location: bool | 'Location' = True, **kwargs) StoppableThread' | 'Server[source]#

Starts a Bokeh server and displays the Viewable in a new tab.

Parameters:
  • title (str | None) – A string title to give the Document (if served as an app)

  • port (int (optional, default=0)) – Allows specifying a specific port

  • address (str) – The address the server should listen on for HTTP requests.

  • websocket_origin (str or list(str) (optional)) – A list of hosts that can connect to the websocket. This is typically required when embedding a server app in an external web site. If None, “localhost” is used.

  • threaded (boolean (optional, default=False)) – Whether to launch the Server on a separate thread, allowing interactive use.

  • verbose (boolean (optional, default=True)) – Whether to print the address and port

  • open (boolean (optional, default=True)) – Whether to open the server in a new browser tab

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

server – Returns the Bokeh server instance or the thread the server was launched on (if threaded=True)

Return type:

bokeh.server.Server or panel.io.server.StoppableThread

stop() bool[source]#

Cancels the current callback task if possible.

Return type:

Whether the task was successfully stopped or done.

stream(value: str | dict | panel.chat.message.ChatMessage, user: str | None = None, avatar: str | bytes | _io.BytesIO | None = None, message: panel.chat.message.ChatMessage | None = None, replace: bool = False) panel.chat.message.ChatMessage | None[source]#

Streams a token and updates the provided message, if provided. Otherwise creates a new message in the chat log, so be sure the returned message is passed back into the method, e.g. message = chat.stream(token, message=message).

This method is primarily for outputs that are not generators– notably LangChain. For most cases, use the send method instead.

Parameters:
  • value (str | dict | ChatMessage) – The new token value to stream.

  • user (str | None) – The user to stream as; overrides the message’s user if provided. Will default to the user parameter.

  • avatar (str | bytes | BytesIO | None) – The avatar to use; overrides the message’s avatar if provided. Will default to the avatar parameter.

  • message (ChatMessage | None) – The message to update.

  • replace (bool) – Whether to replace the existing text when streaming a string or dict.

Return type:

The message that was updated.

undo(count: int = 1) List[Any][source]#

Removes the last count of messages from the chat log and returns them.

Parameters:

count (int) – The number of messages to remove, starting from the last message.

Return type:

The messages that were removed.

class panel.chat.ChatMessage(object=None, **params)[source]#

Bases: PaneBase

A widget for displaying chat messages with support for various content types.

This widget provides a structured view of chat messages, including features like: - Displaying user avatars, which can be text, emoji, or images. - Showing the user’s name. - Displaying the message timestamp in a customizable format. - Associating reactions with messages and mapping them to icons. - Rendering various content types including text, images, audio, video, and more.

Reference: https://panel.holoviz.org/reference/chat/ChatMessage.html

Example:

>>> ChatMessage(object="Hello world!", user="New User", avatar="😊")

Parameters inherited from:

panel.viewable.Layoutable: align, aspect_ratio, design, height, min_width, min_height, max_height, styles, stylesheets, tags, width, width_policy, height_policy, sizing_mode, visible

panel.viewable.Viewable: loading

panel.pane.base.PaneBase: margin, default_layout

css_classes = param.List(allow_refs=True, bounds=(0, None), default=[‘chat-message’], label=’Css classes’, nested_refs=True, rx=<param.reactive.reactive_ops object at 0x141f28bd0>)

The CSS classes to apply to the widget.

max_width = param.Integer(allow_refs=True, bounds=(0, None), default=1200, inclusive_bounds=(True, True), label=’Max width’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1422f2690>)

Minimal width of the component (in pixels) if width is adjustable.

object = param.Parameter(allow_None=True, allow_refs=False, label=’Object’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14234d190>)

The message contents. Can be any Python object that panel can display.

avatar = param.ClassSelector(allow_refs=False, class_=(<class ‘str’>, <class ‘_io.BytesIO’>, <class ‘bytes’>, <class ‘panel.pane.image.ImageBase’>), default=’’, label=’Avatar’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1422f0d10>)

The avatar to use for the user. Can be a single character text, an emoji, or anything supported by pn.pane.Image. If not set, checks if the user is available in the default_avatars mapping; else uses the first character of the name.

avatar_lookup = param.Callable(allow_None=True, allow_refs=False, label=’Avatar lookup’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14234ddd0>)

A function that can lookup an avatar from a user name. The function signature should be (user: str) -> Avatar. If this is set, default_avatars is disregarded.

default_avatars = param.Dict(allow_refs=False, class_=<class ‘dict’>, default={‘client’: ‘🧑’, ‘customer’: ‘🧑’, ‘employee’: ‘🧑’, ‘human’: ‘🧑’, ‘person’: ‘🧑’, ‘user’: ‘🧑’, ‘agent’: ‘🤖’, ‘ai’: ‘🤖’, ‘assistant’: ‘🤖’, ‘bot’: ‘🤖’, ‘chatbot’: ‘🤖’, ‘machine’: ‘🤖’, ‘robot’: ‘🤖’, ‘system’: ‘⚙️’, ‘exception’: ‘❌’, ‘error’: ‘❌’, ‘help’: ‘❓’, ‘adult’: ‘🧑’, ‘baby’: ‘👶’, ‘boy’: ‘👦’, ‘child’: ‘🧒’, ‘girl’: ‘👧’, ‘man’: ‘👨’, ‘woman’: ‘👩’, ‘chatgpt’: ‘{dist_path}assets/logo/gpt-3.svg’, ‘gpt3’: ‘{dist_path}assets/logo/gpt-3.svg’, ‘gpt4’: ‘{dist_path}assets/logo/gpt-4.svg’, ‘dalle’: ‘{dist_path}assets/logo/gpt-4.svg’, ‘openai’: ‘{dist_path}assets/logo/gpt-4.svg’, ‘huggingface’: ‘🤗’, ‘calculator’: ‘🧮’, ‘langchain’: ‘🦜’, ‘retriever’: ‘📄’, ‘tool’: ‘🛠️’, ‘translator’: ‘🌐’, ‘wolfram’: ‘{dist_path}assets/logo/wolfram.svg’, ‘wolfram alpha’: ‘{dist_path}assets/logo/wolfram.svg’, ‘llama’: ‘🦙’, ‘llama2’: ‘🐪’, ‘plot’: ‘📊’, ‘lumen’: ‘{dist_path}assets/logo/lumen.svg’, ‘holoviews’: ‘{dist_path}assets/logo/holoviews.svg’, ‘hvplot’: ‘{dist_path}assets/logo/hvplot.svg’, ‘panel’: ‘{dist_path}images/icon-vector.svg’}, label=’Default avatars’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1422f0d10>)

A default mapping of user names to their corresponding avatars to use when the user is specified but the avatar is. You can modify, but not replace the dictionary.

footer_objects = param.List(allow_refs=False, bounds=(0, None), default=[], label=’Footer objects’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14234f5d0>)

A list of objects to display in the column of the footer of the message.

header_objects = param.List(allow_refs=False, bounds=(0, None), default=[], label=’Header objects’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1422f0d10>)

A list of objects to display in the row of the header of the message.

reactions = param.List(allow_refs=False, bounds=(0, None), default=[], label=’Reactions’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14234ed90>)

Reactions to associate with the message.

reaction_icons = param.ClassSelector(allow_None=True, allow_refs=False, class_=<class ‘panel.chat.icon.ChatReactionIcons’>, label=’Reaction icons’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1422f0d10>)

A mapping of reactions to their reaction icons; if not provided defaults to {“favorite”: “heart”}.

timestamp = param.Date(allow_None=True, allow_refs=False, inclusive_bounds=(True, True), label=’Timestamp’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1413bb190>)

Timestamp of the message. Defaults to the creation time.

timestamp_format = param.String(allow_refs=False, default=’%H:%M’, label=’Timestamp format’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1422f2690>)

The timestamp format.

timestamp_tz = param.String(allow_None=True, allow_refs=False, label=’Timestamp tz’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14234c450>)

The timezone to used for the creation timestamp; only applicable if timestamp is not set. If None, tries to use pn.state.browser_info.timezone, else, the default tz of datetime.datetime.now(); see zoneinfo.available_timezones() for a list of valid timezones.

show_avatar = param.Boolean(allow_refs=False, default=True, label=’Show avatar’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1422f2fd0>)

Whether to display the avatar of the user.

show_user = param.Boolean(allow_refs=False, default=True, label=’Show user’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14234fc90>)

Whether to display the name of the user.

show_timestamp = param.Boolean(allow_refs=False, default=True, label=’Show timestamp’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1422f2fd0>)

Whether to display the timestamp of the message.

show_reaction_icons = param.Boolean(allow_refs=False, default=True, label=’Show reaction icons’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14234cb10>)

Whether to display the reaction icons.

show_copy_icon = param.Boolean(allow_refs=False, default=True, label=’Show copy icon’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1422f2690>)

Whether to display the copy icon.

show_activity_dot = param.Boolean(allow_refs=False, default=False, label=’Show activity dot’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14234f150>)

Whether to show the activity dot.

renderers = param.HookList(allow_refs=False, bounds=(0, None), default=[], label=’Renderers’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x141feba50>)

A callable or list of callables that accept the object and return a Panel object to render the object. If a list is provided, will attempt to use the first renderer that does not raise an exception. If None, will attempt to infer the renderer from the object.

user = param.Parameter(allow_refs=False, default=’User’, label=’User’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14234f150>)

Name of the user who sent the message.

classmethod applies(obj: Any) float | bool | None[source]#

Returns boolean or float indicating whether the Pane can render the object.

If the priority of the pane is set to None, this method may also be used to define a float priority depending on the object being rendered.

clone(object: Optional[Any] = None, **params) T[source]#

Makes a copy of the Pane sharing the same parameters.

Parameters:
  • object (Optional new object to render) –

  • params (Keyword arguments override the parameters on the clone.) –

Return type:

Cloned Pane object

controls(parameters: List[str] = [], jslink: bool = True, **kwargs) Panel[source]#

Creates a set of widgets which allow manipulating the parameters on this instance. By default all parameters which support linking are exposed, but an explicit list of parameters can be provided.

Parameters:
  • parameters (list(str)) – An explicit list of parameters to return controls for.

  • jslink (bool) – Whether to use jslinks instead of Python based links. This does not allow using all types of parameters.

  • kwargs (dict) – Additional kwargs to pass to the Param pane(s) used to generate the controls widgets.

Return type:

A layout of the controls

default_layout[source]#

alias of Row

embed(max_states: int = 1000, max_opts: int = 3, json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = False, states={}) None[source]#

Renders a static version of a panel in a notebook by evaluating the set of states defined by the widgets in the model. Note this will only work well for simple apps with a relatively small state space.

Parameters:
  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for JSON filename

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=False)) – Whether to report progress

  • states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

classmethod get_pane_type(obj: Any, **kwargs) Type[PaneBase][source]#

Returns the applicable Pane type given an object by resolving the precedence of all types whose applies method declares that the object is supported.

Parameters:

(object) (obj) –

Return type:

The applicable Pane type with the highest precedence.

get_root(doc: Optional[Document] = None, comm: Comm | None = None, preprocess: bool = True) Model[source]#

Returns the root model and applies pre-processing hooks

Parameters:
  • doc (bokeh.document.Document) – Optional Bokeh document the bokeh model will be attached to.

  • comm (pyviz_comms.Comm) – Optional pyviz_comms when working in notebook

  • preprocess (bool (default=True)) – Whether to run preprocessing hooks

Return type:

Returns the bokeh model corresponding to this panel object

jscallback(args: Dict[str, Any] = {}, **callbacks: str) Callback[source]#

Allows defining a JS callback to be triggered when a property changes on the source object. The keyword arguments define the properties that trigger a callback and the JS code that gets executed.

Parameters:
  • args (dict) – A mapping of objects to make available to the JS callback

  • **callbacks (dict) – A mapping between properties on the source model and the code to execute when that property changes

Returns:

callback – The Callback which can be used to disable the callback.

Return type:

Callback

Links properties on the this Reactive object to those on the target Reactive object in JS code.

Supports two modes, either specify a mapping between the source and target model properties as keywords or provide a dictionary of JS code snippets which maps from the source parameter to a JS code snippet which is executed when the property changes.

Parameters:
  • target (panel.viewable.Viewable | bokeh.model.Model | holoviews.core.dimension.Dimensioned) – The target to link the value to.

  • code (dict) – Custom code which will be executed when the widget value changes.

  • args (dict) – A mapping of objects to make available to the JS callback

  • bidirectional (boolean) – Whether to link source and target bi-directionally

  • **links (dict) – A mapping between properties on the source model and the target model property to link it to.

Returns:

link – The GenericLink which can be used unlink the widget and the target model.

Return type:

GenericLink

Links the parameters on this Reactive object to attributes on the target Parameterized object.

Supports two modes, either specify a mapping between the source and target object parameters as keywords or provide a dictionary of callbacks which maps from the source parameter to a callback which is triggered when the parameter changes.

Parameters:
  • target (param.Parameterized) – The target object of the link.

  • callbacks (dict | None) – Maps from a parameter in the source object to a callback.

  • bidirectional (bool) – Whether to link source and target bi-directionally

  • **links (dict) – Maps between parameters on this object to the parameters on the supplied object.

save(filename: str | os.PathLike | IO, title: Optional[str] = None, resources: bokeh.resources.Resources | None = None, template: str | jinja2.environment.Template | None = None, template_variables: Dict[str, Any] = {}, embed: bool = False, max_states: int = 1000, max_opts: int = 3, embed_json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = True, embed_states: Dict[Any, Any] = {}, as_png: bool | None = None, **kwargs) None[source]#

Saves Panel objects to file.

Parameters:
  • filename (str or file-like object) – Filename to save the plot to

  • title (string) – Optional title for the plot

  • resources (bokeh resources) – One of the valid bokeh.resources (e.g. CDN or INLINE)

  • template – passed to underlying io.save

  • template_variables – passed to underlying io.save

  • embed (bool) – Whether the state space should be embedded in the saved file.

  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • embed_json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for the auto-generated json directory

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=True)) – Whether to report progress

  • embed_states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

  • as_png (boolean (default=None)) – To save as a .png. If None save_png will be true if filename is string and ends with png.

select(selector: Optional[Union[type, Callable[[Viewable], bool]]] = None) List[Viewable][source]#

Iterates over the Viewable and any potential children in the applying the Selector.

Parameters:

selector (type or callable or None) – The selector allows selecting a subset of Viewables by declaring a type or callable function to filter by.

Returns:

viewables

Return type:

list(Viewable)

serialize(prefix_with_viewable_label: bool = True, prefix_with_container_label: bool = True) str[source]#

Format the object to a string.

Parameters:
  • obj (Any) – The object to format.

  • prefix_with_viewable_label (bool) – Whether to include the name of the Viewable, or type of the viewable if no name is specified.

  • prefix_with_container_label (bool) – Whether to include the name of the container, or type of the container if no name is specified.

Returns:

The serialized string.

Return type:

str

servable(title: Optional[str] = None, location: bool | 'Location' = True, area: str = 'main', target: Optional[str] = None) ServableMixin[source]#

Serves the object or adds it to the configured pn.state.template if in a panel serve context, writes to the DOM if in a pyodide context and returns the Panel object to allow it to display itself in a notebook context.

Parameters:
  • title (str) – A string title to give the Document (if served as an app)

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

  • area (str (deprecated)) – The area of a template to add the component too. Only has an effect if pn.config.template has been set.

  • target (str) – Target area to write to. If a template has been configured on pn.config.template this refers to the target area in the template while in pyodide this refers to the ID of the DOM node to write to.

Return type:

The Panel object itself

server_doc(doc: Optional[Document] = None, title: Optional[str] = None, location: bool | 'Location' = True) Document[source]#

Returns a serveable bokeh Document with the panel attached

Parameters:
  • doc (bokeh.Document (optional)) – The bokeh Document to attach the panel to as a root, defaults to bokeh.io.curdoc()

  • title (str) – A string title to give the Document

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

doc – The bokeh document the panel was attached to

Return type:

bokeh.Document

show(title: Optional[str] = None, port: int = 0, address: Optional[str] = None, websocket_origin: Optional[str] = None, threaded: bool = False, verbose: bool = True, open: bool = True, location: bool | 'Location' = True, **kwargs) StoppableThread' | 'Server[source]#

Starts a Bokeh server and displays the Viewable in a new tab.

Parameters:
  • title (str | None) – A string title to give the Document (if served as an app)

  • port (int (optional, default=0)) – Allows specifying a specific port

  • address (str) – The address the server should listen on for HTTP requests.

  • websocket_origin (str or list(str) (optional)) – A list of hosts that can connect to the websocket. This is typically required when embedding a server app in an external web site. If None, “localhost” is used.

  • threaded (boolean (optional, default=False)) – Whether to launch the Server on a separate thread, allowing interactive use.

  • verbose (boolean (optional, default=True)) – Whether to print the address and port

  • open (boolean (optional, default=True)) – Whether to open the server in a new browser tab

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

server – Returns the Bokeh server instance or the thread the server was launched on (if threaded=True)

Return type:

bokeh.server.Server or panel.io.server.StoppableThread

stream(token: str, replace: bool = False)[source]#

Updates the message with the new token traversing the object to allow updating nested objects. When traversing a nested Panel the last object that supports rendering strings is updated, e.g. in a layout of Column(Markdown(…), Image(…)) the Markdown pane is updated.

Parameters:
  • token (str) – The token to stream to the text pane.

  • replace (bool (default=False)) – Whether to replace the existing text.

update(value: dict | panel.chat.message.ChatMessage | Any, user: str | None = None, avatar: str | bytes | _io.BytesIO | None = None)[source]#

Updates the message with a new value, user and avatar.

Parameters:
  • value (ChatMessage | dict | Any) – The message contents to send.

  • user (str | None) – The user to send as; overrides the message message’s user if provided.

  • avatar (str | bytes | BytesIO | None) – The avatar to use; overrides the message message’s avatar if provided.

class panel.chat.ChatReactionIcons(*, active_icons, options, value, disabled, loading, align, aspect_ratio, css_classes, design, height, height_policy, margin, max_height, max_width, min_height, min_width, sizing_mode, styles, stylesheets, tags, visible, width, width_policy, name)[source]#

Bases: CompositeWidget

A widget to display reaction icons that can be clicked on.

Parameters:

:param : :type : Example: :param >>> ChatReactionIcons(value=[“like”]: :type >>> ChatReactionIcons(value=[“like”]: “thumb-up”, “dislike”: “thumb-down”}) :param options={“like”: :type options={“like”: “thumb-up”, “dislike”: “thumb-down”})

Parameters inherited from:

panel.viewable.Layoutable: align, aspect_ratio, design, min_width, min_height, max_width, max_height, styles, stylesheets, tags, width_policy, height_policy, sizing_mode, visible

panel.viewable.Viewable: loading

panel.widgets.base.Widget: height, margin, width, disabled

css_classes = param.List(allow_refs=True, bounds=(0, None), default=[‘reaction-icons’], label=’Css classes’, nested_refs=True, rx=<param.reactive.reactive_ops object at 0x142385950>)

The CSS classes of the widget.

active_icons = param.Dict(allow_refs=False, class_=<class ‘dict’>, default={}, label=’Active icons’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14230e3d0>)

The mapping of reactions to their corresponding active icon names. If not set, the active icon name will default to its “filled” version.

options = param.Dict(allow_refs=False, class_=<class ‘dict’>, default={‘favorite’: ‘heart’}, label=’Options’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1423844d0>)

A key-value pair of reaction values and their corresponding tabler icon names found on https://tabler-icons.io.

value = param.List(allow_refs=False, bounds=(0, None), default=[], label=’Value’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14230f210>)

The active reactions.

clone(**params) Viewable[source]#

Makes a copy of the object sharing the same parameters.

Parameters:

params (Keyword arguments override the parameters on the clone.) –

Return type:

Cloned Viewable object

controls(parameters: List[str] = [], jslink: bool = True, **kwargs) Panel[source]#

Creates a set of widgets which allow manipulating the parameters on this instance. By default all parameters which support linking are exposed, but an explicit list of parameters can be provided.

Parameters:
  • parameters (list(str)) – An explicit list of parameters to return controls for.

  • jslink (bool) – Whether to use jslinks instead of Python based links. This does not allow using all types of parameters.

  • kwargs (dict) – Additional kwargs to pass to the Param pane(s) used to generate the controls widgets.

Return type:

A layout of the controls

embed(max_states: int = 1000, max_opts: int = 3, json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = False, states={}) None[source]#

Renders a static version of a panel in a notebook by evaluating the set of states defined by the widgets in the model. Note this will only work well for simple apps with a relatively small state space.

Parameters:
  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for JSON filename

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=False)) – Whether to report progress

  • states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

classmethod from_param(parameter: param.Parameter, **params) T[source]#

Construct a widget from a Parameter and link the two bi-directionally.

Parameters:

parameter (param.Parameter) – A parameter to create the widget from.

Return type:

Widget instance linked to the supplied parameter

get_root(doc: Optional[Document] = None, comm: Optional[Comm] = None, preprocess: bool = True) Model[source]#

Returns the root model and applies pre-processing hooks

Parameters:
  • doc (bokeh.Document) – Bokeh document the bokeh model will be attached to.

  • comm (pyviz_comms.Comm) – Optional pyviz_comms when working in notebook

  • preprocess (boolean (default=True)) – Whether to run preprocessing hooks

Return type:

Returns the bokeh model corresponding to this panel object

jscallback(args: Dict[str, Any] = {}, **callbacks: str) Callback[source]#

Allows defining a JS callback to be triggered when a property changes on the source object. The keyword arguments define the properties that trigger a callback and the JS code that gets executed.

Parameters:
  • args (dict) – A mapping of objects to make available to the JS callback

  • **callbacks (dict) – A mapping between properties on the source model and the code to execute when that property changes

Returns:

callback – The Callback which can be used to disable the callback.

Return type:

Callback

Links properties on the this Reactive object to those on the target Reactive object in JS code.

Supports two modes, either specify a mapping between the source and target model properties as keywords or provide a dictionary of JS code snippets which maps from the source parameter to a JS code snippet which is executed when the property changes.

Parameters:
  • target (panel.viewable.Viewable | bokeh.model.Model | holoviews.core.dimension.Dimensioned) – The target to link the value to.

  • code (dict) – Custom code which will be executed when the widget value changes.

  • args (dict) – A mapping of objects to make available to the JS callback

  • bidirectional (boolean) – Whether to link source and target bi-directionally

  • **links (dict) – A mapping between properties on the source model and the target model property to link it to.

Returns:

link – The GenericLink which can be used unlink the widget and the target model.

Return type:

GenericLink

Links the parameters on this Reactive object to attributes on the target Parameterized object.

Supports two modes, either specify a mapping between the source and target object parameters as keywords or provide a dictionary of callbacks which maps from the source parameter to a callback which is triggered when the parameter changes.

Parameters:
  • target (param.Parameterized) – The target object of the link.

  • callbacks (dict | None) – Maps from a parameter in the source object to a callback.

  • bidirectional (bool) – Whether to link source and target bi-directionally

  • **links (dict) – Maps between parameters on this object to the parameters on the supplied object.

save(filename: str | os.PathLike | IO, title: Optional[str] = None, resources: bokeh.resources.Resources | None = None, template: str | jinja2.environment.Template | None = None, template_variables: Dict[str, Any] = {}, embed: bool = False, max_states: int = 1000, max_opts: int = 3, embed_json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = True, embed_states: Dict[Any, Any] = {}, as_png: bool | None = None, **kwargs) None[source]#

Saves Panel objects to file.

Parameters:
  • filename (str or file-like object) – Filename to save the plot to

  • title (string) – Optional title for the plot

  • resources (bokeh resources) – One of the valid bokeh.resources (e.g. CDN or INLINE)

  • template – passed to underlying io.save

  • template_variables – passed to underlying io.save

  • embed (bool) – Whether the state space should be embedded in the saved file.

  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • embed_json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for the auto-generated json directory

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=True)) – Whether to report progress

  • embed_states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

  • as_png (boolean (default=None)) – To save as a .png. If None save_png will be true if filename is string and ends with png.

select(selector: Optional[Union[type, Callable[[Viewable], bool]]] = None) List[Viewable][source]#

Iterates over the Viewable and any potential children in the applying the Selector.

Parameters:

selector (type or callable or None) – The selector allows selecting a subset of Viewables by declaring a type or callable function to filter by.

Returns:

viewables

Return type:

list(Viewable)

servable(title: Optional[str] = None, location: bool | 'Location' = True, area: str = 'main', target: Optional[str] = None) ServableMixin[source]#

Serves the object or adds it to the configured pn.state.template if in a panel serve context, writes to the DOM if in a pyodide context and returns the Panel object to allow it to display itself in a notebook context.

Parameters:
  • title (str) – A string title to give the Document (if served as an app)

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

  • area (str (deprecated)) – The area of a template to add the component too. Only has an effect if pn.config.template has been set.

  • target (str) – Target area to write to. If a template has been configured on pn.config.template this refers to the target area in the template while in pyodide this refers to the ID of the DOM node to write to.

Return type:

The Panel object itself

server_doc(doc: Optional[Document] = None, title: Optional[str] = None, location: bool | 'Location' = True) Document[source]#

Returns a serveable bokeh Document with the panel attached

Parameters:
  • doc (bokeh.Document (optional)) – The bokeh Document to attach the panel to as a root, defaults to bokeh.io.curdoc()

  • title (str) – A string title to give the Document

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

doc – The bokeh document the panel was attached to

Return type:

bokeh.Document

show(title: Optional[str] = None, port: int = 0, address: Optional[str] = None, websocket_origin: Optional[str] = None, threaded: bool = False, verbose: bool = True, open: bool = True, location: bool | 'Location' = True, **kwargs) StoppableThread' | 'Server[source]#

Starts a Bokeh server and displays the Viewable in a new tab.

Parameters:
  • title (str | None) – A string title to give the Document (if served as an app)

  • port (int (optional, default=0)) – Allows specifying a specific port

  • address (str) – The address the server should listen on for HTTP requests.

  • websocket_origin (str or list(str) (optional)) – A list of hosts that can connect to the websocket. This is typically required when embedding a server app in an external web site. If None, “localhost” is used.

  • threaded (boolean (optional, default=False)) – Whether to launch the Server on a separate thread, allowing interactive use.

  • verbose (boolean (optional, default=True)) – Whether to print the address and port

  • open (boolean (optional, default=True)) – Whether to open the server in a new browser tab

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

server – Returns the Bokeh server instance or the thread the server was launched on (if threaded=True)

Return type:

bokeh.server.Server or panel.io.server.StoppableThread


feed Module#

Inheritance diagram of panel.chat.feed

The feed module provides a high-level API for interacting with a list of ChatMessage objects through the backend methods.

class panel.chat.feed.CallbackState(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]#

Bases: Enum

class panel.chat.feed.ChatFeed(*objects, **params)[source]#

Bases: ListPanel

A widget to display a list of ChatMessage objects and interact with them.

This widget provides methods to: - Send (append) messages to the chat log. - Stream tokens to the latest ChatMessage in the chat log. - Execute callbacks when a user sends a message. - Undo a number of sent ChatMessage objects. - Clear the chat log of all ChatMessage objects.

Reference: https://panel.holoviz.org/reference/chat/ChatFeed.html

Example:

>>> async def say_welcome(contents, user, instance):
>>>    yield "Welcome!"
>>>    yield "Glad you're here!"
>>> chat_feed = ChatFeed(callback=say_welcome, header="Welcome Feed")
>>> chat_feed.send("Hello World!", user="New User", avatar="😊")

Parameters inherited from:

panel.viewable.Layoutable: align, aspect_ratio, css_classes, design, height, min_width, min_height, max_width, max_height, styles, stylesheets, tags, width, width_policy, height_policy, sizing_mode, visible

panel.viewable.Viewable: loading

panel.layout.base.ListPanel: scroll

margin = param.Margin(allow_None=True, allow_refs=True, default=5, label=’Margin’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1434851d0>)

Allows to create additional space around the component. May be specified as a two-tuple of the form (vertical, horizontal) or a four-tuple (top, right, bottom, left).

objects = param.List(allow_refs=False, bounds=(0, None), default=[], label=’Objects’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x141ef7e10>)

The list of child objects that make up the layout.

auto_scroll_limit = param.Integer(allow_refs=False, bounds=(0, None), default=200, inclusive_bounds=(True, True), label=’Auto scroll limit’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142eae6d0>)

Max pixel distance from the latest object in the Column to activate automatic scrolling upon update. Setting to 0 disables auto-scrolling.

callback = param.Callable(allow_None=True, allow_refs=False, label=’Callback’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143484ed0>)

Callback to execute when a user sends a message or when respond is called. The signature must include the previous message value contents, the previous user name, and the component instance.

callback_exception = param.ObjectSelector(allow_refs=False, default=’summary’, label=’Callback exception’, names={}, nested_refs=False, objects=[‘raise’, ‘summary’, ‘verbose’, ‘ignore’], rx=<param.reactive.reactive_ops object at 0x142bcf750>)

How to handle exceptions raised by the callback. If “raise”, the exception will be raised. If “summary”, a summary will be sent to the chat feed. If “verbose”, the full traceback will be sent to the chat feed. If “ignore”, the exception will be ignored.

callback_user = param.String(allow_refs=False, default=’Assistant’, label=’Callback user’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142306710>)

The default user name to use for the message provided by the callback.

card_params = param.Dict(allow_refs=False, class_=<class ‘dict’>, default={}, label=’Card params’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142eae6d0>)

Params to pass to Card, like header, header_background, header_color, etc.

collapsible = param.Boolean(allow_refs=False, constant=True, default=False, label=’Collapsible’, nested_refs=False, readonly=True, rx=<param.reactive.reactive_ops object at 0x143485010>)

Whether the Card should be expandable and collapsible.

disabled = param.Boolean(allow_refs=False, default=False, label=’Disabled’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142d0aa10>)

Whether the feed is disabled.

message_params = param.Dict(allow_refs=False, class_=<class ‘dict’>, default={}, label=’Message params’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143484b10>)

Params to pass to each ChatMessage, like reaction_icons, timestamp_format, show_avatar, show_user, and show_timestamp. Params passed that are not ChatFeed params will be forwarded into message_params.

header = param.Parameter(allow_None=True, allow_refs=False, label=’Header’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14277f350>)

The header of the chat feed; commonly used for the title. Can be a string, pane, or widget.

help_text = param.String(allow_refs=False, default=’’, label=’Help text’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143484610>)

If provided, initializes a chat message in the chat log using the provided help text as the message object and help as the user. This is useful for providing instructions, and will not be included in the serialize method by default.

placeholder_text = param.String(allow_refs=False, default=’’, label=’Placeholder text’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142bd1310>)

The text to display next to the placeholder icon.

placeholder_params = param.Dict(allow_refs=False, class_=<class ‘dict’>, default={‘user’: ‘ ‘, ‘reaction_icons’: {}, ‘show_copy_icon’: False, ‘show_timestamp’: False}, label=’Placeholder params’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143485010>)

Params to pass to the placeholder ChatMessage, like reaction_icons, timestamp_format, show_avatar, show_user, show_timestamp.

placeholder_threshold = param.Number(allow_refs=False, bounds=(0, None), default=1, inclusive_bounds=(True, True), label=’Placeholder threshold’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143484a10>)

Min duration in seconds of buffering before displaying the placeholder. If 0, the placeholder will be disabled.

renderers = param.HookList(allow_refs=False, bounds=(0, None), default=[], label=’Renderers’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14301fb90>)

A callable or list of callables that accept the value and return a Panel object to render the value. If a list is provided, will attempt to use the first renderer that does not raise an exception. If None, will attempt to infer the renderer from the value.

load_buffer = param.Integer(allow_refs=False, bounds=(0, None), default=50, inclusive_bounds=(True, True), label=’Load buffer’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1428eee90>)

The number of objects loaded on each side of the visible objects. When scrolled halfway into the buffer, the feed will automatically load additional objects while unloading objects on the opposite side.

scroll_button_threshold = param.Integer(allow_refs=False, bounds=(0, None), default=100, inclusive_bounds=(True, True), label=’Scroll button threshold’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143484ad0>)

Min pixel distance from the latest object in the Column to display the scroll button. Setting to 0 disables the scroll button.

show_activity_dot = param.Boolean(allow_refs=False, default=True, label=’Show activity dot’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142fdcfd0>)

Whether to show an activity dot on the ChatMessage while streaming the callback response.

view_latest = param.Boolean(allow_refs=False, default=True, label=’View latest’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1424091d0>)

Whether to scroll to the latest object on init. If not enabled the view will be on the first object.

_placeholder = param.ClassSelector(allow_None=True, allow_refs=False, class_=<class ‘panel.chat.message.ChatMessage’>, label=’ placeholder’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142eae6d0>)

The placeholder wrapped in a ChatMessage object; primarily to prevent recursion error in _update_placeholder.

_callback_state = param.ObjectSelector(allow_refs=False, label=’ callback state’, names={}, nested_refs=False, objects=[<CallbackState.IDLE: ‘idle’>, <CallbackState.RUNNING: ‘running’>, <CallbackState.GENERATING: ‘generating’>, <CallbackState.STOPPING: ‘stopping’>, <CallbackState.STOPPED: ‘stopped’>], rx=<param.reactive.reactive_ops object at 0x14301fb90>)

The current state of the callback.

_callback_trigger = param.Event(allow_refs=False, default=False, label=’ callback trigger’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x142163fd0>)

Triggers the callback to respond.

_disabled_stack = param.List(allow_refs=False, bounds=(0, None), default=[], label=’ disabled stack’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1428b8e50>)

The previous disabled state of the feed.

append(obj: Any) None[source]#

Appends an object to the layout.

Parameters:

(object) (obj) –

clear() List[Any][source]#

Clears the chat log and returns the messages that were cleared.

Return type:

The messages that were cleared.

clone(*objects: Any, **params: Any) ListLike[source]#

Makes a copy of the layout sharing the same parameters.

Parameters:
  • objects (Objects to add to the cloned layout.) –

  • params (Keyword arguments override the parameters on the clone.) –

Return type:

Cloned layout object

controls(parameters: List[str] = [], jslink: bool = True, **kwargs) Panel[source]#

Creates a set of widgets which allow manipulating the parameters on this instance. By default all parameters which support linking are exposed, but an explicit list of parameters can be provided.

Parameters:
  • parameters (list(str)) – An explicit list of parameters to return controls for.

  • jslink (bool) – Whether to use jslinks instead of Python based links. This does not allow using all types of parameters.

  • kwargs (dict) – Additional kwargs to pass to the Param pane(s) used to generate the controls widgets.

Return type:

A layout of the controls

embed(max_states: int = 1000, max_opts: int = 3, json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = False, states={}) None[source]#

Renders a static version of a panel in a notebook by evaluating the set of states defined by the widgets in the model. Note this will only work well for simple apps with a relatively small state space.

Parameters:
  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for JSON filename

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=False)) – Whether to report progress

  • states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

extend(objects: Iterable[Any]) None[source]#

Extends the objects on this layout with a list.

Parameters:

(list) (objects) –

get_root(doc: Optional[Document] = None, comm: Optional[Comm] = None, preprocess: bool = True) Model[source]#

Returns the root model and applies pre-processing hooks

Parameters:
  • doc (bokeh.Document) – Bokeh document the bokeh model will be attached to.

  • comm (pyviz_comms.Comm) – Optional pyviz_comms when working in notebook

  • preprocess (boolean (default=True)) – Whether to run preprocessing hooks

Return type:

Returns the bokeh model corresponding to this panel object

index(object) int[source]#

Returns the integer index of the supplied object in the list of objects.

Parameters:

(object) (obj) –

Returns:

index (int)

Return type:

Integer index of the object in the layout.

insert(index: int, obj: Any) None[source]#

Inserts an object in the layout at the specified index.

Parameters:
  • (int) (index) –

  • (object) (object) –

jscallback(args: Dict[str, Any] = {}, **callbacks: str) Callback[source]#

Allows defining a JS callback to be triggered when a property changes on the source object. The keyword arguments define the properties that trigger a callback and the JS code that gets executed.

Parameters:
  • args (dict) – A mapping of objects to make available to the JS callback

  • **callbacks (dict) – A mapping between properties on the source model and the code to execute when that property changes

Returns:

callback – The Callback which can be used to disable the callback.

Return type:

Callback

Links properties on the this Reactive object to those on the target Reactive object in JS code.

Supports two modes, either specify a mapping between the source and target model properties as keywords or provide a dictionary of JS code snippets which maps from the source parameter to a JS code snippet which is executed when the property changes.

Parameters:
  • target (panel.viewable.Viewable | bokeh.model.Model | holoviews.core.dimension.Dimensioned) – The target to link the value to.

  • code (dict) – Custom code which will be executed when the widget value changes.

  • args (dict) – A mapping of objects to make available to the JS callback

  • bidirectional (boolean) – Whether to link source and target bi-directionally

  • **links (dict) – A mapping between properties on the source model and the target model property to link it to.

Returns:

link – The GenericLink which can be used unlink the widget and the target model.

Return type:

GenericLink

Links the parameters on this Reactive object to attributes on the target Parameterized object.

Supports two modes, either specify a mapping between the source and target object parameters as keywords or provide a dictionary of callbacks which maps from the source parameter to a callback which is triggered when the parameter changes.

Parameters:
  • target (param.Parameterized) – The target object of the link.

  • callbacks (dict | None) – Maps from a parameter in the source object to a callback.

  • bidirectional (bool) – Whether to link source and target bi-directionally

  • **links (dict) – Maps between parameters on this object to the parameters on the supplied object.

pop(index: int) Viewable[source]#

Pops an item from the layout by index.

Parameters:

(int) (index) –

remove(obj: Viewable) None[source]#

Removes an object from the layout.

Parameters:

(object) (obj) –

respond()[source]#

Executes the callback with the latest message in the chat log.

reverse() None[source]#

Reverses the objects in the layout.

save(filename: str | os.PathLike | IO, title: Optional[str] = None, resources: bokeh.resources.Resources | None = None, template: str | jinja2.environment.Template | None = None, template_variables: Dict[str, Any] = {}, embed: bool = False, max_states: int = 1000, max_opts: int = 3, embed_json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = True, embed_states: Dict[Any, Any] = {}, as_png: bool | None = None, **kwargs) None[source]#

Saves Panel objects to file.

Parameters:
  • filename (str or file-like object) – Filename to save the plot to

  • title (string) – Optional title for the plot

  • resources (bokeh resources) – One of the valid bokeh.resources (e.g. CDN or INLINE)

  • template – passed to underlying io.save

  • template_variables – passed to underlying io.save

  • embed (bool) – Whether the state space should be embedded in the saved file.

  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • embed_json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for the auto-generated json directory

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=True)) – Whether to report progress

  • embed_states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

  • as_png (boolean (default=None)) – To save as a .png. If None save_png will be true if filename is string and ends with png.

select(selector=None)[source]#

Iterates over the ChatInterface and any potential children in the applying the selector.

Parameters:

selector (type or callable or None) – The selector allows selecting a subset of Viewables by declaring a type or callable function to filter by.

Returns:

viewables

Return type:

list(Viewable)

send(value: panel.chat.message.ChatMessage | dict | Any, user: str | None = None, avatar: str | bytes | _io.BytesIO | None = None, respond: bool = True) panel.chat.message.ChatMessage | None[source]#

Sends a value and creates a new message in the chat log.

If respond is True, additionally executes the callback, if provided.

Parameters:
  • value (ChatMessage | dict | Any) – The message contents to send.

  • user (str | None) – The user to send as; overrides the message message’s user if provided.

  • avatar (str | bytes | BytesIO | None) – The avatar to use; overrides the message message’s avatar if provided.

  • respond (bool) – Whether to execute the callback.

Return type:

The message that was created.

serialize(exclude_users: Optional[List[str]] = None, filter_by: Optional[Callable] = None, format: Literal['transformers'] = 'transformers', custom_serializer: Optional[Callable] = None, **serialize_kwargs)[source]#

Exports the chat log.

Parameters:
  • format (str) – The format to export the chat log as; currently only supports “transformers”.

  • exclude_users (list(str) | None) – A list of user (case insensitive names) to exclude from serialization. If not provided, defaults to [“help”]. This will be executed before filter_by.

  • filter_by (callable) – A function to filter the chat log by. The function must accept and return a list of ChatMessage objects.

  • custom_serializer (callable) – A custom function to format the ChatMessage’s object. The function must accept one positional argument, the ChatMessage object, and return a string. If not provided, uses the serialize method on ChatMessage.

  • **serialize_kwargs

    Additional keyword arguments to use for the specified format.

    • format=”transformers” role_names : dict(str, str | list(str)) | None

      A dictionary mapping the role to the ChatMessage’s user name. Defaults to {“user”: [“user”], “assistant”: [self.callback_user]} if not set. The keys and values are case insensitive as the strings will all be lowercased. The values can be a string or a list of strings, e.g. {“user”: “user”, “assistant”: [“executor”, “langchain”]}.

      default_rolestr

      The default role to use if the user name is not found in role_names. If this is set to None, raises a ValueError if the user name is not found.

Return type:

The chat log serialized in the specified format.

servable(title: Optional[str] = None, location: bool | 'Location' = True, area: str = 'main', target: Optional[str] = None) ServableMixin[source]#

Serves the object or adds it to the configured pn.state.template if in a panel serve context, writes to the DOM if in a pyodide context and returns the Panel object to allow it to display itself in a notebook context.

Parameters:
  • title (str) – A string title to give the Document (if served as an app)

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

  • area (str (deprecated)) – The area of a template to add the component too. Only has an effect if pn.config.template has been set.

  • target (str) – Target area to write to. If a template has been configured on pn.config.template this refers to the target area in the template while in pyodide this refers to the ID of the DOM node to write to.

Return type:

The Panel object itself

server_doc(doc: Optional[Document] = None, title: Optional[str] = None, location: bool | 'Location' = True) Document[source]#

Returns a serveable bokeh Document with the panel attached

Parameters:
  • doc (bokeh.Document (optional)) – The bokeh Document to attach the panel to as a root, defaults to bokeh.io.curdoc()

  • title (str) – A string title to give the Document

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

doc – The bokeh document the panel was attached to

Return type:

bokeh.Document

show(title: Optional[str] = None, port: int = 0, address: Optional[str] = None, websocket_origin: Optional[str] = None, threaded: bool = False, verbose: bool = True, open: bool = True, location: bool | 'Location' = True, **kwargs) StoppableThread' | 'Server[source]#

Starts a Bokeh server and displays the Viewable in a new tab.

Parameters:
  • title (str | None) – A string title to give the Document (if served as an app)

  • port (int (optional, default=0)) – Allows specifying a specific port

  • address (str) – The address the server should listen on for HTTP requests.

  • websocket_origin (str or list(str) (optional)) – A list of hosts that can connect to the websocket. This is typically required when embedding a server app in an external web site. If None, “localhost” is used.

  • threaded (boolean (optional, default=False)) – Whether to launch the Server on a separate thread, allowing interactive use.

  • verbose (boolean (optional, default=True)) – Whether to print the address and port

  • open (boolean (optional, default=True)) – Whether to open the server in a new browser tab

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

server – Returns the Bokeh server instance or the thread the server was launched on (if threaded=True)

Return type:

bokeh.server.Server or panel.io.server.StoppableThread

stop() bool[source]#

Cancels the current callback task if possible.

Return type:

Whether the task was successfully stopped or done.

stream(value: str | dict | panel.chat.message.ChatMessage, user: str | None = None, avatar: str | bytes | _io.BytesIO | None = None, message: panel.chat.message.ChatMessage | None = None, replace: bool = False) panel.chat.message.ChatMessage | None[source]#

Streams a token and updates the provided message, if provided. Otherwise creates a new message in the chat log, so be sure the returned message is passed back into the method, e.g. message = chat.stream(token, message=message).

This method is primarily for outputs that are not generators– notably LangChain. For most cases, use the send method instead.

Parameters:
  • value (str | dict | ChatMessage) – The new token value to stream.

  • user (str | None) – The user to stream as; overrides the message’s user if provided.

  • avatar (str | bytes | BytesIO | None) – The avatar to use; overrides the message’s avatar if provided.

  • message (ChatMessage | None) – The message to update.

  • replace (bool) – Whether to replace the existing text when streaming a string or dict.

Return type:

The message that was updated.

undo(count: int = 1) List[Any][source]#

Removes the last count of messages from the chat log and returns them.

Parameters:

count (int) – The number of messages to remove, starting from the last message.

Return type:

The messages that were removed.

exception panel.chat.feed.StopCallback[source]#

Bases: Exception

add_note()#

Exception.add_note(note) – add a note to the exception

with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.


icon Module#

Inheritance diagram of panel.chat.icon

The icon module provides a low-level API for rendering chat related icons.

class panel.chat.icon.ChatCopyIcon(*, fill, value, loading, align, aspect_ratio, css_classes, design, height, height_policy, margin, max_height, max_width, min_height, min_width, sizing_mode, styles, stylesheets, tags, visible, width, width_policy, name)[source]#

Bases: ReactiveHTML

Parameters inherited from:

panel.viewable.Layoutable: align, aspect_ratio, design, height, min_width, min_height, max_width, max_height, margin, styles, stylesheets, tags, width, width_policy, height_policy, sizing_mode, visible

panel.viewable.Viewable: loading

css_classes = param.List(allow_refs=True, bounds=(0, None), default=[‘copy-icon’], label=’Css classes’, nested_refs=True, rx=<param.reactive.reactive_ops object at 0x14352ce90>)

The CSS classes of the widget.

fill = param.String(allow_refs=False, default=’none’, label=’Fill’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14344e710>)

The fill color of the icon.

value = param.String(allow_None=True, allow_refs=False, label=’Value’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14352ce50>)

The text to copy to the clipboard.

clone(**params) Viewable[source]#

Makes a copy of the object sharing the same parameters.

Parameters:

params (Keyword arguments override the parameters on the clone.) –

Return type:

Cloned Viewable object

controls(parameters: List[str] = [], jslink: bool = True, **kwargs) Panel[source]#

Creates a set of widgets which allow manipulating the parameters on this instance. By default all parameters which support linking are exposed, but an explicit list of parameters can be provided.

Parameters:
  • parameters (list(str)) – An explicit list of parameters to return controls for.

  • jslink (bool) – Whether to use jslinks instead of Python based links. This does not allow using all types of parameters.

  • kwargs (dict) – Additional kwargs to pass to the Param pane(s) used to generate the controls widgets.

Return type:

A layout of the controls

embed(max_states: int = 1000, max_opts: int = 3, json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = False, states={}) None[source]#

Renders a static version of a panel in a notebook by evaluating the set of states defined by the widgets in the model. Note this will only work well for simple apps with a relatively small state space.

Parameters:
  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for JSON filename

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=False)) – Whether to report progress

  • states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

get_root(doc: Optional[Document] = None, comm: Optional[Comm] = None, preprocess: bool = True) Model[source]#

Returns the root model and applies pre-processing hooks

Parameters:
  • doc (bokeh.Document) – Bokeh document the bokeh model will be attached to.

  • comm (pyviz_comms.Comm) – Optional pyviz_comms when working in notebook

  • preprocess (boolean (default=True)) – Whether to run preprocessing hooks

Return type:

Returns the bokeh model corresponding to this panel object

jscallback(args: Dict[str, Any] = {}, **callbacks: str) Callback[source]#

Allows defining a JS callback to be triggered when a property changes on the source object. The keyword arguments define the properties that trigger a callback and the JS code that gets executed.

Parameters:
  • args (dict) – A mapping of objects to make available to the JS callback

  • **callbacks (dict) – A mapping between properties on the source model and the code to execute when that property changes

Returns:

callback – The Callback which can be used to disable the callback.

Return type:

Callback

Links properties on the this Reactive object to those on the target Reactive object in JS code.

Supports two modes, either specify a mapping between the source and target model properties as keywords or provide a dictionary of JS code snippets which maps from the source parameter to a JS code snippet which is executed when the property changes.

Parameters:
  • target (panel.viewable.Viewable | bokeh.model.Model | holoviews.core.dimension.Dimensioned) – The target to link the value to.

  • code (dict) – Custom code which will be executed when the widget value changes.

  • args (dict) – A mapping of objects to make available to the JS callback

  • bidirectional (boolean) – Whether to link source and target bi-directionally

  • **links (dict) – A mapping between properties on the source model and the target model property to link it to.

Returns:

link – The GenericLink which can be used unlink the widget and the target model.

Return type:

GenericLink

Links the parameters on this Reactive object to attributes on the target Parameterized object.

Supports two modes, either specify a mapping between the source and target object parameters as keywords or provide a dictionary of callbacks which maps from the source parameter to a callback which is triggered when the parameter changes.

Parameters:
  • target (param.Parameterized) – The target object of the link.

  • callbacks (dict | None) – Maps from a parameter in the source object to a callback.

  • bidirectional (bool) – Whether to link source and target bi-directionally

  • **links (dict) – Maps between parameters on this object to the parameters on the supplied object.

on_event(node: str, event: str, callback: Callable) None[source]#

Registers a callback to be executed when the specified DOM event is triggered on the named node. Note that the named node must be declared in the HTML. To create a named node you must give it an id of the form id=”name”, where name will be the node identifier.

Parameters:
  • node (str) – Named node in the HTML identifiable via id of the form id=”name”.

  • event (str) – Name of the DOM event to add an event listener to.

  • callback (callable) – A callable which will be given the DOMEvent object.

save(filename: str | os.PathLike | IO, title: Optional[str] = None, resources: bokeh.resources.Resources | None = None, template: str | jinja2.environment.Template | None = None, template_variables: Dict[str, Any] = {}, embed: bool = False, max_states: int = 1000, max_opts: int = 3, embed_json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = True, embed_states: Dict[Any, Any] = {}, as_png: bool | None = None, **kwargs) None[source]#

Saves Panel objects to file.

Parameters:
  • filename (str or file-like object) – Filename to save the plot to

  • title (string) – Optional title for the plot

  • resources (bokeh resources) – One of the valid bokeh.resources (e.g. CDN or INLINE)

  • template – passed to underlying io.save

  • template_variables – passed to underlying io.save

  • embed (bool) – Whether the state space should be embedded in the saved file.

  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • embed_json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for the auto-generated json directory

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=True)) – Whether to report progress

  • embed_states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

  • as_png (boolean (default=None)) – To save as a .png. If None save_png will be true if filename is string and ends with png.

select(selector: Optional[Union[type, Callable[[Viewable], bool]]] = None) List[Viewable][source]#

Iterates over the Viewable and any potential children in the applying the Selector.

Parameters:

selector (type or callable or None) – The selector allows selecting a subset of Viewables by declaring a type or callable function to filter by.

Returns:

viewables

Return type:

list(Viewable)

servable(title: Optional[str] = None, location: bool | 'Location' = True, area: str = 'main', target: Optional[str] = None) ServableMixin[source]#

Serves the object or adds it to the configured pn.state.template if in a panel serve context, writes to the DOM if in a pyodide context and returns the Panel object to allow it to display itself in a notebook context.

Parameters:
  • title (str) – A string title to give the Document (if served as an app)

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

  • area (str (deprecated)) – The area of a template to add the component too. Only has an effect if pn.config.template has been set.

  • target (str) – Target area to write to. If a template has been configured on pn.config.template this refers to the target area in the template while in pyodide this refers to the ID of the DOM node to write to.

Return type:

The Panel object itself

server_doc(doc: Optional[Document] = None, title: Optional[str] = None, location: bool | 'Location' = True) Document[source]#

Returns a serveable bokeh Document with the panel attached

Parameters:
  • doc (bokeh.Document (optional)) – The bokeh Document to attach the panel to as a root, defaults to bokeh.io.curdoc()

  • title (str) – A string title to give the Document

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

doc – The bokeh document the panel was attached to

Return type:

bokeh.Document

show(title: Optional[str] = None, port: int = 0, address: Optional[str] = None, websocket_origin: Optional[str] = None, threaded: bool = False, verbose: bool = True, open: bool = True, location: bool | 'Location' = True, **kwargs) StoppableThread' | 'Server[source]#

Starts a Bokeh server and displays the Viewable in a new tab.

Parameters:
  • title (str | None) – A string title to give the Document (if served as an app)

  • port (int (optional, default=0)) – Allows specifying a specific port

  • address (str) – The address the server should listen on for HTTP requests.

  • websocket_origin (str or list(str) (optional)) – A list of hosts that can connect to the websocket. This is typically required when embedding a server app in an external web site. If None, “localhost” is used.

  • threaded (boolean (optional, default=False)) – Whether to launch the Server on a separate thread, allowing interactive use.

  • verbose (boolean (optional, default=True)) – Whether to print the address and port

  • open (boolean (optional, default=True)) – Whether to open the server in a new browser tab

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

server – Returns the Bokeh server instance or the thread the server was launched on (if threaded=True)

Return type:

bokeh.server.Server or panel.io.server.StoppableThread

class panel.chat.icon.ChatReactionIcons(*, active_icons, options, value, disabled, loading, align, aspect_ratio, css_classes, design, height, height_policy, margin, max_height, max_width, min_height, min_width, sizing_mode, styles, stylesheets, tags, visible, width, width_policy, name)[source]#

Bases: CompositeWidget

A widget to display reaction icons that can be clicked on.

Parameters:

:param : :type : Example: :param >>> ChatReactionIcons(value=[“like”]: :type >>> ChatReactionIcons(value=[“like”]: “thumb-up”, “dislike”: “thumb-down”}) :param options={“like”: :type options={“like”: “thumb-up”, “dislike”: “thumb-down”})

Parameters inherited from:

panel.viewable.Layoutable: align, aspect_ratio, design, min_width, min_height, max_width, max_height, styles, stylesheets, tags, width_policy, height_policy, sizing_mode, visible

panel.viewable.Viewable: loading

panel.widgets.base.Widget: height, margin, width, disabled

css_classes = param.List(allow_refs=True, bounds=(0, None), default=[‘reaction-icons’], label=’Css classes’, nested_refs=True, rx=<param.reactive.reactive_ops object at 0x14335af90>)

The CSS classes of the widget.

active_icons = param.Dict(allow_refs=False, class_=<class ‘dict’>, default={}, label=’Active icons’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14335a850>)

The mapping of reactions to their corresponding active icon names. If not set, the active icon name will default to its “filled” version.

options = param.Dict(allow_refs=False, class_=<class ‘dict’>, default={‘favorite’: ‘heart’}, label=’Options’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14335bc50>)

A key-value pair of reaction values and their corresponding tabler icon names found on https://tabler-icons.io.

value = param.List(allow_refs=False, bounds=(0, None), default=[], label=’Value’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14335ab10>)

The active reactions.

clone(**params) Viewable[source]#

Makes a copy of the object sharing the same parameters.

Parameters:

params (Keyword arguments override the parameters on the clone.) –

Return type:

Cloned Viewable object

controls(parameters: List[str] = [], jslink: bool = True, **kwargs) Panel[source]#

Creates a set of widgets which allow manipulating the parameters on this instance. By default all parameters which support linking are exposed, but an explicit list of parameters can be provided.

Parameters:
  • parameters (list(str)) – An explicit list of parameters to return controls for.

  • jslink (bool) – Whether to use jslinks instead of Python based links. This does not allow using all types of parameters.

  • kwargs (dict) – Additional kwargs to pass to the Param pane(s) used to generate the controls widgets.

Return type:

A layout of the controls

embed(max_states: int = 1000, max_opts: int = 3, json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = False, states={}) None[source]#

Renders a static version of a panel in a notebook by evaluating the set of states defined by the widgets in the model. Note this will only work well for simple apps with a relatively small state space.

Parameters:
  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for JSON filename

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=False)) – Whether to report progress

  • states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

classmethod from_param(parameter: param.Parameter, **params) T[source]#

Construct a widget from a Parameter and link the two bi-directionally.

Parameters:

parameter (param.Parameter) – A parameter to create the widget from.

Return type:

Widget instance linked to the supplied parameter

get_root(doc: Optional[Document] = None, comm: Optional[Comm] = None, preprocess: bool = True) Model[source]#

Returns the root model and applies pre-processing hooks

Parameters:
  • doc (bokeh.Document) – Bokeh document the bokeh model will be attached to.

  • comm (pyviz_comms.Comm) – Optional pyviz_comms when working in notebook

  • preprocess (boolean (default=True)) – Whether to run preprocessing hooks

Return type:

Returns the bokeh model corresponding to this panel object

jscallback(args: Dict[str, Any] = {}, **callbacks: str) Callback[source]#

Allows defining a JS callback to be triggered when a property changes on the source object. The keyword arguments define the properties that trigger a callback and the JS code that gets executed.

Parameters:
  • args (dict) – A mapping of objects to make available to the JS callback

  • **callbacks (dict) – A mapping between properties on the source model and the code to execute when that property changes

Returns:

callback – The Callback which can be used to disable the callback.

Return type:

Callback

Links properties on the this Reactive object to those on the target Reactive object in JS code.

Supports two modes, either specify a mapping between the source and target model properties as keywords or provide a dictionary of JS code snippets which maps from the source parameter to a JS code snippet which is executed when the property changes.

Parameters:
  • target (panel.viewable.Viewable | bokeh.model.Model | holoviews.core.dimension.Dimensioned) – The target to link the value to.

  • code (dict) – Custom code which will be executed when the widget value changes.

  • args (dict) – A mapping of objects to make available to the JS callback

  • bidirectional (boolean) – Whether to link source and target bi-directionally

  • **links (dict) – A mapping between properties on the source model and the target model property to link it to.

Returns:

link – The GenericLink which can be used unlink the widget and the target model.

Return type:

GenericLink

Links the parameters on this Reactive object to attributes on the target Parameterized object.

Supports two modes, either specify a mapping between the source and target object parameters as keywords or provide a dictionary of callbacks which maps from the source parameter to a callback which is triggered when the parameter changes.

Parameters:
  • target (param.Parameterized) – The target object of the link.

  • callbacks (dict | None) – Maps from a parameter in the source object to a callback.

  • bidirectional (bool) – Whether to link source and target bi-directionally

  • **links (dict) – Maps between parameters on this object to the parameters on the supplied object.

save(filename: str | os.PathLike | IO, title: Optional[str] = None, resources: bokeh.resources.Resources | None = None, template: str | jinja2.environment.Template | None = None, template_variables: Dict[str, Any] = {}, embed: bool = False, max_states: int = 1000, max_opts: int = 3, embed_json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = True, embed_states: Dict[Any, Any] = {}, as_png: bool | None = None, **kwargs) None[source]#

Saves Panel objects to file.

Parameters:
  • filename (str or file-like object) – Filename to save the plot to

  • title (string) – Optional title for the plot

  • resources (bokeh resources) – One of the valid bokeh.resources (e.g. CDN or INLINE)

  • template – passed to underlying io.save

  • template_variables – passed to underlying io.save

  • embed (bool) – Whether the state space should be embedded in the saved file.

  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • embed_json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for the auto-generated json directory

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=True)) – Whether to report progress

  • embed_states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

  • as_png (boolean (default=None)) – To save as a .png. If None save_png will be true if filename is string and ends with png.

select(selector: Optional[Union[type, Callable[[Viewable], bool]]] = None) List[Viewable][source]#

Iterates over the Viewable and any potential children in the applying the Selector.

Parameters:

selector (type or callable or None) – The selector allows selecting a subset of Viewables by declaring a type or callable function to filter by.

Returns:

viewables

Return type:

list(Viewable)

servable(title: Optional[str] = None, location: bool | 'Location' = True, area: str = 'main', target: Optional[str] = None) ServableMixin[source]#

Serves the object or adds it to the configured pn.state.template if in a panel serve context, writes to the DOM if in a pyodide context and returns the Panel object to allow it to display itself in a notebook context.

Parameters:
  • title (str) – A string title to give the Document (if served as an app)

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

  • area (str (deprecated)) – The area of a template to add the component too. Only has an effect if pn.config.template has been set.

  • target (str) – Target area to write to. If a template has been configured on pn.config.template this refers to the target area in the template while in pyodide this refers to the ID of the DOM node to write to.

Return type:

The Panel object itself

server_doc(doc: Optional[Document] = None, title: Optional[str] = None, location: bool | 'Location' = True) Document[source]#

Returns a serveable bokeh Document with the panel attached

Parameters:
  • doc (bokeh.Document (optional)) – The bokeh Document to attach the panel to as a root, defaults to bokeh.io.curdoc()

  • title (str) – A string title to give the Document

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

doc – The bokeh document the panel was attached to

Return type:

bokeh.Document

show(title: Optional[str] = None, port: int = 0, address: Optional[str] = None, websocket_origin: Optional[str] = None, threaded: bool = False, verbose: bool = True, open: bool = True, location: bool | 'Location' = True, **kwargs) StoppableThread' | 'Server[source]#

Starts a Bokeh server and displays the Viewable in a new tab.

Parameters:
  • title (str | None) – A string title to give the Document (if served as an app)

  • port (int (optional, default=0)) – Allows specifying a specific port

  • address (str) – The address the server should listen on for HTTP requests.

  • websocket_origin (str or list(str) (optional)) – A list of hosts that can connect to the websocket. This is typically required when embedding a server app in an external web site. If None, “localhost” is used.

  • threaded (boolean (optional, default=False)) – Whether to launch the Server on a separate thread, allowing interactive use.

  • verbose (boolean (optional, default=True)) – Whether to print the address and port

  • open (boolean (optional, default=True)) – Whether to open the server in a new browser tab

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

server – Returns the Bokeh server instance or the thread the server was launched on (if threaded=True)

Return type:

bokeh.server.Server or panel.io.server.StoppableThread


input Module#

Inheritance diagram of panel.chat.input
class panel.chat.input.ChatAreaInput(*, disabled_enter, enter_sends, auto_grow, cols, max_rows, resizable, rows, description, max_length, placeholder, value, value_input, disabled, loading, align, aspect_ratio, css_classes, design, height, height_policy, margin, max_height, max_width, min_height, min_width, sizing_mode, styles, stylesheets, tags, visible, width, width_policy, name)[source]#

Bases: TextAreaInput

The ChatAreaInput allows entering any multiline string using a text input box, with the ability to press enter to submit the message.

Unlike TextAreaInput, the ChatAreaInput defaults to auto_grow=True and max_rows=10, and the value is not synced to the server until the enter key is pressed so bind on value_input if you need to access the existing value.

Lines are joined with the newline character n.

Reference: https://panel.holoviz.org/reference/chat/ChatAreaInput.html

Example:

>>> ChatAreaInput(max_rows=10)

Parameters inherited from:

panel.viewable.Layoutable: align, aspect_ratio, css_classes, design, min_width, min_height, max_width, max_height, styles, stylesheets, tags, width_policy, height_policy, sizing_mode, visible

panel.viewable.Viewable: loading

panel.widgets.base.Widget: height, margin, disabled

panel.widgets.input.TextInput: width, description, max_length, placeholder, value, value_input

panel.widgets.input.TextAreaInput: cols

auto_grow = param.Boolean(allow_refs=False, default=True, label=’Auto grow’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143a47310>)

Whether the text area should automatically grow vertically to accommodate the current text.

max_rows = param.Integer(allow_refs=False, default=10, inclusive_bounds=(True, True), label=’Max rows’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143a50b90>)

When combined with auto_grow this determines the maximum number of rows the input area can grow.

rows = param.Integer(allow_refs=False, default=1, inclusive_bounds=(True, True), label=’Rows’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143a51150>)

Number of rows in the text input field.

resizable = param.ObjectSelector(allow_refs=False, default=’height’, label=’Resizable’, names={}, nested_refs=False, objects=[‘both’, ‘width’, ‘height’, False], rx=<param.reactive.reactive_ops object at 0x143927750>)

Whether the layout is interactively resizable, and if so in which dimensions: width, height, or both. Can only be set during initialization.

disabled_enter = param.Boolean(allow_refs=False, default=False, label=’Disabled enter’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143a47310>)

If True, disables sending the message by pressing the enter_sends key.

enter_sends = param.Boolean(allow_refs=False, default=True, label=’Enter sends’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1433faa10>)

If True, pressing the Enter key sends the message, if False it is sent by pressing the Ctrl+Enter.

clone(**params) Viewable[source]#

Makes a copy of the object sharing the same parameters.

Parameters:

params (Keyword arguments override the parameters on the clone.) –

Return type:

Cloned Viewable object

controls(parameters: List[str] = [], jslink: bool = True, **kwargs) Panel[source]#

Creates a set of widgets which allow manipulating the parameters on this instance. By default all parameters which support linking are exposed, but an explicit list of parameters can be provided.

Parameters:
  • parameters (list(str)) – An explicit list of parameters to return controls for.

  • jslink (bool) – Whether to use jslinks instead of Python based links. This does not allow using all types of parameters.

  • kwargs (dict) – Additional kwargs to pass to the Param pane(s) used to generate the controls widgets.

Return type:

A layout of the controls

embed(max_states: int = 1000, max_opts: int = 3, json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = False, states={}) None[source]#

Renders a static version of a panel in a notebook by evaluating the set of states defined by the widgets in the model. Note this will only work well for simple apps with a relatively small state space.

Parameters:
  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for JSON filename

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=False)) – Whether to report progress

  • states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

classmethod from_param(parameter: param.Parameter, onkeyup=False, **params) Viewable[source]#

Construct a widget from a Parameter and link the two bi-directionally.

Parameters:
  • parameter (param.Parameter) – A parameter to create the widget from.

  • onkeyup (boolean) – Whether to trigger events on every key press.

  • params (dict) – Keyword arguments to be passed to the widget constructor

Return type:

Widget instance linked to the supplied parameter

get_root(doc: Optional[Document] = None, comm: Optional[Comm] = None, preprocess: bool = True) Model[source]#

Returns the root model and applies pre-processing hooks

Parameters:
  • doc (bokeh.Document) – Bokeh document the bokeh model will be attached to.

  • comm (pyviz_comms.Comm) – Optional pyviz_comms when working in notebook

  • preprocess (boolean (default=True)) – Whether to run preprocessing hooks

Return type:

Returns the bokeh model corresponding to this panel object

jscallback(args: Dict[str, Any] = {}, **callbacks: str) Callback[source]#

Allows defining a JS callback to be triggered when a property changes on the source object. The keyword arguments define the properties that trigger a callback and the JS code that gets executed.

Parameters:
  • args (dict) – A mapping of objects to make available to the JS callback

  • **callbacks (dict) – A mapping between properties on the source model and the code to execute when that property changes

Returns:

callback – The Callback which can be used to disable the callback.

Return type:

Callback

Links properties on the this Reactive object to those on the target Reactive object in JS code.

Supports two modes, either specify a mapping between the source and target model properties as keywords or provide a dictionary of JS code snippets which maps from the source parameter to a JS code snippet which is executed when the property changes.

Parameters:
  • target (panel.viewable.Viewable | bokeh.model.Model | holoviews.core.dimension.Dimensioned) – The target to link the value to.

  • code (dict) – Custom code which will be executed when the widget value changes.

  • args (dict) – A mapping of objects to make available to the JS callback

  • bidirectional (boolean) – Whether to link source and target bi-directionally

  • **links (dict) – A mapping between properties on the source model and the target model property to link it to.

Returns:

link – The GenericLink which can be used unlink the widget and the target model.

Return type:

GenericLink

Links the parameters on this Reactive object to attributes on the target Parameterized object.

Supports two modes, either specify a mapping between the source and target object parameters as keywords or provide a dictionary of callbacks which maps from the source parameter to a callback which is triggered when the parameter changes.

Parameters:
  • target (param.Parameterized) – The target object of the link.

  • callbacks (dict | None) – Maps from a parameter in the source object to a callback.

  • bidirectional (bool) – Whether to link source and target bi-directionally

  • **links (dict) – Maps between parameters on this object to the parameters on the supplied object.

save(filename: str | os.PathLike | IO, title: Optional[str] = None, resources: bokeh.resources.Resources | None = None, template: str | jinja2.environment.Template | None = None, template_variables: Dict[str, Any] = {}, embed: bool = False, max_states: int = 1000, max_opts: int = 3, embed_json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = True, embed_states: Dict[Any, Any] = {}, as_png: bool | None = None, **kwargs) None[source]#

Saves Panel objects to file.

Parameters:
  • filename (str or file-like object) – Filename to save the plot to

  • title (string) – Optional title for the plot

  • resources (bokeh resources) – One of the valid bokeh.resources (e.g. CDN or INLINE)

  • template – passed to underlying io.save

  • template_variables – passed to underlying io.save

  • embed (bool) – Whether the state space should be embedded in the saved file.

  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • embed_json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for the auto-generated json directory

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=True)) – Whether to report progress

  • embed_states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

  • as_png (boolean (default=None)) – To save as a .png. If None save_png will be true if filename is string and ends with png.

select(selector: Optional[Union[type, Callable[[Viewable], bool]]] = None) List[Viewable][source]#

Iterates over the Viewable and any potential children in the applying the Selector.

Parameters:

selector (type or callable or None) – The selector allows selecting a subset of Viewables by declaring a type or callable function to filter by.

Returns:

viewables

Return type:

list(Viewable)

servable(title: Optional[str] = None, location: bool | 'Location' = True, area: str = 'main', target: Optional[str] = None) ServableMixin[source]#

Serves the object or adds it to the configured pn.state.template if in a panel serve context, writes to the DOM if in a pyodide context and returns the Panel object to allow it to display itself in a notebook context.

Parameters:
  • title (str) – A string title to give the Document (if served as an app)

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

  • area (str (deprecated)) – The area of a template to add the component too. Only has an effect if pn.config.template has been set.

  • target (str) – Target area to write to. If a template has been configured on pn.config.template this refers to the target area in the template while in pyodide this refers to the ID of the DOM node to write to.

Return type:

The Panel object itself

server_doc(doc: Optional[Document] = None, title: Optional[str] = None, location: bool | 'Location' = True) Document[source]#

Returns a serveable bokeh Document with the panel attached

Parameters:
  • doc (bokeh.Document (optional)) – The bokeh Document to attach the panel to as a root, defaults to bokeh.io.curdoc()

  • title (str) – A string title to give the Document

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

doc – The bokeh document the panel was attached to

Return type:

bokeh.Document

show(title: Optional[str] = None, port: int = 0, address: Optional[str] = None, websocket_origin: Optional[str] = None, threaded: bool = False, verbose: bool = True, open: bool = True, location: bool | 'Location' = True, **kwargs) StoppableThread' | 'Server[source]#

Starts a Bokeh server and displays the Viewable in a new tab.

Parameters:
  • title (str | None) – A string title to give the Document (if served as an app)

  • port (int (optional, default=0)) – Allows specifying a specific port

  • address (str) – The address the server should listen on for HTTP requests.

  • websocket_origin (str or list(str) (optional)) – A list of hosts that can connect to the websocket. This is typically required when embedding a server app in an external web site. If None, “localhost” is used.

  • threaded (boolean (optional, default=False)) – Whether to launch the Server on a separate thread, allowing interactive use.

  • verbose (boolean (optional, default=True)) – Whether to print the address and port

  • open (boolean (optional, default=True)) – Whether to open the server in a new browser tab

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

server – Returns the Bokeh server instance or the thread the server was launched on (if threaded=True)

Return type:

bokeh.server.Server or panel.io.server.StoppableThread


interface Module#

Inheritance diagram of panel.chat.interface

The interface module provides an even higher-level API for interacting with a list of ChatMessage objects compared to the ChatFeed through a frontend input UI.

class panel.chat.interface.ChatInterface(*objects, **params)[source]#

Bases: ChatFeed

High level widget that contains the chat log and the chat input.

Reference: https://panel.holoviz.org/reference/chat/ChatInterface.html

Example:

>>> async def repeat_contents(contents, user, instance):
>>>     yield contents
>>> chat_interface = ChatInterface(
    callback=repeat_contents, widgets=[TextInput(), FileInput()]
)

Parameters inherited from:

panel.viewable.Layoutable: align, aspect_ratio, css_classes, design, height, min_width, min_height, max_width, max_height, styles, stylesheets, tags, width, width_policy, height_policy, sizing_mode, visible

panel.viewable.Viewable: loading

panel.layout.base.ListPanel: scroll

panel.chat.feed.ChatFeed: margin, objects, auto_scroll_limit, callback, callback_exception, callback_user, card_params, collapsible, disabled, message_params, header, help_text, placeholder_text, placeholder_params, placeholder_threshold, renderers, load_buffer, scroll_button_threshold, show_activity_dot, view_latest, _placeholder, _callback_state, _callback_trigger, _disabled_stack

auto_send_types = param.List(allow_refs=False, bounds=(0, None), default=[], label=’Auto send types’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143ae1110>)

The widget types to automatically send when the user presses enter or clicks away from the widget. If not provided, defaults to [TextInput].

avatar = param.ClassSelector(allow_None=True, allow_refs=False, class_=(<class ‘str’>, <class ‘_io.BytesIO’>, <class ‘bytes’>, <class ‘panel.pane.image.ImageBase’>), label=’Avatar’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143cd8990>)

The avatar to use for the user. Can be a single character text, an emoji, or anything supported by pn.pane.Image. If not set, uses the first character of the name.

reset_on_send = param.Boolean(allow_refs=False, default=True, label=’Reset on send’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143c85a10>)

Whether to reset the widget’s value after sending a message; has no effect for TextInput.

show_send = param.Boolean(allow_refs=False, default=True, label=’Show send’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143c84110>)

Whether to show the send button.

show_stop = param.Boolean(allow_refs=False, default=True, label=’Show stop’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143c85a10>)

Whether to show the stop button temporarily replacing the send button during callback; has no effect if callback is not async.

show_rerun = param.Boolean(allow_refs=False, default=True, label=’Show rerun’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143c84110>)

Whether to show the rerun button.

show_undo = param.Boolean(allow_refs=False, default=True, label=’Show undo’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143c85a10>)

Whether to show the undo button.

show_clear = param.Boolean(allow_refs=False, default=True, label=’Show clear’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143c84110>)

Whether to show the clear button.

show_button_name = param.Boolean(allow_None=True, allow_refs=False, label=’Show button name’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143c85ed0>)

Whether to show the button name.

user = param.String(allow_refs=False, default=’User’, label=’User’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143826710>)

Name of the ChatInterface user.

widgets = param.ClassSelector(allow_None=True, allow_refs=False, class_=(<class ‘panel.widgets.base.Widget’>, <class ‘list’>), label=’Widgets’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143c85a10>)

Widgets to use for the input. If not provided, defaults to [TextInput].

button_properties = param.Dict(allow_refs=False, class_=<class ‘dict’>, default={}, label=’Button properties’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143c846d0>)

Allows addition of functionality or customization of buttons by supplying a mapping from the button name to a dictionary containing the icon, callback, post_callback, and/or js_on_click keys. If the button names correspond to default buttons (send, rerun, undo, clear), the default icon can be updated and if a callback key value pair is provided, the specified callback functionality runs before the existing one. For button names that don’t match existing ones, new buttons are created and must include a callback, post_callback, and/or js_on_click key. The provided callbacks should have a signature that accepts two positional arguments: instance (the ChatInterface instance) and event (the button click event). The js_on_click key should be a str or dict. If str, provide the JavaScript code; else if dict, it must have a code key, containing the JavaScript code to execute when the button is clicked, and optionally an args key, containing dictionary of arguments to pass to the JavaScript code.

_widgets = param.Dict(allow_refs=False, class_=<class ‘dict’>, default={}, label=’ widgets’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143c84110>)

The input widgets.

_input_container = param.ClassSelector(allow_None=True, allow_refs=False, class_=<class ‘panel.layout.base.Row’>, label=’ input container’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143c84690>)

The input message row that wraps the input layout (Tabs / Row) to easily swap between Tabs and Rows, depending on number of widgets.

_input_layout = param.ClassSelector(allow_None=True, allow_refs=False, class_=(<class ‘panel.layout.base.Row’>, <class ‘panel.layout.tabs.Tabs’>), label=’ input layout’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143c84110>)

The input layout that contains the input widgets.

_button_data = param.Dict(allow_refs=False, class_=<class ‘dict’>, default={}, label=’ button data’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143c84690>)

Metadata and data related to the buttons.

_buttons = param.Dict(allow_refs=False, class_=<class ‘dict’>, default={}, label=’ buttons’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143c84390>)

The rendered buttons.

property active: int#

The currently active input widget tab index; -1 if there is only one widget available which is not in a tab.

Return type:

The active input widget tab index.

property active_widget: Widget#

The currently active widget.

Return type:

The active widget.

append(obj: Any) None[source]#

Appends an object to the layout.

Parameters:

(object) (obj) –

clear() List[Any][source]#

Clears the chat log and returns the messages that were cleared.

Return type:

The messages that were cleared.

clone(*objects: Any, **params: Any) ListLike[source]#

Makes a copy of the layout sharing the same parameters.

Parameters:
  • objects (Objects to add to the cloned layout.) –

  • params (Keyword arguments override the parameters on the clone.) –

Return type:

Cloned layout object

controls(parameters: List[str] = [], jslink: bool = True, **kwargs) Panel[source]#

Creates a set of widgets which allow manipulating the parameters on this instance. By default all parameters which support linking are exposed, but an explicit list of parameters can be provided.

Parameters:
  • parameters (list(str)) – An explicit list of parameters to return controls for.

  • jslink (bool) – Whether to use jslinks instead of Python based links. This does not allow using all types of parameters.

  • kwargs (dict) – Additional kwargs to pass to the Param pane(s) used to generate the controls widgets.

Return type:

A layout of the controls

embed(max_states: int = 1000, max_opts: int = 3, json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = False, states={}) None[source]#

Renders a static version of a panel in a notebook by evaluating the set of states defined by the widgets in the model. Note this will only work well for simple apps with a relatively small state space.

Parameters:
  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for JSON filename

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=False)) – Whether to report progress

  • states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

extend(objects: Iterable[Any]) None[source]#

Extends the objects on this layout with a list.

Parameters:

(list) (objects) –

get_root(doc: Optional[Document] = None, comm: Optional[Comm] = None, preprocess: bool = True) Model[source]#

Returns the root model and applies pre-processing hooks

Parameters:
  • doc (bokeh.Document) – Bokeh document the bokeh model will be attached to.

  • comm (pyviz_comms.Comm) – Optional pyviz_comms when working in notebook

  • preprocess (boolean (default=True)) – Whether to run preprocessing hooks

Return type:

Returns the bokeh model corresponding to this panel object

index(object) int[source]#

Returns the integer index of the supplied object in the list of objects.

Parameters:

(object) (obj) –

Returns:

index (int)

Return type:

Integer index of the object in the layout.

insert(index: int, obj: Any) None[source]#

Inserts an object in the layout at the specified index.

Parameters:
  • (int) (index) –

  • (object) (object) –

jscallback(args: Dict[str, Any] = {}, **callbacks: str) Callback[source]#

Allows defining a JS callback to be triggered when a property changes on the source object. The keyword arguments define the properties that trigger a callback and the JS code that gets executed.

Parameters:
  • args (dict) – A mapping of objects to make available to the JS callback

  • **callbacks (dict) – A mapping between properties on the source model and the code to execute when that property changes

Returns:

callback – The Callback which can be used to disable the callback.

Return type:

Callback

Links properties on the this Reactive object to those on the target Reactive object in JS code.

Supports two modes, either specify a mapping between the source and target model properties as keywords or provide a dictionary of JS code snippets which maps from the source parameter to a JS code snippet which is executed when the property changes.

Parameters:
  • target (panel.viewable.Viewable | bokeh.model.Model | holoviews.core.dimension.Dimensioned) – The target to link the value to.

  • code (dict) – Custom code which will be executed when the widget value changes.

  • args (dict) – A mapping of objects to make available to the JS callback

  • bidirectional (boolean) – Whether to link source and target bi-directionally

  • **links (dict) – A mapping between properties on the source model and the target model property to link it to.

Returns:

link – The GenericLink which can be used unlink the widget and the target model.

Return type:

GenericLink

Links the parameters on this Reactive object to attributes on the target Parameterized object.

Supports two modes, either specify a mapping between the source and target object parameters as keywords or provide a dictionary of callbacks which maps from the source parameter to a callback which is triggered when the parameter changes.

Parameters:
  • target (param.Parameterized) – The target object of the link.

  • callbacks (dict | None) – Maps from a parameter in the source object to a callback.

  • bidirectional (bool) – Whether to link source and target bi-directionally

  • **links (dict) – Maps between parameters on this object to the parameters on the supplied object.

pop(index: int) Viewable[source]#

Pops an item from the layout by index.

Parameters:

(int) (index) –

remove(obj: Viewable) None[source]#

Removes an object from the layout.

Parameters:

(object) (obj) –

respond()[source]#

Executes the callback with the latest message in the chat log.

reverse() None[source]#

Reverses the objects in the layout.

save(filename: str | os.PathLike | IO, title: Optional[str] = None, resources: bokeh.resources.Resources | None = None, template: str | jinja2.environment.Template | None = None, template_variables: Dict[str, Any] = {}, embed: bool = False, max_states: int = 1000, max_opts: int = 3, embed_json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = True, embed_states: Dict[Any, Any] = {}, as_png: bool | None = None, **kwargs) None[source]#

Saves Panel objects to file.

Parameters:
  • filename (str or file-like object) – Filename to save the plot to

  • title (string) – Optional title for the plot

  • resources (bokeh resources) – One of the valid bokeh.resources (e.g. CDN or INLINE)

  • template – passed to underlying io.save

  • template_variables – passed to underlying io.save

  • embed (bool) – Whether the state space should be embedded in the saved file.

  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • embed_json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for the auto-generated json directory

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=True)) – Whether to report progress

  • embed_states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

  • as_png (boolean (default=None)) – To save as a .png. If None save_png will be true if filename is string and ends with png.

select(selector=None)[source]#

Iterates over the ChatInterface and any potential children in the applying the selector.

Parameters:

selector (type or callable or None) – The selector allows selecting a subset of Viewables by declaring a type or callable function to filter by.

Returns:

viewables

Return type:

list(Viewable)

send(value: panel.chat.message.ChatMessage | dict | Any, user: str | None = None, avatar: str | bytes | _io.BytesIO | None = None, respond: bool = True) panel.chat.message.ChatMessage | None[source]#

Sends a value and creates a new message in the chat log.

If respond is True, additionally executes the callback, if provided.

Parameters:
  • value (ChatMessage | dict | Any) – The message contents to send.

  • user (str | None) – The user to send as; overrides the message message’s user if provided. Will default to the user parameter.

  • avatar (str | bytes | BytesIO | None) – The avatar to use; overrides the message message’s avatar if provided. Will default to the avatar parameter.

  • respond (bool) – Whether to execute the callback.

Return type:

The message that was created.

serialize(exclude_users: Optional[List[str]] = None, filter_by: Optional[Callable] = None, format: Literal['transformers'] = 'transformers', custom_serializer: Optional[Callable] = None, **serialize_kwargs)[source]#

Exports the chat log.

Parameters:
  • format (str) – The format to export the chat log as; currently only supports “transformers”.

  • exclude_users (list(str) | None) – A list of user (case insensitive names) to exclude from serialization. If not provided, defaults to [“help”]. This will be executed before filter_by.

  • filter_by (callable) – A function to filter the chat log by. The function must accept and return a list of ChatMessage objects.

  • custom_serializer (callable) – A custom function to format the ChatMessage’s object. The function must accept one positional argument, the ChatMessage object, and return a string. If not provided, uses the serialize method on ChatMessage.

  • **serialize_kwargs

    Additional keyword arguments to use for the specified format.

    • format=”transformers” role_names : dict(str, str | list(str)) | None

      A dictionary mapping the role to the ChatMessage’s user name. Defaults to {“user”: [“user”], “assistant”: [self.callback_user]} if not set. The keys and values are case insensitive as the strings will all be lowercased. The values can be a string or a list of strings, e.g. {“user”: “user”, “assistant”: [“executor”, “langchain”]}.

      default_rolestr

      The default role to use if the user name is not found in role_names. If this is set to None, raises a ValueError if the user name is not found.

Return type:

The chat log serialized in the specified format.

servable(title: Optional[str] = None, location: bool | 'Location' = True, area: str = 'main', target: Optional[str] = None) ServableMixin[source]#

Serves the object or adds it to the configured pn.state.template if in a panel serve context, writes to the DOM if in a pyodide context and returns the Panel object to allow it to display itself in a notebook context.

Parameters:
  • title (str) – A string title to give the Document (if served as an app)

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

  • area (str (deprecated)) – The area of a template to add the component too. Only has an effect if pn.config.template has been set.

  • target (str) – Target area to write to. If a template has been configured on pn.config.template this refers to the target area in the template while in pyodide this refers to the ID of the DOM node to write to.

Return type:

The Panel object itself

server_doc(doc: Optional[Document] = None, title: Optional[str] = None, location: bool | 'Location' = True) Document[source]#

Returns a serveable bokeh Document with the panel attached

Parameters:
  • doc (bokeh.Document (optional)) – The bokeh Document to attach the panel to as a root, defaults to bokeh.io.curdoc()

  • title (str) – A string title to give the Document

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

doc – The bokeh document the panel was attached to

Return type:

bokeh.Document

show(title: Optional[str] = None, port: int = 0, address: Optional[str] = None, websocket_origin: Optional[str] = None, threaded: bool = False, verbose: bool = True, open: bool = True, location: bool | 'Location' = True, **kwargs) StoppableThread' | 'Server[source]#

Starts a Bokeh server and displays the Viewable in a new tab.

Parameters:
  • title (str | None) – A string title to give the Document (if served as an app)

  • port (int (optional, default=0)) – Allows specifying a specific port

  • address (str) – The address the server should listen on for HTTP requests.

  • websocket_origin (str or list(str) (optional)) – A list of hosts that can connect to the websocket. This is typically required when embedding a server app in an external web site. If None, “localhost” is used.

  • threaded (boolean (optional, default=False)) – Whether to launch the Server on a separate thread, allowing interactive use.

  • verbose (boolean (optional, default=True)) – Whether to print the address and port

  • open (boolean (optional, default=True)) – Whether to open the server in a new browser tab

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

server – Returns the Bokeh server instance or the thread the server was launched on (if threaded=True)

Return type:

bokeh.server.Server or panel.io.server.StoppableThread

stop() bool[source]#

Cancels the current callback task if possible.

Return type:

Whether the task was successfully stopped or done.

stream(value: str | dict | panel.chat.message.ChatMessage, user: str | None = None, avatar: str | bytes | _io.BytesIO | None = None, message: panel.chat.message.ChatMessage | None = None, replace: bool = False) panel.chat.message.ChatMessage | None[source]#

Streams a token and updates the provided message, if provided. Otherwise creates a new message in the chat log, so be sure the returned message is passed back into the method, e.g. message = chat.stream(token, message=message).

This method is primarily for outputs that are not generators– notably LangChain. For most cases, use the send method instead.

Parameters:
  • value (str | dict | ChatMessage) – The new token value to stream.

  • user (str | None) – The user to stream as; overrides the message’s user if provided. Will default to the user parameter.

  • avatar (str | bytes | BytesIO | None) – The avatar to use; overrides the message’s avatar if provided. Will default to the avatar parameter.

  • message (ChatMessage | None) – The message to update.

  • replace (bool) – Whether to replace the existing text when streaming a string or dict.

Return type:

The message that was updated.

undo(count: int = 1) List[Any][source]#

Removes the last count of messages from the chat log and returns them.

Parameters:

count (int) – The number of messages to remove, starting from the last message.

Return type:

The messages that were removed.


langchain Module#

Inheritance diagram of panel.chat.langchain

The langchain module integrates Langchain support with Panel.

class panel.chat.langchain.PanelCallbackHandler(instance: panel.chat.feed.ChatFeed | panel.chat.interface.ChatInterface, user: str = 'LangChain', avatar: str = '🦜')[source]#

Bases: object

The Langchain PanelCallbackHandler itself is not a widget or pane, but is useful for rendering and streaming the chain of thought from Langchain Tools, Agents, and Chains as ChatMessage objects.

Reference: https://panel.holoviz.org/reference/chat/PanelCallbackHandler.html

Example:

>>> chat_interface = pn.widgets.ChatInterface(callback=callback, callback_user="Langchain")
>>> callback_handler = pn.widgets.langchain.PanelCallbackHandler(instance=chat_interface)
>>> llm = ChatOpenAI(streaming=True, callbacks=[callback_handler])
>>> chain = ConversationChain(llm=llm)
on_chat_model_start(serialized: Dict[str, Any], messages: List, **kwargs: Any) None[source]#

To prevent the inherited class from raising NotImplementedError, will not call super() here.

on_retriever_end(documents, **kwargs: Any) Any[source]#

Run when Retriever ends running.

on_retriever_error(error: Union[Exception, KeyboardInterrupt], **kwargs: Any) Any[source]#

Run when Retriever errors.

on_text(text: str, **kwargs: Any)[source]#

Run when text is received.


message Module#

Inheritance diagram of panel.chat.message

The message module provides a low-level API for rendering chat messages.

class panel.chat.message.ChatMessage(object=None, **params)[source]#

Bases: PaneBase

A widget for displaying chat messages with support for various content types.

This widget provides a structured view of chat messages, including features like: - Displaying user avatars, which can be text, emoji, or images. - Showing the user’s name. - Displaying the message timestamp in a customizable format. - Associating reactions with messages and mapping them to icons. - Rendering various content types including text, images, audio, video, and more.

Reference: https://panel.holoviz.org/reference/chat/ChatMessage.html

Example:

>>> ChatMessage(object="Hello world!", user="New User", avatar="😊")

Parameters inherited from:

panel.viewable.Layoutable: align, aspect_ratio, design, height, min_width, min_height, max_height, styles, stylesheets, tags, width, width_policy, height_policy, sizing_mode, visible

panel.viewable.Viewable: loading

panel.pane.base.PaneBase: margin, default_layout

css_classes = param.List(allow_refs=True, bounds=(0, None), default=[‘chat-message’], label=’Css classes’, nested_refs=True, rx=<param.reactive.reactive_ops object at 0x143cd8bd0>)

The CSS classes to apply to the widget.

max_width = param.Integer(allow_refs=True, bounds=(0, None), default=1200, inclusive_bounds=(True, True), label=’Max width’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x143fa66d0>)

Minimal width of the component (in pixels) if width is adjustable.

object = param.Parameter(allow_None=True, allow_refs=False, label=’Object’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1440a7d90>)

The message contents. Can be any Python object that panel can display.

avatar = param.ClassSelector(allow_refs=False, class_=(<class ‘str’>, <class ‘_io.BytesIO’>, <class ‘bytes’>, <class ‘panel.pane.image.ImageBase’>), default=’’, label=’Avatar’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1440a5550>)

The avatar to use for the user. Can be a single character text, an emoji, or anything supported by pn.pane.Image. If not set, checks if the user is available in the default_avatars mapping; else uses the first character of the name.

avatar_lookup = param.Callable(allow_None=True, allow_refs=False, label=’Avatar lookup’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1440a7cd0>)

A function that can lookup an avatar from a user name. The function signature should be (user: str) -> Avatar. If this is set, default_avatars is disregarded.

default_avatars = param.Dict(allow_refs=False, class_=<class ‘dict’>, default={‘client’: ‘🧑’, ‘customer’: ‘🧑’, ‘employee’: ‘🧑’, ‘human’: ‘🧑’, ‘person’: ‘🧑’, ‘user’: ‘🧑’, ‘agent’: ‘🤖’, ‘ai’: ‘🤖’, ‘assistant’: ‘🤖’, ‘bot’: ‘🤖’, ‘chatbot’: ‘🤖’, ‘machine’: ‘🤖’, ‘robot’: ‘🤖’, ‘system’: ‘⚙️’, ‘exception’: ‘❌’, ‘error’: ‘❌’, ‘help’: ‘❓’, ‘adult’: ‘🧑’, ‘baby’: ‘👶’, ‘boy’: ‘👦’, ‘child’: ‘🧒’, ‘girl’: ‘👧’, ‘man’: ‘👨’, ‘woman’: ‘👩’, ‘chatgpt’: ‘{dist_path}assets/logo/gpt-3.svg’, ‘gpt3’: ‘{dist_path}assets/logo/gpt-3.svg’, ‘gpt4’: ‘{dist_path}assets/logo/gpt-4.svg’, ‘dalle’: ‘{dist_path}assets/logo/gpt-4.svg’, ‘openai’: ‘{dist_path}assets/logo/gpt-4.svg’, ‘huggingface’: ‘🤗’, ‘calculator’: ‘🧮’, ‘langchain’: ‘🦜’, ‘retriever’: ‘📄’, ‘tool’: ‘🛠️’, ‘translator’: ‘🌐’, ‘wolfram’: ‘{dist_path}assets/logo/wolfram.svg’, ‘wolfram alpha’: ‘{dist_path}assets/logo/wolfram.svg’, ‘llama’: ‘🦙’, ‘llama2’: ‘🐪’, ‘plot’: ‘📊’, ‘lumen’: ‘{dist_path}assets/logo/lumen.svg’, ‘holoviews’: ‘{dist_path}assets/logo/holoviews.svg’, ‘hvplot’: ‘{dist_path}assets/logo/hvplot.svg’, ‘panel’: ‘{dist_path}images/icon-vector.svg’}, label=’Default avatars’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1440a56d0>)

A default mapping of user names to their corresponding avatars to use when the user is specified but the avatar is. You can modify, but not replace the dictionary.

footer_objects = param.List(allow_refs=False, bounds=(0, None), default=[], label=’Footer objects’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1440a7d50>)

A list of objects to display in the column of the footer of the message.

header_objects = param.List(allow_refs=False, bounds=(0, None), default=[], label=’Header objects’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1440a7b90>)

A list of objects to display in the row of the header of the message.

reactions = param.List(allow_refs=False, bounds=(0, None), default=[], label=’Reactions’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1440a7d90>)

Reactions to associate with the message.

reaction_icons = param.ClassSelector(allow_None=True, allow_refs=False, class_=<class ‘panel.chat.icon.ChatReactionIcons’>, label=’Reaction icons’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1440a7ad0>)

A mapping of reactions to their reaction icons; if not provided defaults to {“favorite”: “heart”}.

timestamp = param.Date(allow_None=True, allow_refs=False, inclusive_bounds=(True, True), label=’Timestamp’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x14406a690>)

Timestamp of the message. Defaults to the creation time.

timestamp_format = param.String(allow_refs=False, default=’%H:%M’, label=’Timestamp format’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x144081f50>)

The timestamp format.

timestamp_tz = param.String(allow_None=True, allow_refs=False, label=’Timestamp tz’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1440a7e10>)

The timezone to used for the creation timestamp; only applicable if timestamp is not set. If None, tries to use pn.state.browser_info.timezone, else, the default tz of datetime.datetime.now(); see zoneinfo.available_timezones() for a list of valid timezones.

show_avatar = param.Boolean(allow_refs=False, default=True, label=’Show avatar’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1440a45d0>)

Whether to display the avatar of the user.

show_user = param.Boolean(allow_refs=False, default=True, label=’Show user’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1440a7c90>)

Whether to display the name of the user.

show_timestamp = param.Boolean(allow_refs=False, default=True, label=’Show timestamp’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1440a7d90>)

Whether to display the timestamp of the message.

show_reaction_icons = param.Boolean(allow_refs=False, default=True, label=’Show reaction icons’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1440a7c10>)

Whether to display the reaction icons.

show_copy_icon = param.Boolean(allow_refs=False, default=True, label=’Show copy icon’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1440a7d90>)

Whether to display the copy icon.

show_activity_dot = param.Boolean(allow_refs=False, default=False, label=’Show activity dot’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1440a7b50>)

Whether to show the activity dot.

renderers = param.HookList(allow_refs=False, bounds=(0, None), default=[], label=’Renderers’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1439f2290>)

A callable or list of callables that accept the object and return a Panel object to render the object. If a list is provided, will attempt to use the first renderer that does not raise an exception. If None, will attempt to infer the renderer from the object.

user = param.Parameter(allow_refs=False, default=’User’, label=’User’, nested_refs=False, rx=<param.reactive.reactive_ops object at 0x1440a7810>)

Name of the user who sent the message.

classmethod applies(obj: Any) float | bool | None[source]#

Returns boolean or float indicating whether the Pane can render the object.

If the priority of the pane is set to None, this method may also be used to define a float priority depending on the object being rendered.

clone(object: Optional[Any] = None, **params) T[source]#

Makes a copy of the Pane sharing the same parameters.

Parameters:
  • object (Optional new object to render) –

  • params (Keyword arguments override the parameters on the clone.) –

Return type:

Cloned Pane object

controls(parameters: List[str] = [], jslink: bool = True, **kwargs) Panel[source]#

Creates a set of widgets which allow manipulating the parameters on this instance. By default all parameters which support linking are exposed, but an explicit list of parameters can be provided.

Parameters:
  • parameters (list(str)) – An explicit list of parameters to return controls for.

  • jslink (bool) – Whether to use jslinks instead of Python based links. This does not allow using all types of parameters.

  • kwargs (dict) – Additional kwargs to pass to the Param pane(s) used to generate the controls widgets.

Return type:

A layout of the controls

default_layout[source]#

alias of Row

embed(max_states: int = 1000, max_opts: int = 3, json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = False, states={}) None[source]#

Renders a static version of a panel in a notebook by evaluating the set of states defined by the widgets in the model. Note this will only work well for simple apps with a relatively small state space.

Parameters:
  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for JSON filename

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=False)) – Whether to report progress

  • states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

classmethod get_pane_type(obj: Any, **kwargs) Type[PaneBase][source]#

Returns the applicable Pane type given an object by resolving the precedence of all types whose applies method declares that the object is supported.

Parameters:

(object) (obj) –

Return type:

The applicable Pane type with the highest precedence.

get_root(doc: Optional[Document] = None, comm: Comm | None = None, preprocess: bool = True) Model[source]#

Returns the root model and applies pre-processing hooks

Parameters:
  • doc (bokeh.document.Document) – Optional Bokeh document the bokeh model will be attached to.

  • comm (pyviz_comms.Comm) – Optional pyviz_comms when working in notebook

  • preprocess (bool (default=True)) – Whether to run preprocessing hooks

Return type:

Returns the bokeh model corresponding to this panel object

jscallback(args: Dict[str, Any] = {}, **callbacks: str) Callback[source]#

Allows defining a JS callback to be triggered when a property changes on the source object. The keyword arguments define the properties that trigger a callback and the JS code that gets executed.

Parameters:
  • args (dict) – A mapping of objects to make available to the JS callback

  • **callbacks (dict) – A mapping between properties on the source model and the code to execute when that property changes

Returns:

callback – The Callback which can be used to disable the callback.

Return type:

Callback

Links properties on the this Reactive object to those on the target Reactive object in JS code.

Supports two modes, either specify a mapping between the source and target model properties as keywords or provide a dictionary of JS code snippets which maps from the source parameter to a JS code snippet which is executed when the property changes.

Parameters:
  • target (panel.viewable.Viewable | bokeh.model.Model | holoviews.core.dimension.Dimensioned) – The target to link the value to.

  • code (dict) – Custom code which will be executed when the widget value changes.

  • args (dict) – A mapping of objects to make available to the JS callback

  • bidirectional (boolean) – Whether to link source and target bi-directionally

  • **links (dict) – A mapping between properties on the source model and the target model property to link it to.

Returns:

link – The GenericLink which can be used unlink the widget and the target model.

Return type:

GenericLink

Links the parameters on this Reactive object to attributes on the target Parameterized object.

Supports two modes, either specify a mapping between the source and target object parameters as keywords or provide a dictionary of callbacks which maps from the source parameter to a callback which is triggered when the parameter changes.

Parameters:
  • target (param.Parameterized) – The target object of the link.

  • callbacks (dict | None) – Maps from a parameter in the source object to a callback.

  • bidirectional (bool) – Whether to link source and target bi-directionally

  • **links (dict) – Maps between parameters on this object to the parameters on the supplied object.

save(filename: str | os.PathLike | IO, title: Optional[str] = None, resources: bokeh.resources.Resources | None = None, template: str | jinja2.environment.Template | None = None, template_variables: Dict[str, Any] = {}, embed: bool = False, max_states: int = 1000, max_opts: int = 3, embed_json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = True, embed_states: Dict[Any, Any] = {}, as_png: bool | None = None, **kwargs) None[source]#

Saves Panel objects to file.

Parameters:
  • filename (str or file-like object) – Filename to save the plot to

  • title (string) – Optional title for the plot

  • resources (bokeh resources) – One of the valid bokeh.resources (e.g. CDN or INLINE)

  • template – passed to underlying io.save

  • template_variables – passed to underlying io.save

  • embed (bool) – Whether the state space should be embedded in the saved file.

  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • embed_json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for the auto-generated json directory

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=True)) – Whether to report progress

  • embed_states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

  • as_png (boolean (default=None)) – To save as a .png. If None save_png will be true if filename is string and ends with png.

select(selector: Optional[Union[type, Callable[[Viewable], bool]]] = None) List[Viewable][source]#

Iterates over the Viewable and any potential children in the applying the Selector.

Parameters:

selector (type or callable or None) – The selector allows selecting a subset of Viewables by declaring a type or callable function to filter by.

Returns:

viewables

Return type:

list(Viewable)

serialize(prefix_with_viewable_label: bool = True, prefix_with_container_label: bool = True) str[source]#

Format the object to a string.

Parameters:
  • obj (Any) – The object to format.

  • prefix_with_viewable_label (bool) – Whether to include the name of the Viewable, or type of the viewable if no name is specified.

  • prefix_with_container_label (bool) – Whether to include the name of the container, or type of the container if no name is specified.

Returns:

The serialized string.

Return type:

str

servable(title: Optional[str] = None, location: bool | 'Location' = True, area: str = 'main', target: Optional[str] = None) ServableMixin[source]#

Serves the object or adds it to the configured pn.state.template if in a panel serve context, writes to the DOM if in a pyodide context and returns the Panel object to allow it to display itself in a notebook context.

Parameters:
  • title (str) – A string title to give the Document (if served as an app)

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

  • area (str (deprecated)) – The area of a template to add the component too. Only has an effect if pn.config.template has been set.

  • target (str) – Target area to write to. If a template has been configured on pn.config.template this refers to the target area in the template while in pyodide this refers to the ID of the DOM node to write to.

Return type:

The Panel object itself

server_doc(doc: Optional[Document] = None, title: Optional[str] = None, location: bool | 'Location' = True) Document[source]#

Returns a serveable bokeh Document with the panel attached

Parameters:
  • doc (bokeh.Document (optional)) – The bokeh Document to attach the panel to as a root, defaults to bokeh.io.curdoc()

  • title (str) – A string title to give the Document

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

doc – The bokeh document the panel was attached to

Return type:

bokeh.Document

show(title: Optional[str] = None, port: int = 0, address: Optional[str] = None, websocket_origin: Optional[str] = None, threaded: bool = False, verbose: bool = True, open: bool = True, location: bool | 'Location' = True, **kwargs) StoppableThread' | 'Server[source]#

Starts a Bokeh server and displays the Viewable in a new tab.

Parameters:
  • title (str | None) – A string title to give the Document (if served as an app)

  • port (int (optional, default=0)) – Allows specifying a specific port

  • address (str) – The address the server should listen on for HTTP requests.

  • websocket_origin (str or list(str) (optional)) – A list of hosts that can connect to the websocket. This is typically required when embedding a server app in an external web site. If None, “localhost” is used.

  • threaded (boolean (optional, default=False)) – Whether to launch the Server on a separate thread, allowing interactive use.

  • verbose (boolean (optional, default=True)) – Whether to print the address and port

  • open (boolean (optional, default=True)) – Whether to open the server in a new browser tab

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

server – Returns the Bokeh server instance or the thread the server was launched on (if threaded=True)

Return type:

bokeh.server.Server or panel.io.server.StoppableThread

stream(token: str, replace: bool = False)[source]#

Updates the message with the new token traversing the object to allow updating nested objects. When traversing a nested Panel the last object that supports rendering strings is updated, e.g. in a layout of Column(Markdown(…), Image(…)) the Markdown pane is updated.

Parameters:
  • token (str) – The token to stream to the text pane.

  • replace (bool (default=False)) – Whether to replace the existing text.

update(value: dict | panel.chat.message.ChatMessage | Any, user: str | None = None, avatar: str | bytes | _io.BytesIO | None = None)[source]#

Updates the message with a new value, user and avatar.

Parameters:
  • value (ChatMessage | dict | Any) – The message contents to send.

  • user (str | None) – The user to send as; overrides the message message’s user if provided.

  • avatar (str | bytes | BytesIO | None) – The avatar to use; overrides the message message’s avatar if provided.