MkLlm

github Show source on GitHub

Node for LLM-based text generation.

Example: Regular

Jinja

{{ "Write a poem about MkDocs" | MkLlm(model="openai:gpt-6-luna") }}

Python

MkLlm('Write a poem about MkDocs', [])

The MkDocs Lantern

From Markdown’s quiet pages,
a little lantern grows—
MkDocs gathers every heading,
every link, and note, and knows

how to turn a folder’s whispers
into paths of polished light,
with a theme to frame the reading
and a search that shines at night.

One command, and files are traveling
through the browser, clean and clear;
what began as words in plain text
becomes a guide for all to hear.

So build the map, arrange the chapters,
let each reference find its place—
MkDocs makes a home for knowledge,
one bright page at a time.

**The MkDocs Lantern**

From Markdown’s quiet pages,  
a little lantern grows—  
MkDocs gathers every heading,  
every link, and note, and knows

how to turn a folder’s whispers  
into paths of polished light,  
with a theme to frame the reading  
and a search that shines at night.

One command, and files are traveling  
through the browser, clean and clear;  
what began as words in plain text  
becomes a guide for all to hear.

So build the map, arrange the chapters,  
let each reference find its place—  
MkDocs makes a home for knowledge,  
one bright page at a time.
<p><strong>The MkDocs Lantern</strong></p>
<p>From Markdown’s quiet pages,<br />
a little lantern grows—<br />
MkDocs gathers every heading,<br />
every link, and note, and knows</p>
<p>how to turn a folder’s whispers<br />
into paths of polished light,<br />
with a theme to frame the reading<br />
and a search that shines at night.</p>
<p>One command, and files are traveling<br />
through the browser, clean and clear;<br />
what began as words in plain text<br />
becomes a guide for all to hear.</p>
<p>So build the map, arrange the chapters,<br />
let each reference find its place—<br />
MkDocs makes a home for knowledge,<br />
one bright page at a time.</p>

class MkLlm(mktext.MkText)

Name

Children

Inherits

MkText
mknodes.basenodes.mktext
Class for any Markup text.

graph TD
  4031386596["mkllm.MkLlm"]
  1315922923["mktext.MkText"]
  3160803176["rendercache.TemplateRenderMixin"]
  2751680898["builtins.object"]
  1359323199["mknode.MkNode"]
  1315922923 --> 4031386596
  3160803176 --> 1315922923
  2751680898 --> 3160803176
  1359323199 --> 1315922923
  2751680898 --> 1359323199
/home/runner/work/mknodes/mknodes/src/mknodes/templatenodes/mkllm/metadata.toml
[metadata]
icon = "mdi:view-grid"
status = "new"
name = "MkLlm"

[examples.regular]
title = "Regular"
jinja = """
{{ "Write a poem about MkDocs" | MkLlm(model="openai:gpt-6-luna") }}
"""

# [output.markdown]
# template = """
# <div class="grid cards" markdown="1">

# {% for item in node.get_items() %}
# -   {{ item | indent }}
# {% endfor %}
# </div>
# """
mknodes.templatenodes.mkllm.MkLlm
 34class MkLlm(mktext.MkText):
 35    """Node for LLM-based text generation."""
 36
 37    ICON = "material/format-list-group"
 38    REQUIRED_PACKAGES = [resources.Package("litellm")]
 39
 40    def __init__(
 41        self,
 42        user_prompt: str,
 43        system_prompt: str | None = None,
 44        model: str | ModelName = "openai:gpt-6-luna",
 45        context: str | None = None,
 46        extra_files: Sequence[str | os.PathLike[str]] | None = None,
 47        **kwargs: Any,
 48    ) -> None:
 49        """Constructor.
 50
 51        Args:
 52            user_prompt: Main prompt for the LLM
 53            system_prompt: System prompt to set LLM behavior
 54            model: LLM model identifier to use
 55            context: Main context string
 56            extra_files: Additional context files or strings
 57            kwargs: Keyword arguments passed to parent
 58        """
 59        super().__init__(**kwargs)
 60        self.user_prompt = user_prompt
 61        self.system_prompt = system_prompt
 62        self._model = model
 63        self._context = context
 64        self._extra_files = extra_files or []
 65
 66    def _process_extra_files(self) -> list[str]:
 67        """Process extra context items, reading files if necessary.
 68
 69        Returns:
 70            List of context strings.
 71        """
 72        context_items: list[str] = []
 73
 74        def process_dir(path: UPath) -> list[str]:
 75            return [f.read_text("utf-8") for f in path.rglob("*") if f.is_file()]
 76
 77        for item in self._extra_files:
 78            try:
 79                path = to_upath(item)
 80                if path.is_file():
 81                    context_items.append(path.read_text("utf-8"))
 82                elif path.is_dir():
 83                    context_items.extend(process_dir(path))
 84                else:
 85                    context_items.append(str(item))
 86            except Exception as exc:
 87                err_msg = f"Failed to read context file: {item}"
 88                logger.warning(err_msg)
 89                raise ValueError(err_msg) from exc
 90
 91        return context_items
 92
 93    def _llm_params(self) -> dict[str, Any]:
 94        context_items = self._process_extra_files()
 95        combined_context = "\n".join(filter(None, [self._context, *context_items]))
 96        return dict(
 97            user_prompt=self.user_prompt,
 98            system_prompt=self.system_prompt or "",
 99            model=self._model,
100            context=combined_context,
101        )
102
103    def get_input_requests(self) -> list[inputs.InputRequest]:
104        return [inputs.InputRequest.create("llm", **self._llm_params())]
105
106    def get_text(self) -> str:
107        """Generate text using the LLM (pinned in the lock file of the inputs store).
108
109        Returns:
110            Generated text content.
111        """
112        try:
113            return self.ctx.inputs.get("llm", **self._llm_params())
114        except inputs.InputUnavailableError as e:
115            logger.warning("MkLlm: %s, using a placeholder", e)
116            return UNAVAILABLE_TEXT
Page info
Code for this page
mknodes.manual.nodes_section.create_section_for_nodes
 93def create_section_for_nodes(
 94    nav: mk.MkNav,
 95    klasses: Sequence[type[mk.MkNode]],
 96) -> mk.MkTable:
 97    table = mk.MkTable(columns=["Node", "Docstrings", "Markdown extensions"])
 98    for kls in klasses:
 99        tpl = "classpage_custom.jinja"
100        page = mk.MkClassPage(kls, icon=kls.ICON, template_path=tpl, parent=nav, hide="toc")
101        nav += page
102        if kls.STATUS:
103            page.metadata.status = kls.STATUS
104        elif kls.JS_FILES:
105            page.metadata.status = "js"
106        elif kls.CSS:
107            page.metadata.status = "css"
108        page.created_by = create_section_for_nodes
109        link = mk.MkLink(page, kls.__name__, icon=kls.ICON)
110        extensions = ", ".join(f"`{i}`" for i in kls.REQUIRED_EXTENSIONS)
111        table.add_row((link, kls.__doc__, extensions))
112    return table
Resources
Resources(css=[],
          markdown_extensions={'admonition': {},
                               'pymdownx.details': {},
                               'pymdownx.highlight': {'anchor_linenums': True,
                                                      'line_spans': '__span',
                                                      'pygments_lang_class': True},
                               'pymdownx.superfences': {'custom_fences': [{'class': 'mermaid',
                                                                           'format': <function fence_code_format at 0x7ff77e88b060>,
                                                                           'name': 'mermaid'}]},
                               'pymdownx.tabbed': {},
                               'tables': {}},
          plugins=[Plugin('mkdocstrings')],
          js=[],
          assets=[],
          packages=[])
Metadata
created:
  source_filename: /home/runner/work/mknodes/mknodes/src/mknodes/manual/nodes_section.py
  source_function: create_section_for_nodes
  source_line_no: 93
hide:
- toc
icon: material/format-list-group
title: MkLlm