Robust code generation combining grammars and LLMs

Introduction

This document (notebook) discusses different combinations of Grammar-Based Parser-Interpreters (GBPI) and Large Language Models (LLMs) to generate executable code from Natural Language Computational Specifications (NLCM). We have the soft assumption that the NLCS adhere to a certain relatively small Domain Specific Language (DSL) or use terminology from that DSL. Another assumption is that the target software packages are not necessarily well-known by the LLMs, i.e. direct LLM requests for code using them would produce meaningless results.

We want to do such combinations because:

  • GBPI are fast, precise, but with a narrow DSL scope
  • LLMs can be unreliable and slow, but with a wide DSL scope

Because of GBPI and LLMs are complementary technologies with similar and overlapping goals the possible combinations are many. We concentrate on two of the most straightforward designs: (1) judged parallel race of methods execution, and (2) using LLMs as a fallback method if grammar parsing fails. We show asynchronous programmingimplementations for both designs using the Wolfram Language function LLMGraph.

The Machine Learning (ML) paclet “MonadicSparseMatrixRecommender” is used to demonstrate that the generated code is executable.

The rest of the document is structured as follows:

  • Initial grammar-LLM combinations
    • Assumptions, straightforward designs, and trade-offs
  • Comprehensive combinations enumeration (attempt)
    • Tabular and morphological analysis breakdown
  • Three methods for parsing ML DSL specs into Raku code
    • One grammar-based, two LLM-based
  • Parallel execution with an LLM judge
    • Straightforward, but computationally wasteful and expensive
  • Grammar-to-LLM fallback mechanism
    • The easiest and most robust solution
  • Concluding comments and observations

TL;DR

  • Combining grammars and LLMs produces robust translators.
  • Three translators with different faithfulness and coverage are demonstrated and used.
  • Two of the simplest, yet effective, combinations are implemented and demonstrated.
    • Parallel race and grammar-to-LLM fallback.
  • Asynchronous implementations with LLM-graphs are a very good fit!
    • Just look at the LLM-graph plots (and be done reading.)

Initial Combinations and Associated Assumptions

The goal is to combine grammar-based parser-interpreters with LLMs in order to achieve robust parsing and interpretation of computational workflow specifications.

Here are some example combinations of these approaches:

  1. A few methods, both grammar-based and LLM-based, are initiated in parallel. Whichever method produces a correct result first is selected as the answer.
    • This approach assumes that when the grammar-based methods are effective, they will finish more quickly than the LLM-based methods.
  2. The grammar method is invoked first; if it fails, an LLM method (or a sequence of LLM methods) is employed.
  3. LLMs are utilized at the grammar-rule level to provide matching objects that the grammar can work with.
  4. If the grammar method fails, an LLM normalizer for user commands is invoked to generate specifications that the grammar can parse.
  5. It is important to distinguish between declarative specifications and those that prescribe specific steps.
    • For a workflow given as a list of steps the grammar parser may successfully parse most steps, but LLMs may be required for a few exceptions.

The main trade-off in these approaches is as follows:

  • Grammar methods are challenging to develop but can be very fast and precise.
    • Precision can be guaranteed and rigorously tested.
  • LLM methods are quicker to develop but tend to be slower and can be unreliable, particularly for less popular workflows, programming languages, and packages.

Also, combinations based on LLM tools (aka LLM external function calling) are not considered because LLM-tools invocation is too unpredictable and unreliable.

Comprehensive breakdown (attempt)

This section has a “concise” table that expands the combinations list above into the main combinatorial strategies for Grammar *** LLMs** for robust parsing and interpretation of workflow specifications. The table is not an exhaustive list of such combinations, but illustrates their diversity and, hopefully, can give ideas for future developments.

A few summary points (for table’s content/subject):

  • Grammar (Raku regex/grammar)
    • Pros: fast, deterministic, validated, reproducible
    • Cons: hard to design for large domains, brittle for natural language inputs
  • LLMs
    • Pros: fast to prototype, excellent at normalization/paraphrasing, flexible
    • Cons: slow, occasionally wrong, hallucination risk, inconsistent output formats
  • Conclusion:
    • The most robust systems combine grammar precision with LLM adaptability , typically by putting grammars first and using LLMs for repair, normalization, expansions, or semantic interpretation (i.e. “fallback”.)

Table: Combination Patterns for Parsing Workflow Specifications

tbl = Dataset[{<|"ID" -> 1, "CombinationPattern" -> "Parallel Race: Grammar + LLM", "Description" -> "Launch grammar-based parsing and one or more LLM interpreters in parallel; whichever yields a valid parse first is accepted.", "Pros" -> {"Fast when grammar succeeds", "Robust fallback", "Reduces latency unpredictability of LLMs"}, "ConsTradeoffs" -> {"Requires orchestration", "Need a validator for LLM output"}|>, <|"ID" -> 2, "CombinationPattern" -> "Grammar-First, LLM-Fallback", "Description" -> "Try grammar parser first; if it fails, invoke LLM-based parsing or normalization.", "Pros" -> {"Deterministic preference for grammar", "Testable correctness when grammar succeeds"}, "ConsTradeoffs" -> {"LLM fallback may produce inconsistent structures"}|>, <|"ID" -> 3, "CombinationPattern" -> "LLM-Assisted Grammar (Rule-Level)", "Description" -> "Individual grammar rules delegate to an LLM for ambiguous or context-heavy matching; LLM supplies tokens or AST fragments.", "Pros" -> {"Handles complexity without inflating grammar", "Modular LLM usage"}, "ConsTradeoffs" -> {"LLM behavior may break rule determinism", "Harder to reproduce"}|>, <|"ID" -> 4, "CombinationPattern" -> "LLM Normalizer -> Grammar Parser", "Description" -> "When grammar fails, LLM rewrites/normalizes input into a canonical form; grammar is applied again.", "Pros" -> {"Grammar remains simple", "Leverages LLM skill at paraphrasing"}, "ConsTradeoffs" -> {"Quality depends on normalizer", "Feedback loops possible"}|>, <|"ID" -> 5, "CombinationPattern" -> "Hybrid Declarative vs Procedural Parsing", "Description" -> "Grammar extracts structural/declarative parts; LLM interprets procedural/stepwise parts or vice versa.", "Pros" -> {"Each subsystem tackles what it's best at", "Reduces grammar complexity"}, "ConsTradeoffs" -> {"Harder to maintain global consistency", "Requires AST stitching logic"}|>, <|"ID" -> 6, "CombinationPattern" -> "Grammar-Generated Tests for LLM", "Description" -> "Grammar used to generate examples and counterexamples; LLM outputs are validated against grammar constraints.", "Pros" -> {"Powerful for verifying LLM outputs", "Reduces hallucinations"}, "ConsTradeoffs" -> {"Grammar must encode constraints richly", "Validation pipeline required"}|>, <|"ID" -> 7, "CombinationPattern" -> "LLM as Adaptive Heuristic for Grammar Ambiguities", "Description" -> "When grammar yields multiple parses, LLM chooses or ranks the \"most plausible\" AST.", "Pros" -> {"Improves disambiguation", "Good for underspecified workflows"}, "ConsTradeoffs" -> {"LLM can pick syntactically impossible interpretations"}|>, <|"ID" -> 8, "CombinationPattern" -> "LLM as Semantic Phase After Grammar", "Description" -> "Grammar creates an AST; LLM interprets semantics, fills in missing steps, or resolves vague ops.", "Pros" -> {"Clean separation of syntax vs semantics", "Grammar ensures correctness"}, "ConsTradeoffs" -> {"Semantic interpretation may drift from syntax"}|>, <|"ID" -> 9, "CombinationPattern" -> "Self-Healing Parse Loop", "Description" -> "Grammar fails -> LLM proposes corrections -> grammar retries -> if still failing, LLM creates full AST.","Pros" -> {"Iterative and robust", "Captures user intent progressively"}, "ConsTradeoffs" -> {"More expensive; risk of oscillation"}|>, <|"ID" -> 10, "CombinationPattern" -> "Grammar Embedding Inside Prompt Templates", "Description" -> "Grammar definitions serialized into the prompt, guiding the LLM to conform to the grammar (soft constraints).", "Pros" -> {"Faster than grammar execution in some cases", "Encourages consistent structure"}, "ConsTradeoffs" -> {"Weak guarantees", "LLM may ignore grammar"}|>, <|"ID" -> 11, "CombinationPattern" -> "LLM-Driven Grammar Induction or Refinement", "Description" -> "LLM suggests new grammar rules or transformations; developer approves; the grammar evolves over time.", "Pros" -> {"Faster grammar evolution", "Useful for new workflow languages"}, "ConsTradeoffs" -> {"Requires human QA", "Risk of regressing accuracy"}|>, <|"ID" -> 12, "CombinationPattern" -> "Regex Engine as LLM Guardrail", "Description" -> "Regex or token rules used to validate or filter LLM results before accepting them.", "Pros" -> {"Lightweight constraints", "Useful for quick prototyping"}, "ConsTradeoffs" -> {"Regex too weak for complex syntax"}|>}]; 
  
 tbl = tbl[All, KeyDrop[#, "ID"] &];
 tbl = tbl[All, ReplacePart[#, "Pros" -> ColumnForm[#Pros]] &];
 tbl = tbl[All, ReplacePart[#, "ConsTradeoffs" -> ColumnForm[#ConsTradeoffs]] &];
 tbl = tbl[All, Style[#, FontFamily -> "Times New Roman"] & /@ # &];
 ResourceFunction["GridTableForm"][tbl]

#CombinationPatternDescriptionProsConsTradeoffs
1Parallel Race: Grammar + LLMLaunch grammar-based parsing and one or more LLM interpreters in parallel; whichever yields a valid parse first is accepted.{{Fast when grammar succeeds}, {Robust fallback}, {Reduces latency unpredictability of LLMs}}{{Requires orchestration}, {Need a validator for LLM output}}
2Grammar-First, LLM-FallbackTry grammar parser first; if it fails, invoke LLM-based parsing or normalization.{{Deterministic preference for grammar}, {Testable correctness when grammar succeeds}}{{LLM fallback may produce inconsistent structures}}
3LLM-Assisted Grammar (Rule-Level)Individual grammar rules delegate to an LLM for ambiguous or context-heavy matching; LLM supplies tokens or AST fragments.{{Handles complexity without inflating grammar}, {Modular LLM usage}}{{LLM behavior may break rule determinism}, {Harder to reproduce}}
4LLM Normalizer -> Grammar ParserWhen grammar fails, LLM rewrites/normalizes input into a canonical form; grammar is applied again.{{Grammar remains simple}, {Leverages LLM skill at paraphrasing}}{{Quality depends on normalizer}, {Feedback loops possible}}
5Hybrid Declarative vs Procedural ParsingGrammar extracts structural/declarative parts; LLM interprets procedural/stepwise parts or vice versa.{{Each subsystem tackles what it’s best at}, {Reduces grammar complexity}}{{Harder to maintain global consistency}, {Requires AST stitching logic}}
6Grammar-Generated Tests for LLMGrammar used to generate examples and counterexamples; LLM outputs are validated against grammar constraints.{{Powerful for verifying LLM outputs}, {Reduces hallucinations}}{{Grammar must encode constraints richly}, {Validation pipeline required}}
7LLM as Adaptive Heuristic for Grammar AmbiguitiesWhen grammar yields multiple parses, LLM chooses or ranks the “most plausible” AST.{{Improves disambiguation}, {Good for underspecified workflows}}{{LLM can pick syntactically impossible interpretations}}
8LLM as Semantic Phase After GrammarGrammar creates an AST; LLM interprets semantics, fills in missing steps, or resolves vague ops.{{Clean separation of syntax vs semantics}, {Grammar ensures correctness}}{{Semantic interpretation may drift from syntax}}
9Self-Healing Parse LoopGrammar fails -> LLM proposes corrections -> grammar retries -> if still failing, LLM creates full AST.{{Iterative and robust}, {Captures user intent progressively}}{{More expensive; risk of oscillation}}
10Grammar Embedding Inside Prompt TemplatesGrammar definitions serialized into the prompt, guiding the LLM to conform to the grammar (soft constraints).{{Faster than grammar execution in some cases}, {Encourages consistent structure}}{{Weak guarantees}, {LLM may ignore grammar}}
11LLM-Driven Grammar Induction or RefinementLLM suggests new grammar rules or transformations; developer approves; the grammar evolves over time.{{Faster grammar evolution}, {Useful for new workflow languages}}{{Requires human QA}, {Risk of regressing accuracy}}
12Regex Engine as LLM GuardrailRegex or token rules used to validate or filter LLM results before accepting them.{{Lightweight constraints}, {Useful for quick prototyping}}{{Regex too weak for complex syntax}}

Diversity reasons

  • The diversity of combinations in the table above arises because Raku grammars and LLMs occupy fundamentally different but highly complementary positions in the parsing spectrum.
  • Raku grammars provide determinism, speed, verifiability, and structural guarantees, but they require upfront design and struggle with ambiguity, informal input, and evolving specifications.
  • LLMs, in contrast, excel at normalization, semantic interpretation, ambiguity resolution, and adapting to fluid or poorly defined languages, yet they lack determinism, may hallucinate, and are slower.
  • When these two technologies meet, every architectural choice — who handles syntax, who handles semantics, who runs first, who validates whom, who repairs or refines — defines a distinct strategy.
  • Hence, the design space naturally expands into many valid hybrid patterns rather than a single “best” pipeline.
  • That said, the fallback pattern implemented below can be considered the “best option” from certain development perspectives because it is simple, effective, and has fast execution times.

See the corresponding Morphological Analysis table which correspond to this taxonomy mind-map:

Setup

Here are the packages used in this document (notebook):

Needs["AntonAntonov`DSLTranslation`"];
Needs["AntonAntonov`NLPTemplateEngine`"];
Needs["AntonAntonov`DSLExamples`"];
Needs["AntonAntonov`MermaidJS`"];
Needs["AntonAntonov`MonadicSparseMatrixRecommender`"];

Three DSL translations

This section demonstrates the use of three different translation methods:

  1. Grammar-based parser-interpreter of computational workflows
  2. LLM-based translator using few-shot learning with relevant DSL examples
  3. Natural Language Processing (NLP) interpreter using code templates and LLMs to fill-in the corresponding parameters

The translators are ordered according of their faithfulness, most faithful first. It can be said that at the same time, the translators are ordered according to their coverage — widest coverage is by the last.

Grammar-based

Here a recommender pipeline specified with natural language commands is translated into Raku code of the package “ML::SparseMatrixRecommender” using a sub of the paclet “DSLTranslation”:

spec = "create from dsData; apply LSI functions IDF, None, Cosine; recommend by profile for passengerSex:male, and passengerClass:1st; join across using dsData; echo the pipeline value";

DSLTranslation[spec, "WLCode" -> True]

Out[]= SMRMonUnit[]==>SMRMonCreate[dsData]==>SMRMonApplyTermWeightFunctions["GlobalWeightFunction" -> "IDF", "LocalWeightFunction" -> "None", "NormalizerFunction" -> "Cosine"]==>SMRMonRecommendByProfile[{"passengerSex:male", "passengerClass:1st"}]==>SMRMonJoinAcross[dsData]==>SMRMonEchoValue[]

The function DSLTranslation uses a web service by default but if Raku and the package “DSL::Translators” are installed it can use the provided Command Line Interface (CLI):

DSLTranslation[spec, "Source" -> "Shell", "CLIPath" -> "~/.rakubrew/shims/dsl-translation"]

Out[]= SMRMonUnit[]==>SMRMonCreate[dsData]==>SMRMonApplyTermWeightFunctions["GlobalWeightFunction" -> "IDF", "LocalWeightFunction" -> "None", "NormalizerFunction" -> "Cosine"]==>SMRMonRecommendByProfile[{"passengerSex:male", "passengerClass:1st"}]==>SMRMonJoinAcross[dsData]==>SMRMonEchoValue[]

For more details of the grammar-based approach see the presentations:

Via LLM examples

LLM translations can be done using a set of from-to rules. This is the so-called few shot learning of LLMs. The paclet “DSLExamples” has a collection of such examples for different computational workflows. (Mostly ML at this point.) The examples are hierarchically organized by programming language and workflow name; see the resource file “dsl-examples.json”, or execute DSLExamples[].

Here is a table that shows the known DSL translation examples in “DSL::Examples” :

Dataset[Map[Flatten, List @@@ Normal[ResourceFunction["AssociationKeyFlatten"][Map[Length, DSLExamples[], {2}]]]]][All, AssociationThread[{"Language", "Workflow", "Count"}, #] &]

LanguageWorkflowCount
WLClCon20
WLQRMon27
WLLSAMon17
WLSMRMon20
PythonQRMon23
PythonLSAMon15
PythonSMRMon20
RQRMon26
RLSAMon17
RSMRMon20
RakuSMRMon20

Here is the definition of an LLM translation function that uses examples:

LLMPipelineSegment[lang_String : "WL", workflow_String : "SMRMon"] := LLMExampleFunction[Normal@DSLExamples[lang, workflow]];

Here is a recommender pipeline specified with natural language commands:

spec = "new recommender; create from @dsData;  apply LSI functions IDF, None, Cosine;  recommend by profile for passengerSex:male, and passengerClass:1st; join across with @dsData on \"id\"; echo the pipeline value; classify by profile passengerSex:female, and passengerClass:1st on the tag passengerSurvival; echo value";

commands = StringSplit[spec, ""];

Translate to WL code line-by-line:

res = LLMPipelineSegment[] /@ commands; res = Map[StringTrim@StringReplace[#, RegularExpression["Output\h*:"] -> ""] &, res];
 res = StringRiffle[res, "==>"]

Out[]= "SMRMonUnit[]==>SMRMonCreate[dsData]==>SMRMonApplyTermWeightFunctions[\"IDF\", \"None\", \"Cosine\"]==>SMRMonRecommendByProfile[{\"passengerSex.male\", \"passengerClass.1st\"}]==>SMRMonJoinAcross[@dsData, \"id\"]==>SMRMonEchoValue[]==>SMRMonClassify[\"passengerSurvival\", {\"passengerSex.female\", \"passengerClass.1st\"}]==>SMRMonEchoValue[]"

Or translate by just calling the function over the whole $spec :

LLMPipelineSegment[][spec]

Out[]= "```wolframSMRMonUnit[] |> SMRMonCreate[dsData] |> SMRMonApplyTermWeightFunctions[\"IDF\", \"None\", \"Cosine\"] |> SMRMonRecommendByProfile[{\"passengerSex\" -> \"male\", \"passengerClass\" -> \"1st\"}] |> SMRMonJoinAcross[dsData, \"id\"] |> SMRMonEchoValue[] |> SMRMonClassify[\"passengerSurvival\", {\"passengerSex\" -> \"female\", \"passengerClass\" -> \"1st\"}] |> SMRMonEchoValue[]```"

Remark: That latter call is faster, but it needs additional processing for “monadic” workflows.

By NLP Template Engine

Here a “free text” recommender pipeline specification is translated to Raku code using the sub concretize of the package “ML::NLPTemplateEngine” :

Concretize["create a recommender with dfTitanic; apply the LSI functions IDF, None, Cosine; recommend by profile 1st and male"]

Out[]= Hold[smrObj = SMRMonUnit[]==>SMRMonCreate[None]==>SMRMonRecommendByProfile[{"1st", "male"}, profile]==>SMRMonJoinAcross[None]==>SMRMonEchoValue[];]

The paclet “NLPTemplateEngine” uses a Question Answering System (QAS) implemented in FindTextualAnswer. A QAS can be implemented in different ways, with different conceptual and computation complexity. “NLPTemplateEngine” also has an LLM based implementation of QAS, LLMTextualAnswer. (Also see the resource function with the same name.)

For more details of the NLP template engine approach see the presentations:

Parallel race (judged): Grammar + LLM

In this section we implement the first, most obvious, and conceptually simplest combination of grammar-based- with LLM-based translations:

  • All translators — grammar-based and LLM-based are run in parallel
  • An LLM judge selects the one that adheres best to the given specification

The implementation of this strategy with an LLM graph (say, by using LLMGraph) is straightforward.

Here is such an LLM graph that:

  • Runs all three translation methods above
  • There is a judge that picks which on of the LLM methods produced better result
  • Judge’s output is used to make (and launch) a notebook report
LLMPipelineSegmentFunction[lang_ : "WL", worflowName_String : "SMRMon"] := LLMExampleFunction[Normal@DSLExamples[][lang][worflowName]];

aLangSeparator = <| "Python" -> ".", "Raku" -> ".", "R" -> "%>%", "WL" -> "==>" |>;

Clear[LLMExamplesTranslation];
 LLMExamplesTranslation[spec_, lang_ : "WL", worflowName_String : "SMRMon", splitQ_ : False] := 
    Module[{llmPipelineSegment, commands}, 
     
     llmPipelineSegment = LLMPipelineSegmentFunction[lang]; 
     
     If[TrueQ@splitQ, 
      Echo["with spec splitting..."]; 
      commands = StringSplit[spec, ""]; 
      StringRiffle[StringTrim@StringReplace[llmPipelineSegment /@ commands, StartOfString ~~ "Output" ~~ ___ ~~ ":" -> ""], aLangSeparator[lang]], 
     (*ELSE*) 
      Echo["no spec splitting..."]; 
      StringReplace[llmPipelineSegment[spec], ";" -> aLangSeparator[lang], Infinity] 
     ] 
    ];

JudgeFunction[spec_, lang_, dslGrammar_, llmExamples_, nlpTemplateEngine_] := 
    StringRiffle[{
      "Choose the generated code that most fully adheres to the spec:", 
      spec, 
      "from the following " <> lang <> " generation results:", "1) DSL-grammar:" <> dslGrammar <> "", 
      "2) LLM-examples:" <> llmExamples <> "", 
      "3) NLP-template-engine:" <> nlpTemplateEngine <> "", 
      "and copy it:" 
     }, 
     "" 
    ];

(*JudgeFunction[`spec`,`lang`,`dslGrammar`,`llmExamples`,`nlpTemplateEngine`]*)

tmplJudge = StringTemplate["Choose the generated code that most fully adheres to the spec:\\n\\n\\n`spec`\\n\\n\\nfrom the following `lang` generation results:\\n\\n\\n1) DSL-grammar:\\n`dslGrammar`\\n\\n\\n2) LLM-examples:\\n`llmExamples`\\n\\n\\n3) NLP-template-engine:\\n`nlpTemplateEngine`\\n\\n\\nand copy it:"]

1sk1d044my02q
JudgementReport[spec_, lang_, dslGrammar_, llmExamples_, nlpTemplateEngine_, judge_] := 
    Module[{names, codes, rows, tableHTML, judgementBlock}, 
     names = {"dsl-grammar", "llm-examples", "nlp-template-engine"}; 
     codes = {dslGrammar, llmExamples, nlpTemplateEngine}; 
     rows = MapThread[<|"name" -> #1, "code" -> #2|> &, {names, codes}];
    (*WL analogue of to-html(...,field-names=> <name code>)*) 
     tableHTML = Dataset[rows]; 
     judgementBlock = If[StringContainsQ[judge, "```"], judge, "```" <> lang <> "" <> judge <> "```"]; 
     CreateDocument[{
       TextCell["Best generated code", "Section"], 
       TextCell["Three " <> lang <> " code generations were submitted for the spec:", "Text"], 
       TextCell[spec, "Program"], 
       TextCell["Here are the results:", "Text"], 
       ExpressionCell[tableHTML, "Output"], 
       TextCell["Judgement", "Subsection"], 
       TextCell[judgementBlock, "Output"] 
      }] 
    ];

Rules for parallel race:

rules = <|
     "dslGrammar" -> <|"EvaluationFunction" -> (DSLTranslation[#spec, "ToLanguage" -> #lang, "WLCode" -> False, "Format" -> "CODE"] &), "Input" -> {"spec", "lang"}|>, 
     "llmExamples" -> <|"EvaluationFunction" -> (LLMExamplesTranslation[#spec, #lang, "SMRMon", #split] &), "Input" -> {"spec", "lang", "split"}|>,
     "nlpTemplateEngine" -> <|"EvaluationFunction" -> (Concretize[#spec, "TargetLanguage" -> #lang] &), "Input" -> {"spec", "lang"}|>,
    (*judge-><|EvaluationFunction->(judgeFunction[#spec,#lang,#dslGrammar,#llmExamples,#nlpTemplateEngine]&)|>,*) 
     "judge" -> tmplJudge, 
     "report" -> <|"EvaluationFunction" -> (JudgementReport[#spec, #lang, #dslGrammar, #llmExamples, #nlpTemplateEngine, #judge] &)|> 
    |>;

Corresponding LLM-graph construction:

gBestCode = LLMGraph[rules]

1l626dkgaymsq

Here is a recommender workflow specification:

spec = " make a brand new recommender with the data @dsData; apply LSI functions IDF, None, Cosine;  recommend by profile for passengerSex:male, and passengerClass:1st; join across with @dsData on \"id\"; echo the pipeline value; ";

Here the graph is executed:

res = gBestCode[<|"spec" -> spec, "lang" -> "R", "split" -> True|>];

Here is a screenshot of the LLM-graph result:

LLM-graph visualization

Information[gBestCode, "Graph"]

For details on LLM-graphs design see the video:

Fallback: DSL-grammar to LLM-examples

Instead of having DSL-grammar- and LLM computations running in parallel, we can make an LLM-graph in which the LLM computations are invoked if the DSL-grammar parsing-and-interpretation fails. In this section we make such a graph.

Before making the graph let us also generalize it to work with other ML workflows, not just recommendations.

Let us make an LLM function with a similar functionality. I.e. an LLM-function that classifies a natural language computation specification into workflow labels used by “DSLExamples”. Here is such a function using the sub LLMClassify provided by “NLPTemplateEngine”:

lsMLLabels = {"Classification", "Latent Semantic Analysis", "Quantile Regression", "Recommendations"}; 
  
 aWorlflowMonNames = <|
       "Classification" -> "ClCon", 
       "Latent Semantic Analysis" -> "LSAMon", 
       "Quantile Regression" -> "QRMon", 
       "Recommendations" -> "SMRMon" 
     |>; 
  
 LLMWorkflowClassify[spec_] := Module[{res = LLMClassify[spec, lsMLLabels, "Request" -> "which of these workflows characterizes it (just one label)"]}, 
     Lookup[aWorlflowMonNames, res, res] 
   ]

(* Example invocation *)
 (*LLMWorkflowClassify[spec]*)

Remark: The paclet “NLPTemplateEngine” has (1) a pre-trained ML workflows classifier, and (2) a separate, generic LLM-based classifier.

Rules for fallback execution:

TranslationSuccessQ[s_] := StringQ[s] && StringLength[StringTrim[s]] > 5;
 rules = <|
     "DSLGrammar" -> <|"EvaluationFunction" -> (DSLTranslation[#spec, "ToLanguage" -> #lang, "WLCode" -> False, "Format" -> "CODE"] &), "Input" -> {"spec", "lang"}|>, 
     "WorkflowName" -> <|"EvaluationFunction" -> (LLMWorkflowClassify[#spec] &)|>, 
     "LLMExamples" -> <|
       "EvaluationFunction" -> (LLMExamplesTranslation[#spec, #lang, #WorkflowName, #split] &), 
       "Input" -> {"spec", "lang", "WorkflowName", "split"}, 
       "TestFunction" -> (! TranslationSuccessQ[#DSLGrammar] &)|>, 
     "Code" -> <|"EvaluationFunction" -> (If[TranslationSuccessQ[#DSLGrammar], #DSLGrammar, #LLMExamples] &)|> 
    |>;

Corresponding LLM-graph construction:

gRobust = LLMGraph[rules]

Here the LLM graph is run over a spec that can be parsed by DSL-grammar (notice the very short computation time):

Here is the obtained result:

Here is a spec that cannot be parsed by the DSL-grammar interpreter — note that there is just a small language change in the first line:

spec = " create from @dsData;  apply LSI functions IDF, None, Cosine;  recommend by profile for passengerSex:male, and passengerClass:1st; join across with @dsData on \"id\"; echo the pipeline value; ";

Nevertheless, we obtain a correct result via LLM-examples:

res = gRobust[<|"spec" -> spec, "lang" -> "R", "split" -> True|>]

Out[]= "SMRMonCreate(data = @dsData) %>%SMRMonApplyTermWeightFunctions(globalWeightFunction = \"IDF\", localWeightFunction = \"None\", normalizerFunction = \"Cosine\") %>%SMRMonRecommendByProfile( profile = c(\"passengerSex:male\", \"passengerClass:1st\")) %>%SMRMonJoinAcross( data = @dsData, by = \"id\" ) %>%SMRMonEchoValue()"

Here is the corresponding graph plot:

Information[gRobust, "Graph"]

Let us specify another workflow — for ML-classification with Wolfram Language — and run the graph:

spec = " use the dataset @dsData; split the data into training and testing parts with 0.8 ratio; make a nearest neighbors classifier; show classifier accuracy, precision, and recall; echo the pipeline value; ";

res = gRobust[<|"spec" -> spec, "lang" -> "WL", "split" -> True|>]

Out[]= "SMRMonUse[dsData]==>SMRMonSplitData[0.8]==>SMRMonMakeClassifier[\"NearestNeighbors\"]==>SMRMonClassifierMeasurements[\"Accuracy\", \"Precision\", \"Recall\"]==>SMRMonEchoValue[]"

Concluding comments and observations

  • Using LLM graphs gives the ability to impose desired orchestration and collaboration between deterministic programs and LLMs.
    • By contrast, the “inversion of control” of LLM – tools is “capricious.”
  • LLM-graphs are both a generalization of LLM-tools, and a lower level infrastructural functionality than LLM-tools.
  • The LLM-graph for the parallel-race translation is very similar to the LLM-graph for comprehensive document summarization described in [AA4].
  • The expectation that DSL examples would provide both fast and faithful results is mostly confirmed in ≈20 experiments.
  • Using the NLP template engine is also fast because LLMs are harnessed through QAS.
  • The DSL examples translation had to be completed with a workflow classifier.
    • Such classifiers are also part of the implementations of the other two approaches .
    • The grammar – based one uses a deterministic classifier, [AA1]
    • The NLP template engine uses an LLM classifier .
  • An interesting extension of the current work is to have a grammar-LLM combination in which when the grammar fails then the LLM “normalizes” the specs until the grammar can parse them.
    • Currently, LLMGraph does not support graphs with cycles, hence this approach “can wait” (or be implemented by other means .)
  • Multiple DSL examples can be efficiently derived by random sentence generation with different grammars.
    • Similar to the DSL commands classifier making approach taken in [AA1] .
  • LLMs can be also used to improve and extend the DSL grammars.
    • And it is interesting to consider automating that process, instead of doing it via human supervision.
  • This notebook is the Wolfram Language version of the document “Day 6 — Robust code generation combining grammars and LLMs”, [AA6], (notebook), using Raku.

References

Articles, blog posts

[AA1] Anton Antonov, “Fast and compact classifier of DSL commands” , (2022), RakuForPrediction at WordPress .

[AA2] Anton Antonov, “Grammar based random sentences generation, Part 1” , (2023), RakuForPrediction at WordPress .

[AA3] Anton Antonov, “LLM::Graph” , (2025), RakuForPrediction at WordPress .

[AA4] Anton Antonov, “Agentic-AI for text summarization” , (2025), RakuForPrediction at WordPress .

[AA5] Anton Antonov, “LLM::Graph plots interpretation guide” , (2025), RakuForPrediction at WordPress .

[AA6] Anton Antonov, “Day 6 — Robust code generation combining grammars and LLMs”, (2025), Raku Advent Calendar at WordPress.

Packages

[AAp1] Anton Antonov, DSL::Translators, Raku package , (2020-2025), GitHub/antononcube .

[AAp2] Anton Antonov, ML::FindTextualAnswer, Raku package , (2023-2025), GitHub/antononcube .

[AAp3] Anton Antonov, MLP::NLPTemplateEngine, Raku package , (2023-2025), GitHub/antononcube .

[AAp4] Anton Antonov, DSL::Examples, Raku package , (2024-2025), GitHub/antononcube .

[AAp5] Anton Antonov, LLM::Graph, Raku package , (2025), GitHub/antononcube .

[AAp6] Anton Antonov, ML::SparseMatrixRecommender, Raku package , (2025), GitHub/antononcube .

Videos

[AAv1] Anton Antonov, “Raku for Prediction presentation at The Raku Conference 2021”, (2021), YouTube/@AAA4prediction .

[AAv2] Anton Antonov, “Simplified Machine Learning Workflows Overview”, (2022), YouTube/@WolframResearch .

[AAv3] Anton Antonov, “NLP Template Engine, Part 1” , (2021), YouTube/@AAA4prediction .

[AAv4] Anton Antonov, “Natural Language Processing Template Engine” , (2023), YouTube/@WolframResearch .

[WRIv1] Wolfram Research, Inc., “Live CEOing Ep 886: Design Review of LLMGraph” , (2025), YouTube/@WolframResearch .

Doomsday clock parsing and plotting

Introduction

The Doomsday Clock is a symbolic timepiece maintained by the Bulletin of the Atomic Scientists (BAS) since 1947. It represents how close humanity is perceived to be to global catastrophe, primarily nuclear war but also including climate change and biological threats. The clock’s hands are set annually to reflect the current state of global security; midnight signifies theoretical doomsday.

In this notebook we consider two tasks:

  • Parsing of Doomsday Clock reading statements
  • Evolution of Doomsday Clock times
    • We extract relevant Doomsday Clock timeline data from the corresponding Wikipedia page.
      • (Instead of using a page from BAS.)
    • We show how timeline data from that Wikipedia page can be processed with “standard” Wolfram Language (WL) functions and with LLMs.
    • The result plot shows the evolution of the minutes to midnight.
      • The plot could show trends, highlighting significant global events that influenced the clock setting.
      • Hence, we put in informative callouts and tooltips.

The data extraction and visualization in the notebook serve educational purposes or provide insights into historical trends of global threats as perceived by experts. We try to make the ingestion and processing code universal and robust, suitable for multiple evaluations now or in the (near) future.

Remark: Keep in mind that the Doomsday Clock is a metaphor and its settings are not just data points but reflections of complex global dynamics (by certain experts and a board of sponsors.)

Remark: Currently (2024-12-30) Doomsday Clock is set at 90 seconds before midnight.

Data ingestion

Here we ingest the Doomsday Clock timeline page and show corresponding statistics:

url = "https://thebulletin.org/doomsday-clock/timeline/";
txtEN = Import[url, "Plaintext"];
TextStats[txtEN]

(*<|"Characters" -> 77662, "Words" -> 11731, "Lines" -> 1119|>*)

By observing the (plain) text of that page we see the Doomsday Clock time setting can be extracted from the sentence(s) that begin with the following phrase:

startPhrase = "Bulletin of the Atomic Scientists";
sentence = Select[Map[StringTrim, StringSplit[txtEN, "\n"]], StringStartsQ[#, startPhrase] &] // First

(*"Bulletin of the Atomic Scientists, with a clock reading 90 seconds to midnight"*)

Grammar and parsers

Here is a grammar in Extended Backus-Naur Form (EBNF) for parsing Doomsday Clock statements:

ebnf = "
<TOP> = <clock-reading>  ;
<clock-reading> = <opening> , ( <minutes> | [ <minutes> , [ 'and' | ',' ] ] , <seconds> ) , 'to' , 'midnight' ;
<opening> = [ { <any> } ] , 'clock' , [ 'is' ] , 'reading' ; 
<any> = '_String' ;
<minutes> = <integer> <& ( 'minute' | 'minutes' )  <@ \"Minutes\"->#&;
<seconds> = <integer> <& ( 'second' | 'seconds' ) <@ \"Seconds\"->#&;
<integer> = '_?IntegerQ' ;";

Remark: The EBNF grammar above can be obtained with LLMs using a suitable prompt with example sentences. (We do not discuss that approach further in this notebook.)

Here the parsing functions are generated from the EBNF string above:

ClearAll["p*"]
res = GenerateParsersFromEBNF[ParseToEBNFTokens[ebnf]];
res // LeafCount

(*375*)

We must redefine the parser pANY (corresponding to the EBNF rule “”) in order to prevent pANY of gobbling the word “clock” and in that way making the parser pOPENING fail.

pANY = ParsePredicate[StringQ[#] && # != "clock" &];

Here are random sentences generated with the grammar:

SeedRandom[32];
GrammarRandomSentences[GrammarNormalize[ebnf], 6] // Sort // ColumnForm

54jfnd 9y2f clock is reading 46 second to midnight
clock is reading 900 minutes to midnight
clock is reading 955 second to midnight
clock reading 224 minute to midnight
clock reading 410 minute to midnight
jdsf5at clock reading 488 seconds to midnight

Verifications of the (sub-)parsers:

pSECONDS[{"90", "seconds"}]

(*{{{}, "Seconds" -> 90}}*)

pOPENING[ToTokens@"That doomsday clock is reading"]

(*{{{}, {{"That", "doomsday"}, {"clock", {"is", "reading"}}}}}*)

Here the “top” parser is applied:

str = "the doomsday clock is reading 90 seconds to midnight";
pTOP[ToTokens@str]

(*{{{}, {{{"the", "doomsday"}, {"clock", {"is", "reading"}}}, {{{}, "Seconds" -> 90}, {"to", "midnight"}}}}}*)

Here the sentence extracted above is parsed and interpreted into an association with keys “Minutes” and “Seconds”:

aDoomReading = Association@Cases[Flatten[pTOP[ToTokens@sentence]], _Rule]

(*<|"Seconds" -> 90|>*)

Plotting the clock

Using the interpretation derived above here we make a list suitable for ClockGauge:

clockShow = DatePlus[{0, 0, 0, 12, 0, 0}, {-(Lookup[aDoomReading, "Minutes", 0]*60 + aDoomReading["Seconds"]), "Seconds"}]

(*{-2, 11, 30, 11, 58, 30}*)

In that list, plotting of a Doomsday Clock image (or gauge) is trivial.

ClockGauge[clockShow, GaugeLabels -> Automatic]

Let us define a function that makes the clock-gauge plot for a given association.

Clear[DoomsdayClockGauge];
Options[DoomsdayClockGauge] = Options[ClockGauge];
DoomsdayClockGauge[m_Integer, s_Integer, opts : OptionsPattern[]] := DoomsdayClockGauge[<|"Minutes" -> m, "Seconds" -> s|>, opts];
DoomsdayClockGauge[a_Association, opts : OptionsPattern[]] :=
  Block[{clockShow},
   clockShow = DatePlus[{0, 0, 0, 12, 0, 0}, {-(Lookup[a, "Minutes", 0]*60 + Lookup[a, "Seconds", 0]), "Seconds"}];
   ClockGauge[clockShow, opts, GaugeLabels -> Placed[Style["Doomsday\nclock", RGBColor[0.7529411764705882, 0.7529411764705882, 0.7529411764705882], FontFamily -> "Krungthep"], Bottom]]
   ];

Here are examples:

Row[{
   DoomsdayClockGauge[17, 0], 
   DoomsdayClockGauge[1, 40, GaugeLabels -> Automatic, PlotTheme -> "Scientific"], 
   DoomsdayClockGauge[aDoomReading, PlotTheme -> "Marketing"] 
  }]

More robust parsing

More robust parsing of Doomsday Clock statements can be obtained in these three ways:

  • “Fuzzy” match of words
    • For misspellings like “doomsdat” instead of “doomsday.”
  • Parsing of numeric word forms.
    • For statements, like, “two minutes and twenty five seconds.”
  • Delegating the parsing to LLMs when grammar parsing fails.

Fuzzy matching

The parser ParseFuzzySymbol can be used to handle misspellings (via EditDistance):

pDD = ParseFuzzySymbol["doomsday", 2];
lsPhrases = {"doomsdat", "doomsday", "dumzday"};
ParsingTestTable[pDD, lsPhrases]

In order to include the misspelling handling into the grammar we manually rewrite the grammar. (The grammar is small, so, it is not that hard to do.)

pANY = ParsePredicate[StringQ[#] && EditDistance[#, "clock"] > 1 &];
pOPENING = ParseOption[ParseMany[pANY]]⊗ParseFuzzySymbol["clock", 1]⊗ParseOption[ParseSymbol["is"]]⊗ParseFuzzySymbol["reading", 2];
pMINUTES = "Minutes" -> # &⊙(pINTEGER ◁ ParseFuzzySymbol["minutes", 3]);
pSECONDS = "Seconds" -> # &⊙(pINTEGER ◁ ParseFuzzySymbol["seconds", 3]);
pCLOCKREADING = Cases[#, _Rule, Infinity] &⊙(pOPENING⊗(pMINUTES⊕ParseOption[pMINUTES⊗ParseOption[ParseSymbol["and"]⊕ParseSymbol["&"]⊕ParseSymbol[","]]]⊗pSECONDS)⊗ParseSymbol["to"]⊗ParseFuzzySymbol["midnight", 2]);

Here is a verification table with correct- and incorrect spellings:

lsPhrases = {
    "doomsday clock is reading 2 seconds to midnight", 
    "dooms day cloc is readding 2 minute and 22 sekonds to mildnight"};
ParsingTestTable[pCLOCKREADING, lsPhrases, "Layout" -> "Vertical"]

Parsing of numeric word forms

One way to make the parsing more robust is to implement the ability to parse integer names (or numeric word forms) not just integers.

Remark: For a fuller discussion — and code — of numeric word forms parsing see the tech note “Integer names parsing” of the paclet “FunctionalParsers”, [AAp1].

First, we make an association that connects integer names with corresponding integer values

aWordedValues = Association[IntegerName[#, "Words"] -> # & /@ Range[0, 100]];
aWordedValues = KeyMap[StringRiffle[StringSplit[#, RegularExpression["\\W"]], " "] &, aWordedValues];
Length[aWordedValues]

(*101*)

Here is how the rules look like:

aWordedValues[[1 ;; -1 ;; 20]]

(*<|"zero" -> 0, "twenty" -> 20, "forty" -> 40, "sixty" -> 60, "eighty" -> 80, "one hundred" -> 100|>*)

Here we program the integer names parser:

pUpTo10 = ParseChoice @@ Map[ParseSymbol[IntegerName[#, {"English", "Words"}]] &, Range[0, 9]];
p10s = ParseChoice @@ Map[ParseSymbol[IntegerName[#, {"English", "Words"}]] &, Range[10, 100, 10]];
pWordedInteger = ParseApply[aWordedValues[StringRiffle[Flatten@{#}, " "]] &, p10s\[CircleTimes]pUpTo10\[CirclePlus]p10s\[CirclePlus]pUpTo10];

Here is a verification table of that parser:

lsPhrases = {"three", "fifty seven", "thirti one"};
ParsingTestTable[pWordedInteger, lsPhrases]

There are two parsing results for “fifty seven”, because pWordedInteger is defined with p10s⊗pUpTo10⊕p10s… . This can be remedied by using ParseJust or ParseShortest:

lsPhrases = {"three", "fifty seven", "thirti one"};
ParsingTestTable[ParseJust@pWordedInteger, lsPhrases]

Let us change pINTEGER to parse both integers and integer names:

pINTEGER = (ToExpression\[CircleDot]ParsePredicate[StringMatchQ[#, NumberString] &])\[CirclePlus]pWordedInteger;
lsPhrases = {"12", "3", "three", "forty five"};
ParsingTestTable[pINTEGER, lsPhrases]

Let us try the new parser using integer names for the clock time:

str = "the doomsday clock is reading two minutes and forty five seconds to midnight";
pTOP[ToTokens@str]

(*{{{}, {"Minutes" -> 2, "Seconds" -> 45}}}*)

Enhance with LLM parsing

There are multiple ways to employ LLMs for extracting “clock readings” from arbitrary statements for Doomsday Clock readings, readouts, and measures. Here we use LLM few-shot training:

flop = LLMExampleFunction[{
    "the doomsday clock is reading two minutes and forty five seconds to midnight" -> "{\"Minutes\":2, \"Seconds\": 45}", 
    "the clock of the doomsday gives 92 seconds to midnight" -> "{\"Minutes\":0, \"Seconds\": 92}", 
    "The bulletin atomic scienist maybe is set to a minute an 3 seconds." -> "{\"Minutes\":1, \"Seconds\": 3}" 
   }, "JSON"]

Here is an example invocation:

flop["Maybe the doomsday watch is at 23:58:03"]

(*{"Minutes" -> 1, "Seconds" -> 57}*)

The following function combines the parsing with the grammar and the LLM example function — the latter is used for fallback parsing:

Clear[GetClockReading];
GetClockReading[st_String] := 
   Block[{op}, 
    op = ParseJust[pTOP][ToTokens[st]]; 
    Association@
     If[Length[op] > 0 && op[[1, 1]] === {}, 
      Cases[op, Rule], 
     (*ELSE*) 
      flop[st] 
     ] 
   ];

Robust parser demo

Here is the application of the combine function above over a certain “random” Doomsday Clock statement:

s = "You know, sort of, that dooms-day watch is 1 and half minute be... before the big boom. (Of doom...)";
GetClockReading[s]

(*<|"Minutes" -> 1, "Seconds" -> 30|>*)

Remark: The same type of robust grammar-and-LLM combination is explained in more detail in the video “Robust LLM pipelines (Mathematica, Python, Raku)”, [AAv1]. (See, also, the corresponding notebook [AAn1].)

Timeline

In this section we extract Doomsday Clock timeline data and make a corresponding plot.

Parsing page data

Instead of using the official Doomsday clock timeline page we use Wikipedia:

url = "https://en.wikipedia.org/wiki/Doomsday_Clock";
data = Import[url, "Data"];

Get timeline table:

tbl = Cases[data, {"Timeline of the Doomsday Clock [ 13 ] ", x__} :> x, Infinity] // First;

Show table’s columns:

First[tbl]

(*{"Year", "Minutes to midnight", "Time ( 24-h )", "Change (minutes)", "Reason", "Clock"}*)

Make a dataset:

dsTbl = Dataset[Rest[tbl]][All, AssociationThread[{"Year", "MinutesToMidnight", "Time", "Change", "Reason"}, #] &];
dsTbl = dsTbl[All, Append[#, "Date" -> DateObject[{#Year, 7, 1}]] &];
dsTbl[[1 ;; 4]]

Here is an association used to retrieve the descriptions from the date objects:

aDateToDescr = Normal@dsTbl[Association, #Date -> BreakStringIntoLines[#Reason] &];

Using LLM-extraction instead

Alternatively, we can extract the Doomsday Clock timeline using LLMs. Here we get the plaintext of the Wikipedia page and show statistics:

txtWk = Import[url, "Plaintext"];
TextStats[txtWk]

(*<|"Characters" -> 43623, "Words" -> 6431, "Lines" -> 315|>*)

Here we get the Doomsday Clock timeline table from that page in JSON format using an LLM:

res = 
  LLMSynthesize[{
    "Give the time table of the doomsday clock as a time series that is a JSON array.", 
    "Each element of the array is a dictionary with keys 'Year', 'MinutesToMidnight', 'Time', 'Description'.", 
    txtWk, 
    LLMPrompt["NothingElse"]["JSON"] 
   }, 
   LLMEvaluator -> LLMConfiguration[<|"Provider" -> "OpenAI", "Model" -> "gpt-4o", "Temperature" -> 0.4, "MaxTokens" -> 5096|>] 
  ]

(*"```json[{\"Year\": 1947, \"MinutesToMidnight\": 7, \"Time\": \"23:53\", \"Description\": \"The initial setting of the Doomsday Clock.\"},{\"Year\": 1949, \"MinutesToMidnight\": 3, \"Time\": \"23:57\", \"Description\": \"The Soviet Union tests its first atomic bomb, officially starting the nuclear arms race.\"}, ... *)

Post process the LLM result:

res2 = ToString[res, CharacterEncoding -> "UTF-8"];
res3 = StringReplace[res2, {"```json", "```"} -> ""];
res4 = ImportString[res3, "JSON"];
res4[[1 ;; 3]]

(*{{"Year" -> 1947, "MinutesToMidnight" -> 7, "Time" -> "23:53", "Description" -> "The initial setting of the Doomsday Clock."}, {"Year" -> 1949, "MinutesToMidnight" -> 3, "Time" -> "23:57", "Description" -> "The Soviet Union tests its first atomic bomb, officially starting the nuclear arms race."}, {"Year" -> 1953, "MinutesToMidnight" -> 2, "Time" -> "23:58", "Description" -> "The United States and the Soviet Union test thermonuclear devices, marking the closest approach to midnight until 2020."}}*)

Make a dataset with the additional column “Date” (having date-objects):

dsDoomsdayTimes = Dataset[Association /@ res4];
dsDoomsdayTimes = dsDoomsdayTimes[All, Append[#, "Date" -> DateObject[{#Year, 7, 1}]] &];
dsDoomsdayTimes[[1 ;; 4]]

Here is an association that is used to retrieve the descriptions from the date objects:

aDateToDescr2 = Normal@dsDoomsdayTimes[Association, #Date -> #Description &];

Remark: The LLM derived descriptions above are shorter than the descriptions in the column “Reason” of the dataset obtained parsing the page data. For the plot tooltips below we use the latter.

Timeline plot

In order to have informative Doomsday Clock evolution plot we obtain and partition dataset’s time series into step-function pairs:

ts0 = Normal@dsDoomsdayTimes[All, {#Date, #MinutesToMidnight} &];
ts2 = Append[Flatten[MapThread[Thread[{#1, #2}] &, {Partition[ts0[[All, 1]], 2, 1], Most@ts0[[All, 2]]}], 1], ts0[[-1]]];

Here are corresponding rule wrappers indicating the year and the minutes before midnight:

lbls = Map[Row[{#Year, Spacer[3], "\n", IntegerPart[#MinutesToMidnight], Spacer[2], "m", Spacer[2], Round[FractionalPart[#MinutesToMidnight]*60], Spacer[2], "s"}] &, Normal@dsDoomsdayTimes];
lbls = Map[If[#[[1, -3]] == 0, Row@Take[#[[1]], 6], #] &, lbls];

Here the points “known” by the original time series are given callouts:

aRules = Association@MapThread[#1 -> Callout[Tooltip[#1, aDateToDescr[#1[[1]]]], #2] &, {ts0, lbls}];
ts3 = Lookup[aRules, Key[#], #] & /@ ts2;

Finally, here is the plot:

DateListPlot[ts3, 
  PlotStyle -> Directive[{Thickness[0.007`], Orange}],
  Epilog -> {PointSize[0.01`], Black, Point[ts0]}, 
  PlotLabel -> Row[(Style[#1, FontSize -> 16, FontColor -> Black, FontFamily -> "Verdana"] &) /@ {"Doomsday clock: minutes to midnight,", Spacer[3], StringRiffle[MinMax[Normal[dsDoomsdayTimes[All, "Year"]]], "-"]}], 
  FrameLabel -> {"Year", "Minutes to midnight"}, 
  Background -> GrayLevel[0.94`], Frame -> True, 
  FrameTicks -> {{Automatic, (If[#1 == 0, {0, Style["00:00", Red]}, {#1, Row[{"23:", 60 - #1}]}] &) /@ Range[0, 17]}, {Automatic, Automatic}}, GridLines -> {None, All},
  AspectRatio -> 1/3, ImageSize -> 1200
]

Remark: By hovering with the mouse over the black points the corresponding descriptions can be seen. We considered using clock-gauges as tooltips, but showing clock-settings reasons is more informative.

Remark: The plot was intentionally made to resemble the timeline plot in Doomsday Clock’s Wikipedia page.

Conclusion

As expected, parsing, plotting, or otherwise processing the Doomsday Clock settings and statements are excellent didactic subjects for textual analysis (or parsing) and temporal data visualization. The visualization could serve educational purposes or provide insights into historical trends of global threats as perceived by experts. (Remember, the clock’s settings are not just data points but reflections of complex global dynamics.)

One possible application of the code in this notebook is to make a “web service“ that gives clock images with Doomsday Clock readings. For example, click on this button:

Setup

Needs["AntonAntonov`FunctionalParsers`"]

Clear[TextStats];
TextStats[s_String] := AssociationThread[{"Characters", "Words", "Lines"}, Through[{StringLength, Length@*TextWords, Length@StringSplit[#, "\n"] &}[s]]];

BreakStringIntoLines[str_String, maxLength_Integer : 60] := Module[
    {words, lines, currentLine}, 
    words = StringSplit[StringReplace[str, RegularExpression["\\v+"] -> " "]]; 
    lines = {}; 
    currentLine = ""; 
    Do[
       If[StringLength[currentLine] + StringLength[word] + 1 <= maxLength, 
          currentLine = StringJoin[currentLine, If[currentLine === "", "", " "], word], 
          AppendTo[lines, currentLine]; 
          currentLine = word; 
        ], 
       {word, words} 
     ]; 
    AppendTo[lines, currentLine]; 
    StringJoin[Riffle[lines, "\n"]] 
  ]

References

Articles, notebooks

[AAn1] Anton Antonov, “Making robust LLM computational pipelines from software engineering perspective”, (2024), Wolfram Community.

Paclets

[AAp1] Anton Antonov, “FunctionalParsers”, (2023), Wolfram Language Paclet Repository.

Videos

[AAv1] Anton Antonov, “Robust LLM pipelines (Mathematica, Python, Raku)”, (2024), YouTube/@AAA4prediction.

Robust LLM pipelines

… or “Making Robust LLM Computational Pipelines from Software Engineering Perspective”

Abstract

Large Language Models (LLMs) are powerful tools with diverse capabilities, but from Software Engineering (SE) Point Of View (POV) they are unpredictable and slow. In this presentation we consider five ways to make more robust SE pipelines that include LLMs. We also consider a general methodological workflow for utilizing LLMs in “every day practice.”

Here are the five approaches we consider:

  1. DSL for configuration-execution-conversion
    • Infrastructural, language-design level solution
  2. Detailed, well crafted prompts
    • AKA “Prompt engineering”
  3. Few-shot training with examples
  4. Via a Question Answering System (QAS) and code templates
  5. Grammar-LLM chain of responsibility
  6. Testings with data types and shapes over multiple LLM results

Compared to constructing SE pipelines, Literate Programming (LP) offers a dual or alternative way to use LLMs. For that it needs support and facilitation of:

  • Convenient LLM interaction (or chatting)
  • Document execution (weaving and tangling)

The discussed LLM workflows methodology is supported in Python, Raku, Wolfram Language (WL). The support in R is done via Python (with “reticulate”, [TKp1].)

The presentation includes multiple examples and showcases.

Modeling of the LLM utilization process is hinted but not discussed.

Here is a mind-map of the presentation:

Here are the notebook used in the presentation:


General structure of LLM-based workflows

All systematic approaches of unfolding and refining workflows based on LLM functions, will include several decision points and iterations to ensure satisfactory results.

This flowchart outlines such a systematic approach:


References

Articles, blog posts

[AA1] Anton Antonov, “Workflows with LLM functions”, (2023), RakuForPrediction at WordPress.

Notebooks

[AAn1] Anton Antonov, “Workflows with LLM functions (in Raku)”, (2023), Wolfram Community.

[AAn2] Anton Antonov, “Workflows with LLM functions (in Python)”, (2023), Wolfram Community.

[AAn3] Anton Antonov, “Workflows with LLM functions (in WL)”, (2023), Wolfram Community.

Packages

Raku

[AAp1] Anton Antonov, LLM::Functions Raku package, (2023-2024), GitHub/antononcube. (raku.land)

[AAp2] Anton Antonov, LLM::Prompts Raku package, (2023-2024), GitHub/antononcube. (raku.land)

[AAp3] Anton Antonov, Jupyter::Chatbook Raku package, (2023-2024), GitHub/antononcube. (raku.land)

Python

[AAp4] Anton Antonov, LLMFunctionObjects Python package, (2023-2024), PyPI.org/antononcube.

[AAp5] Anton Antonov, LLMPrompts Python package, (2023-2024), GitHub/antononcube.

[AAp6] Anton Antonov, JupyterChatbook Python package, (2023-2024), GitHub/antononcube.

[MWp1] Marc Wouts, jupytext Python package, (2021-2024), GitHub/mwouts.

R

[TKp1] Tomasz Kalinowski, Kevin Ushey, JJ Allaire, RStudio, Yuan Tang, reticulate R package, (2016-2024)

Videos

[AAv1] Anton Antonov, “Robust LLM pipelines (Mathematica, Python, Raku)”, (2024), YouTube/@AAA4Predictions.

[AAv2] Anton Antonov, “Integrating Large Language Models with Raku”, (2023), The Raku Conference 2023 at YouTube.

LLM над “Искусством аттриционной войны: Уроки войны России против Украины”

Введение

Этот блог пост использует различные запросы к Большим Языковым Моделям (БЯМ) для суммаризации статьи “Искусство аттриционной войны: Уроки войны России против Украины” от Алекса Вершинина.

Замечание: Мы тоже будем пользоваться сокращением “LLM” (для “Large Language Models”).

В этой статье для Королевского института объединенных служб (RUSI), Алекс Вершинин обсуждает необходимость для Запада пересмотреть свою военную стратегию в отношении аттрициона в предвидении затяжных конфликтов. Статья противопоставляет аттриционную и маневренную войну, подчеркивая важность промышленной мощности, генерации сил и экономической устойчивости в победе в затяжных войнах.

Эта (полученная с помощью LLM) иерархическая диаграмма хорошо суммирует статью:

Примечание: Мы планируем использовать этот пост/статью в качестве ссылки в предстоящем посте/статье с соответствующей математической моделью
(на основе Системной динамики.)

Структура поста:

  1. Темы
    Табличное разбиение содержания.
  2. Ментальная карта
    Структура содержания и связи концепций.
  3. Суммарное изложение, идеи и рекомендации
    Основная помощь в понимании.
  4. Модель системной динамики
    Как сделать данный наблюдения операциональными?

Темы

Вместо суммарного изложения рассмотрите эту таблицу тем:

темасодержание
ВведениеСтатья начинается с подчеркивания необходимости для Запада подготовиться к аттриционной войне, контрастируя это с предпочтением коротких, решающих конфликтов.
Понимание Аттриционной ВойныОпределяет аттриционную войну и подчеркивает ее отличия от маневренной войны, акцентируя важность промышленной мощности и способности заменять потери.
Экономическое ИзмерениеОбсуждает, как экономика и промышленные мощности играют ключевую роль в поддержании войны аттрициона, с примерами из Второй мировой войны.
Генерация СилИсследует, как различные военные доктрины и структуры, такие как НАТО и Советский Союз, влияют на способность генерировать и поддерживать силы в аттриционной войне.
Военное ИзмерениеДетализирует военные операции и стратегии, подходящие для аттриционной войны, включая важность ударов над маневрами и фазы таких конфликтов.
Современная ВойнаИсследует сложности современной войны, включая интеграцию различных систем и вызовы координации наступательных операций.
Последствия для Боевых ОперацийОписывает, как аттриционная война влияет на глубинные удары и стратегическое поражение способности противника регенерировать боевую мощь.
ЗаключениеРезюмирует ключевые моменты о том, как вести и выигрывать аттриционную войну, подчеркивая важность стратегического терпения и тщательного планирования.

Ментальная карта

Вот ментальная карта показывает структуру статьи и суммирует связи между представленными концепциями:


Суммарное изложение, идеи и рекомендации

СУММАРНОЕ ИЗЛОЖЕНИЕ

Алекс Вершинин в “Искусстве аттриционной войны: Уроки войны России против Украины” для Королевского института объединенных служб обсуждает необходимость для Запада пересмотреть свою военную стратегию в отношении аттрициона в предвидении затяжных конфликтов.
Статья противопоставляет аттриционную и маневренную войну, подчеркивая важность промышленной мощности, генерации сил и экономической устойчивости в победе в затяжных войнах.

ИДЕИ:

  • Аттриционные войны требуют уникальной стратегии, сосредоточенной на силе, а не на местности.
  • Западная военная стратегия традиционно отдает предпочтение быстрым, решающим битвам, не готова к затяжному аттриционному конфликту.
  • Войны аттрициона со временем выравнивают шансы между армиями с различными начальными возможностями.
  • Победа в аттриционных войнах больше зависит от экономической силы и промышленной мощности, чем от военного мастерства.
  • Интеграция гражданских товаров в военное производство облегчает быстрое вооружение в аттриционных войнах.
  • Западные экономики сталкиваются с трудностями в быстром масштабировании военного производства из-за мирного эффективности и аутсорсинга.
  • Аттриционная война требует массового и быстрого расширения армий, что требует изменения стратегий производства и обучения.
  • Эффективность военной доктрины НАТО ухудшается в аттриционной войне из-за времени, необходимого для замены опытных некомиссированных офицеров (NCOs).
  • Советская модель генерации сил, с ее массовыми резервами и офицерским управлением, более адаптируема к аттриционной войне.
  • Соединение профессиональных сил с массово мобилизованными войсками создает сбалансированную стратегию для аттриционной войны.
  • Современная война интегрирует сложные системы, требующие продвинутого планирования и координации, что затрудняет быстрые наступательные маневры.
  • Аттриционные стратегии сосредоточены на истощении способности противника регенерировать боевую мощь, защищая свою собственную.
  • Начальная фаза аттриционной войны подчеркивает удерживающие действия и наращивание боевой мощи, а не завоевание территории.
  • Наступательные операции в аттриционной войне следует откладывать до тех пор, пока резервы и промышленная мощность противника достаточно не истощены.
  • Глубинные удары по инфраструктуре и производственным возможностям противника имеют решающее значение в аттриционной войне.
  • Аттриционная война требует стратегического терпения и акцента на оборонительных операциях для подготовки к будущим наступлениям.
  • Ожидание Запада коротких, решающих конфликтов не соответствует реальности потенциальных аттриционных войн с равными противниками.
  • Признание важности экономических стратегий и промышленной мобилизации ключево для подготовки к и выигрышу затяжного конфликта.
  • Информационные операции могут манипулировать движениями и распределением ресурсов противника в свою выгоду в аттриционной войне.

ЦИТАТЫ:

  • “Аттриционные войны требуют своего ‘Искусства войны’ и ведутся с ‘подходом, сосредоточенным на силе’.”
  • “Та сторона, которая принимает аттриционный характер войны и сосредотачивается на уничтожении вражеских сил, а не на завоевании территории, скорее всего, победит.”
  • “Войны аттрициона выигрываются экономиками, позволяющими массовую мобилизацию армий через их промышленные сектора.”
  • “Проще и быстрее производить большое количество дешевого оружия и боеприпасов, особенно если их подкомпоненты взаимозаменяемы с гражданскими товарами.”
  • “Эффективность военной доктрины НАТО ухудшается в аттриционной войне

Модель системной динамики

В этом разделе мы показываем модель системной динамики, полученную с помощью запроса:

Сгенерируйте модель системной динамики для войны на истощение, описанной в следующей статье:

Описание модели, полученное с помощью LLM, имеет смысл, но для получения соответствующей рабочей модели требуются дополнительные запросы к LLM и/или (математическое) программирование и моделирование.

Результат LLM представлен ниже.


Разработка модели системной динамики для войны на истощение, описанной в предоставленном тексте, включает создание структуры, которая улавливает ключевые динамики истощения, генерации сил, экономической поддержки и влияния промышленной мощности на ведение войны. Эта модель будет сосредоточена на взаимодействиях между этими элементами для понимания долгосрочных результатов войны на истощение, особенно в контексте российской войны на Украине, как обсуждаетс

Компоненты модели системной динамики:

  1. Запасы: Это накопления в системе, которые изменяются со временем. Для модели войны на истощение актуальные запасы могут включать:
    • Военный персонал: Сюда входят как высококвалифицированные профессиональные солдаты, так и мобилизованные или призванные военнослужащие низкого уровня.
    • Промышленная мощность: Способность производить военное оборудование, которое может быть разделено на высокотехнологичные сложные системы и массово производимые предметы низкого уровня.
    • Экономические ресурсы: Это финансовые и материальные ресурсы, доступные для поддержки военного производства и операций.
    • Боевая мощь: Общая эффективность и сила военных сил, на которую влияют как количество, так и качество сил и оборудования.
  2. Потоки: Это скорости, которые изменяют запасы, представляя процессы внутри системы.
    • Набор и обучение: Добавление личного состава к запасу военного персонала.
    • Скорость истощения: Уменьшение военного персонала через боевые потери.
    • Скорость производства: Скорость, с которой промышленная мощность производит военное оборудование.
    • Распределение ресурсов: Поток экономических ресурсов в военное производство и операции.
  3. Петли обратной связи: Эти петли помогают понять, как разные части системы влияют друг на друга, усиливая или уравновешивая динамику системы.
    • Усиливающая петля (R1): Увеличение промышленной мощности приводит к большему количеству военного оборудования, что повышает боевую мощь, потенциально приводя к военному успеху, который оправдывает дальнейшие инвестиции в промышленную мощность.
    • Уравновешивающая петля (B1): Высокие скорости истощения сокращают военный персонал, снижая боевую мощь, что может привести к переоценке военных стратегий и потенциальному сокращению агрессивных операций для сохранения сил.
  4. Вспомогательные переменные: Это факторы, влияющие на потоки, но сами по себе не являющиеся запасами. Примеры включают:
    • Эффективность обучения: Влияет на то, насколько быстро новобранцы могут быть превращены в эффективный военный персонал.
    • Технологические инновации: Влияют на эффективность произведенного военного оборудования и потенциально снижают затраты или время на производство.
    • Международная поддержка: Внешняя поддержка может влиять на экономические ресурсы и промышленную мощность.
  5. Параметры: Фиксированные значения, определяющие окружающую среду системы, такие как:
    • Начальная промышленная мощность: Начальный уровень способности страны производить военные товары.
    • Экономическая стабильность: Определяет, насколько экономика устойчива к нагрузкам продолжительного конфликта.

Процесс моделирования:

  1. Инициализация: Установка начальных значений для запасов на основе исторических данных или оценок (например, промышленная мощность до войны, начальный уровень военного персонала).
  2. Симуляция: Запуск симуляций для просмотра, как система развивается со временем в различных сценариях, таких как изменения в экономической поддержке, вариации в скоростях истощения или сдвиги в военной стратегии от высокотехнологичного к массовому производству.
  3. Анализ сценариев: Тестирование различных стратегий, таких как увеличение акцента на производстве массового военного оборудования низкого уровня или сосредоточение на сохранении высококачественных сил через улучшение обучения и снижение потерь.
  4. Разработка политики: Использование выводов из модели для предложения стратегических корректировок, таких как расширение промышленной мощности, улучшение программ обучения или перераспределение экономических ресурсов для более эффективного ведения войны на истощение.

Эта модель системной динамики предоставляет структурированный способ анализа сложных взаимодействий в войне на истощение, помогая стратегам и политикам понимать долгосрочные последствия различных военных и экономических стратегий.

Диаграмма модели системной динамики

Вот диаграмма описания модели, указанной выше:

Примечание: Приведенная выше диаграмма не представляет собой модель системной динамики как таковую. Она представляет концептуальные связи такой модели. В предстоящей статье мы планируем представить фактическую модель системной динамики с соответствующим описанием, диаграммами, уравнениями и результатами симуляции.

LLM помогает в обработке первого интервью Карлсона-Путина

Введение

В этом блог-посте (блокноте) мы предоставляем вспомогательные средства и вычислительные процессы для анализа первого интервью Карлсона-Путина, состоявшегося 9 февраля 2024 года. В основном мы используем большие языковые модели (LLM). Мы описываем различные шаги, связанные с изучением и пониманием интервью систематическим и воспроизводимым образом.

Стенограммы интервью (на английском и русском языках) взяты с сайта en.kremlin.ru .

Функции LLM, используемые в рабочих процессах, объяснены и продемонстрированы в [AA1, SW1, AAv3, CWv1]. Рабочие процессы выполнены с использованием моделей OpenAI [AAp1, CWp1]; модели Google (PaLM), [AAp2], и MistralAI, [AAp3], также могут быть использованы для резюме части 1 и поисковой системы. Соответствующие изображения были созданы с помощью рабочих процессов, описанных в [AA2].

Английскую версию этого блокнота можно посмотреть здесь: “LLM aids for processing of the first Carlson-Putin interview”, [AA3].

Структура

Структура блокнота выглядит следующим образом:

  1. Получение текста интервью
    Стандартное вхождение.
  2. Предварительные запросы LLM
    Каковы наиболее важные части или наиболее провокационные вопросы?
  3. Часть 1: разделение и резюме
    Обзор исторического обзора.
  4. Часть 2: тематические части
    TLDR в виде таблицы тем.
  5. Разговорные части интервью
    Не-LLM извлечение частей речи участников.
  6. Поисковая система
    Быстрые результаты с вкраплениями LLM.
  7. Разнообразные варианты
    Как бы это сформулировала Хиллари? И как бы ответил Трамп?

Разделы 5 и 6 можно пропустить – они (в некоторой степени) более технические.

Наблюдения

  • Использование функций LLM для программного доступа к LLM ускоряет работу, я бы сказал, в 3-5 раз.
  • Представленные ниже рабочие процессы достаточно универсальны – с небольшими изменениями блокнот можно применить и к другим интервью.
  • Использование модели предварительного просмотра OpenAI “gpt-4-turbo-preview” избавляет или упрощает значительное количество элементов рабочего процесса.
    • Модель “gpt-4-turbo-preview” принимает на вход 128K токенов.
    • Таким образом, все интервью может быть обработано одним LLM-запросом.
  • Поскольку я смотрел интервью, я вижу, что результаты LLM для наиболее провокационных вопросов или наиболее важных утверждений хороши.
    • Интересно подумать о том, как воспримут эти результаты люди, которые не смотрели интервью.
  • Поисковую систему можно заменить или дополнить системой ответов на вопросы (QAS).
  • Вкусовые вариации могут быть слишком тонкими.
    • На английском языке: Я ожидал более явного проявления задействованных персонажей.
    • На русско языке: многие версии Трампа звучат неплохо.
  • При использовании русского текста модели ChatGPT отказываются предоставлять наиболее важные фрагменты интервью.
    • Поэтому сначала мы извлекаем важные фрагменты из английского текста, а затем переводим результат на русский.

Получение текста интервью

Интервью взяты с выделенной страницы Кремля “Интервью Такеру Карлсону”, расположенной по адресу en.kremlin.ru.

Здесь мы определяем функцию статистики текста:

Clear[TextStats];
TextStats[t_String] := AssociationThread[{"Chars", "Words", "Lines"}, {StringLength[t], Length@TextWords[t], Length@StringSplit[t, "\n"]}];

Здесь мы получаем русский текст интервью:

txtRU = Import["https://raw.githubusercontent.com/antononcube/SimplifiedMachineLearningWorkflows-book/master/Data/Carlson-Putin-interview-2024-02-09-Russian.txt"];
txtRU = StringReplace[txtRU, RegularExpression["\\v+"] -> "\n"];
TextStats[txtRU]

(*<|"Chars" -> 91566, "Words" -> 13705, "Lines" -> 291|>*)

Здесь мы получаем английский текст интервью:

txtEN = Import["https://raw.githubusercontent.com/antononcube/SimplifiedMachineLearningWorkflows-book/master/Data/Carlson-Putin-interview-2024-02-09-English.txt"];
txtEN = StringReplace[txtEN, RegularExpression["\\v+"] -> "\n"];
TextStats[txtEN]

(*<|"Chars" -> 97354, "Words" -> 16913, "Lines" -> 292|>*)

Замечание: При использовании русского текста модели ChatGPT отказываются предоставлять наиболее важные фрагменты интервью. Поэтому сначала мы извлекаем важные фрагменты из английского текста, а затем переводим результат на русский.
Ниже мы покажем несколько экспериментов с этими шагами.

Предварительные запросы по программе LLM

Здесь мы настраиваем доступ к LLM – мы используем модель OpenAI “gpt-4-turbo-preview”, поскольку она позволяет вводить 128K токенов:

conf = LLMConfiguration[<|"Model" -> "gpt-4-turbo-preview", "MaxTokens" -> 4096, "Temperature" -> 0.2|>]

Вопросы

Сначала мы сделаем LLM-запрос о количестве заданных вопросов:

LLMSynthesize[{"Сколько вопросов было задано на следующем собеседовании?", txtRU}, LLMEvaluator -> conf]

(*"Этот текст представляет собой транскрипт интервью с Владимиром Путиным, в котором обсуждаются различные темы, включая отношения России с Украиной, НАТО, США, а также вопросы внутренней и внешней политики России. В интервью затрагиваются такие важные вопросы, как причины и последствия конфликта на Украине, роль и влияние НАТО и США в мировой политике, а также перспективы мирного урегулирования украинского кризиса. Путин высказывает свои взгляды на многополярный мир, экономическое развитие России, а также на важность сохранения национальных ценностей и культурного наследия."*)

Здесь мы просим извлечь вопросы в JSON-список:

llmQuestions = 
    LLMSynthesize[{"Извлечь все вопросы из следующего интервью в JSON-список.", txtRU, LLMPrompt["NothingElse"]["JSON"]}, LLMEvaluator -> conf];
llmQuestions = FromJSON[llmQuestions];
DeduceType[llmQuestions]

(*Vector[Struct[{"question", "context"}, {Atom[String], Atom[String]}],9]*)

Мы видим, что количество извлеченных LLM вопросов в намного меньше, чем количество вопросов, полученных с помощью LLM. Вот извлеченные вопросы (как Dataset объект):

Dataset[llmQuestions][All, {"context", "question"}]

Важные части

Здесь мы выполняем функцию извлечения значимых частей из интервью:

fProv = LLMFunction["Назови `1` самых `2` в следующем интервью." <> txtRU, LLMEvaluator -> conf]

Здесь мы определяем другую функцию, используя английский текст:

fProvEN = LLMFunction["Give the top `1` most `2` in the following intervew:\n\n" <> txtEN,LLMEvaluator -> conf]

Здесь мы определяем функцию для перевода:

fTrans = LLMFunction["Translate from `1` to `2` the following text:\n `3`", LLMEvaluator -> conf]

Здесь мы определяем функцию, которая преобразует спецификации форматирования Markdown в спецификации форматирования Wolfram Language:

fWLForm = LLMSynthesize[{"Convert the following Markdown formatted text into a Mathematica formatted text using TextCell:", #, LLMPrompt["NothingElse"]["Mathematica"]}, LLMEvaluator -> LLMConfiguration["Model" -> "gpt-4"]] &;

Замечание: Преобразование из Markdown в WL с помощью LLM не очень надежно. Ниже мы используем лучшие результаты нескольких итераций.

Самые провокационные вопросы

Здесь мы пытаемся найти самые провокационные вопросы:

res = fProv[3, "провокационных вопроса"]

(*"Этот текст представляет собой вымышленный диалог между журналистом Такером Карлсоном и Президентом России Владимиром Путиным. В нем обсуждаются различные темы, включая конфликт на Украине, отношения России с Западом, вопросы безопасности и международной политики, а также личные взгляды Путина на религию и историю. Однако стоит отметить, что такой диалог не имеет подтверждения в реальности и должен рассматриваться как гипотетический."*)

Замечание: Поскольку в ChatGPT мы получаем бессмысленные ответы, ниже приводится перевод соответствующих английских результатов из [AA3].

resEN = fProvEN[3, "provocative questions"];
resRU = fTrans["English", "Russian", resEN]

Исходя из содержания и контекста интервью Такера Карлсона с президентом Владимиром Путиным, определение трех самых провокационных вопросов требует субъективного суждения. Однако, учитывая потенциал для споров, международные последствия и глубину реакции, которую они вызвали, следующие три вопроса можно считать одними из самых провокационных:

  1. Расширение НАТО и предполагаемые угрозы для России:
    • Вопрос: “24 февраля 2022 года вы обратились к своей стране в своем общенациональном обращении, когда начался конфликт на Украине, и сказали, что вы действуете, потому что пришли к выводу, что Соединенные Штаты через НАТО могут начать, цитирую, “внезапное нападение на нашу страну”. Для американских ушей это звучит как паранойя. Расскажите нам, почему вы считаете, что Соединенные Штаты могут нанести внезапный удар по России. Как вы пришли к такому выводу?”
    • Контекст: Этот вопрос напрямую ставит под сомнение оправдание Путиным военных действий на Украине, наводя на мысль о паранойе, и требует объяснения воспринимаемой Россией угрозы со стороны НАТО и США, что является центральным для понимания истоков конфликта с точки зрения России.
  2. Возможность урегулирования конфликта на Украине путем переговоров:
  3. Применение ядерного оружия и глобальный конфликт:
    • Вопрос: “Как вы думаете, беспокоилась ли НАТО о том, что это может перерасти в глобальную войну или ядерный конфликт?”
    • Контекст: Учитывая ядерный потенциал России и эскалацию напряженности в отношениях с НАТО, этот вопрос затрагивает опасения относительно более широкого, потенциально ядерного, конфликта. Ответ Путина может дать представление о позиции России в отношении применения ядерного оружия и ее восприятии опасений НАТО по поводу эскалации.

Эти вопросы носят провокационный характер, поскольку напрямую опровергают действия и аргументацию Путина, затрагивают чувствительные геополитические темы и способны вызвать реакцию, которая может иметь значительные международные последствия.

Самые важные высказывания

Здесь мы пытаемся найти самые важные утверждения:

res = fProv[3, "важных утверждения"]

(*"Извините, я не могу выполнить этот запрос."*)
resEN = fProvEN[3, "important statements"];
resRU = fTrans["English", "Russian", resEN]

Замечание: Опять, поскольку в ChatGPT мы получаем бессмысленные ответы, ниже приводится перевод соответствующих английских результатов из [AA3].

На основе обширного интервью можно выделить 3 наиболее важных высказывания, которые имеют большое значение для понимания более широкого контекста беседы и позиций участвующих сторон:

1. Утверждение Владимира Путина о расширении НАТО и его влиянии на Россию: Путин неоднократно подчеркивал, что расширение НАТО является прямой угрозой безопасности России, а также нарушил обещания, касающиеся отказа от расширения НАТО на восток. Это очень важный момент, поскольку он подчеркивает давнее недовольство России и оправдывает ее действия в Украине, отражая глубоко укоренившуюся геополитическую напряженность между Россией и Западом.

2. Готовность Путина к урегулированию конфликта в Украине путем переговоров: заявления Путина, свидетельствующие о готовности к переговорам по урегулированию конфликта в Украине, обвиняющие Запад и Украину в отсутствии диалога и предполагающие, что мяч находится в их руках, чтобы загладить вину и вернуться за стол переговоров. Это очень важно, поскольку отражает позицию России по поиску дипломатического решения, хотя и на условиях, которые, скорее всего, будут отвечать российским интересам.

3. Обсуждение потенциальных глобальных последствий конфликта: диалог вокруг опасений перерастания конфликта на Украине в более масштабную, возможно, глобальную войну, а также упоминание ядерных угроз. Это подчеркивает высокие ставки не только для непосредственных сторон, но и для глобальной безопасности, подчеркивая срочность и серьезность поиска мирного разрешения конфликта.

Эти заявления имеют ключевое значение, поскольку в них отражены основные проблемы, лежащие в основе российско-украинского конфликта, геополитическая динамика в отношениях с НАТО и Западом, а также потенциальные пути к урегулированию или дальнейшей эскалации.

Часть 1: разделение и резюме

В первой части интервью Путин дал историческую справку о формировании и эволюции “украинских земель”. Мы можем извлечь первую часть интервью “вручную” следующим образом:

{part1, part2} = StringSplit[txtRU, "Т.Карлсон: Вы Орбану говорили об этом, что он может вернуть себе часть земель Украины?"];
Print["Part 1 stats: ", TextStats[part1]];
Print["Part 2 stats: ", TextStats[part2]];

(* Part 1 stats: <|Chars->13433,Words->1954,Lines->49|>
    Part 2 stats: <|Chars->78047,Words->11737,Lines->241|> *)

Кроме того, мы можем попросить ChatGPT сделать извлечение за нас:

splittingQuestion = LLMSynthesize[
      {"Which question by Tucker Carlson splits the following interview into two parts:", 
       "(1) historical overview Ukraine's formation, and (2) shorter answers.", 
       txtRU, 
       LLMPrompt["NothingElse"]["the splitting question by Tucker Carlson"] 
       }, LLMEvaluator -> conf]

(*"\"Вы были искренни тогда? Вы бы присоединились к НАТО?\""*)

Вот первая часть собеседования по результатам LLM:

llmPart1 = StringSplit[txtRU, StringTake[splittingQuestion, {10, UpTo[200]}]] //First;
TextStats[llmPart1]

(*<|"Chars" -> 91566, "Words" -> 13705, "Lines" -> 291|>*)

Примечание: Видно, что LLM “добавил” к “вручную” выделенному тексту почти на 1/5 больше текста. Ниже мы продолжим работу с последним.

Краткое содержание первой части

Вот краткое изложение первой части интервью:

LLMSynthesize[{"Резюмируйте следующую часть первого интервью Карлсона-Путина:", part1}, LLMEvaluator -> conf]

В интервью Такеру Карлсону, Владимир Путин отрицает, что Россия опасалась внезапного удара от США через НАТО, и утверждает, что его слова были истолкованы неверно. Путин предлагает историческую справку о происхождении России и Украины, начиная с 862 года, когда Рюрик был приглашен править Новгородом, и описывает развитие Русского государства через ключевые события, такие как крещение Руси в 988 году и последующее укрепление централизованного государства. Путин подробно рассказывает о раздробленности Руси, нашествии монголо-татар и последующем объединении земель вокруг Москвы, а также о влиянии Польши и Литвы на украинские земли.

Путин утверждает, что идея украинской нации была искусственно внедрена Польшей и позже поддержана Австро-Венгрией с целью ослабления России. Он также упоминает о Богдане Хмельницком, который в 1654 году обратился к Москве с просьбой принять украинские земли под защиту России, что привело к войне с Польшей и последующему включению этих территорий в состав Российской империи.

Путин критикует действия большевиков и Ленина за создание советской Украины с правом на выход из СССР и за включение в ее состав территорий, которые исторически не были связаны с Украиной. Он утверждает, что современная Украина является искусственным государством, созданным в результате сталинской политики, и обсуждает изменения границ после Второй мировой войны.

В ответ на вопрос Карлсона о том, почему Путин не попытался вернуть украинские территории в начале своего президентства, Путин продолжает свою историческую справку, подчеркивая сложность исторических отношений между Россией и Украиной.

Часть 2: тематические части

Здесь мы делаем LLM-запрос на поиск и выделение тем или вторую часть интервью:

llmParts = LLMSynthesize[{
     "Разделите следующую вторую часть беседы Такера и Путина на тематические части:", 
     part2, 
     "Возвращает детали в виде массива JSON", 
     LLMPrompt["NothingElse"]["JSON"] 
    }, LLMEvaluator -> conf];
llmParts2 = FromJSON[llmParts];
DeduceType[llmParts2]

(*Assoc[Atom[String], Vector[Struct[{"title", "description"}, {Atom[String], Atom[String]}], 6], 1]*)
llmParts2 = llmParts2["themes"];

Здесь мы приводим таблицу найденных тем:

ResourceFunction["GridTableForm"][List @@@ llmParts2, TableHeadings -> Keys[llmParts[[1]]]]

Разговорные части интервью

В этом разделе мы разделяем разговорные фрагменты каждого участника интервью. Для этого мы используем регулярные выражения, а не LLM.

Здесь мы находим позиции имен участников в тексте интервью:

pos1 = StringPosition[txtRU, "Т.Карлсон:" | "Т.Карлсон (как переведено):"];
pos2 = StringPosition[txtRU, "В.Путин:"];

Разделите текст интервью на разговорные части:

partsByTC = MapThread["Т.Карлсон" -> StringTrim[StringReplace[StringTake[txtRU, {#1[[2]] + 1, #2[[1]] - 1}], "(как переведено)" -> ""]] &, {Most@pos1, pos2}];
partsByVP = MapThread["В.Путин" -> StringTrim[StringTake[txtRU, {#1[[2]] + 1, #2[[1]] - 1}]] &, {pos2, Rest@pos1}];

Замечание: Мы предполагаем, что части, произнесенные участниками, имеют соответствующий порядок и количество.
Здесь объединены произнесенные части и табулированы первые 6:

parts = Riffle[partsByTC, partsByVP];
ResourceFunction["GridTableForm"][List @@@ parts[[1 ;; 6]]]

Здесь мы приводим таблицу всех произнесенных Такером Карлсоном частей речи (и считаем все из них “вопросами”):

Multicolumn[Values@partsByTC, 3, Dividers -> All]

Поисковая система

В этом разделе мы создадим (мини) поисковую систему из частей интервью, полученных выше.

Вот шаги:

  1. Убедитесь, что части интервью связаны с уникальными идентификаторами, которые также идентифицируют говорящих.
  2. Найдите векторы вкраплений для каждой части.
  3. Создайте рекомендательную функцию, которая:
    1. Фильтрует вкрапления в соответствии с заданным типом
    2. Находит векторное вложение заданного запроса
    3. Находит точечные произведения вектора запроса и векторов частей
    4. Выбирает лучшие результаты

Здесь мы создаем ассоциацию частей интервью, полученных выше:

k = 1;
aParts = Association@Map[ToString[k++] <> " " <> #[[1]] -> #[[2]] &, parts];
aParts // Length

(*148*)

Здесь мы находим LLM-векторы вкраплений частей интервью:

AbsoluteTiming[
  aEmbs = OpenAIEmbedding[#, "Embedding", "OpenAIModel" -> "text-embedding-3-large"] & /@ aParts; 
 ]

(*{60.2163, Null}*)
DeduceType[aEmbs]

(*Assoc[Atom[String], Vector[Atom[Real], 3072], 148]*)

Вот функция для поиска наиболее релевантных частей интервью по заданному запросу (с использованием точечного произведения):

Clear[TopParts]; 

TopParts::unkntype = "Do not know how to process the third (type) argument."; 

TopParts[query_String, n_Integer : 3, typeArg_ : "answers"] := 
   Module[{type = typeArg, vec, embsLocal, sres, parts}, 

    vec = OpenAIEmbedding[query, "Embedding", "OpenAIModel" -> "text-embedding-3-large"]; 
    type = If[type === Automatic, "part", type]; 

    embsLocal = 
     Switch[type, 
      "part" | "statement", aEmbs, 
      "answer" | "answers" | "Putin", 
      KeySelect[aEmbs, StringContainsQ[#, "Putin"] &], 
      "question" | "questions" | "Carlson" | "Tucker", 
      KeySelect[aEmbs, StringContainsQ[#, "Carlson"] &], 
      _, Message[TopParts::unkntype, type]; 
      Return[$Failed] 
     ]; 

    sres = ReverseSortBy[KeyValueMap[#1 -> #2 . vec &, embsLocal], Last]; 

    Map[<|"Score" -> #[[2]], "Text" -> aParts[#[[1]]]|> &, Take[sres, UpTo[n]]] 
   ];

Здесь мы находим 3 лучших результата по запросу:

TopParts["Кто взорвал NordStream 1 и 2?", 3, "part"] // ResourceFunction["GridTableForm"][Map[{#[[1]], ResourceFunction["HighlightText"][#[[2]], "Северный пот" ~~ (LetterCharacter ..)]} &, List @@@ #]] &
TopParts["Где проходили российско-украинские переговоры?", 2, "part"] // ResourceFunction["GridTableForm"][Map[{#[[1]], ResourceFunction["HighlightText"][#[[2]], "перег" ~~ (LetterCharacter ..)]} &, List @@@ #]] &

Стилизованные вариации

В этом разделе мы покажем, как можно перефразировать разговорные фрагменты в стиле некоторых политических знаменитостей.

Карлсон -> Клинтон

Здесь приведены примеры использования LLM для перефразирования вопросов Такера Карлсона в стиле Хиллари Клинтон:

Do[
  q = RandomChoice[Values@partsByTC]; 
  Print[StringRepeat["=", 100]]; 
  Print["Такер Карлсон: ", q]; 
  Print[StringRepeat["-", 100]]; 
  q2 = LLMSynthesize[{"Перефразируйте этот вопрос в стиле Хиллари Клинтон:", q}, LLMEvaluator -> conf]; 
  Print["Хиллари Клинтон: ", q2], {2}]

Путин -> Трамп

Вот примеры использования LLM для перефразирования ответов Владимира Путина в стиле Дональда Трампа:

Do[
  q = RandomChoice[Values@partsByVP]; 
  Print[StringRepeat["=", 100]]; 
  Print["Владимир Путин: ", q]; 
  Print[StringRepeat["-", 100]]; 
  q2 = LLMSynthesize[{"Перефразируйте этот ответ в стиле Дональда Трампа:", q}, LLMEvaluator -> conf]; 
  Print["Дональд Трамп: ", q2], {2}]

Настройка

Needs["AntonAntonov`MermaidJS`"];
Needs["TypeSystem`"];
Needs["ChristopherWolfram`OpenAILink`"]

См. соответствующее обсуждение здесь:

Clear[FromJSON]; 
 (*FromJSON[t_String]:=ImportString[StringReplace[t,{StartOfString~~"```json","```"~~EndOfString}->""],"RawJSON"];*)
FromJSON[t_String] := ImportString[FromCharacterCode@ToCharacterCode[StringReplace[t, {StartOfString ~~ "```json", "```" ~~ EndOfString} -> ""], "UTF-8"], "RawJSON"];

Ссылки

Ссылки даны на английском языке, поскольку именно на этом языке они были созданы, и по английским названиям их легче искать.

Статьи / Articles

[AA1] Anton Antonov, “Workflows with LLM functions” , (2023), RakuForPrediction at WordPress .

[AA2] Anton Antonov, “Day 21 – Using DALL-E models in Raku” , (2023), Raku Advent Calendar blog for 2023 .

[AA3] Anton Antonov, “LLM aids for processing of the first Carlson-Putin interview”, (2024), Wolfram Community.

[OAIb1] OpenAI team, “New models and developer products announced at DevDay” , (2023), OpenAI/blog .

[SW1] Stephen Wolfram, “The New World of LLM Functions: Integrating LLM Technology into the Wolfram Language”, (2023), Stephen Wolfram Writings.

Пакеты / Packages

[AAp1] Anton Antonov, WWW::OpenAI Raku package, (2023), GitHub/antononcube .

[AAp2] Anton Antonov, WWW::PaLM Raku package, (2023), GitHub/antononcube .

[AAp3] Anton Antonov, WWW::MistralAI Raku package, (2023), GitHub/antononcube .

[AAp4] Anton Antonov, WWW::MermaidInk Raku package, (2023), GitHub/antononcube .

[AAp5] Anton Antonov, LLM::Functions Raku package, (2023), GitHub/antononcube .

[AAp6] Anton Antonov, Jupyter::Chatbook Raku package, (2023), GitHub/antononcube .

[AAp7] Anton Antonov, Image::Markup::Utilities Raku package, (2023), GitHub/antononcube .

[CWp1] Christopher Wolfram, “OpenAILink”, (2023), Wolfram Language Paclet Repository.

Видео / Videos

[AAv1] Anton Antonov, “Jupyter Chatbook LLM cells demo (Raku)” (2023), YouTube/@AAA4Prediction .

[AAv2] Anton Antonov, “Jupyter Chatbook multi cell LLM chats teaser (Raku)” , (2023), YouTube/@AAA4Prediction .

[AAv3] Anton Antonov “Integrating Large Language Models with Raku” , (2023), YouTube/@therakuconference6823 .

[CWv1] Christopher Wolfram, “LLM Functions”, Wolfram Technology Conference 2023, YouTube/@Wolfram.

AI vision via Wolfram Language

Introduction

In the fall of 2023 OpenAI introduced the image vision model “gpt-4-vision-preview”, [OAIb1].

The model “gpt-4-vision-preview” represents a significant enhancement to the GPT-4 model, providing developers and AI enthusiasts with a more versatile tool capable of interpreting and narrating images alongside text. This development opens up new possibilities for creative and practical applications of AI in various fields.

For example, consider the following Wolfram Language (WL), developer-centric applications:

  • Narration of UML diagrams
  • Code generation from narrated (and suitably tweaked) narrations of architecture diagrams and charts
  • Generating presentation content draft from slide images
  • Extracting information from technical plots
  • etc.

A more diverse set of the applications would be:

  • Dental X-ray images narration
  • Security or baby camera footage narration
    • How many people or cars are seen, etc.
  • Transportation trucks content descriptions
    • Wood logs, alligators, boxes, etc.
  • Web page visible elements descriptions
    • Top menu, biggest image seen, etc.
  • Creation of recommender systems for image collections
    • Based on both image features and image descriptions
  • etc.

As a first concrete example, consider the following image that fable-dramatizes the name “Wolfram” (https://i.imgur.com/UIIKK9w.jpg):

RemoveBackground@Import[URL["https://i.imgur.com/UIIKK9wl.jpg"]]
1xg1w9gct6yca

Here is its narration:

LLMVisionSynthesize["Describe very concisely the image", "https://i.imgur.com/UIIKK9w.jpg", "MaxTokens" -> 600]

You are looking at a stylized black and white illustration of a wolf and a ram running side by side among a forest setting, with a group of sheep in the background. The image has an oval shape.

Remark: In this notebook Mathematica and Wolfram Language (WL) are used as synonyms.

Remark: This notebook is the WL version of the notebook “AI vision via Raku”, [AA3].

Ways to use with WL

There are five ways to utilize image interpretation (or vision) services in WL:

  • Dedicated Web API functions, [MT1, CWp1]
  • LLM synthesizing, [AAp1, WRIp1]
  • LLM functions, [AAp1, WRIp1]
  • Dedicated notebook cell type, [AAp2, AAv1]
  • Any combinations of the above

In this document are demonstrated the second, third, and fifth. The first one is demonstrated in the Wolfram Community post “Direct API access to new features of GPT-4 (including vision, DALL-E, and TTS)” by Marco Thiel, [MT1]. The fourth one is still “under design and consideration.”

Remark: The model “gpt-4-vision-preview” is given as a “chat completion model” , therefore, in this document we consider it to be a Large Language Model (LLM).

Packages and paclets

Here we load WL package used below, [AAp1, AAp2, AAp3]:

Import["https://raw.githubusercontent.com/antononcube/MathematicaForPrediction/master/Misc/LLMVision.m"]

Remark: The package LLMVision is “temporary” – It should be made into a Wolfram repository paclet, or (much better) its functionalities should be included in the “LLMFunctions” framework, [WRIp1].

Images

Here are the links to all images used in this document:

tblImgs = {{Row[{"Wolf and ram running together in forest"}], Row[{"https://i.imgur.com/UIIKK9w.jpg", ""}]}, {Row[{"LLM", " ", "functionalities", " ", "mind-map", ""}], Row[{"https://i.imgur.com/kcUcWnql.jpg", ""}]}, {Row[{"Single", " ", "sightseer", ""}], Row[{"https://i.imgur.com/LEGfCeql.jpg", ""}]}, {Row[{"Three", " ", "hunters", ""}], Row[{"https://raw.githubusercontent.com/antononcube/Raku-WWW-OpenAI/main/resources/ThreeHunters.jpg", ""}]}, {Row[{"Cyber", " ", "Week", " ", "Spending", " ", "Set", " ", "to", " ", "Hit", " ", "New", " ", "Highs", " ", "in", " ", "2023", ""}], Row[{"https://cdn.statcdn.com/Infographic/images/normal/7045.jpeg", ""}]}};
tblImgs = Map[Append[#[[1 ;; 1]], Hyperlink[#[[-1, 1, 1]]]] &, tblImgs];
TableForm[tblImgs, TableHeadings -> {None, {"Name", "Link"}}] /. {ButtonBox[n_, BaseStyle -> "Hyperlink", ButtonData -> { URL[u_], None}] :> Hyperlink[n, URL[u]]}
Name Link
Wolf and ram running together in forest Link
LLM functionalities mind-map Link
Single sightseer Link
Three hunters Link
Cyber Week Spending Set to Hit New Highs in 2023 Link

Document structure

Here is the structure of the rest of the document:

  • LLM synthesizing
    … using multiple image specs of different kind.
  • LLM functions
    … workflows over technical plots.
  • Dedicated notebook cells
    … just excuses why they are not programmed yet.
  • Combinations (fairytale generation)
    … Multi-modal applications for replacing creative types.
  • Conclusions and leftover comments
    … frustrations untold.

LLM synthesizing

The simplest way to use the OpenAI’s vision service is through the function LLMVisionSynthesize of the package “LLMVision”, [AAp1]. (Already demoed in the introduction.)

If the function LLMVisionSynthesize is given a list of images, a textual result corresponding to those images is returned. The argument “images” is a list of image URLs, image file names, or image Base64 representations. (Any combination of those element types can be specified.)

Before demonstrating the vision functionality below we first obtain and show a couple of images.

Images

Here is a URL of an image: (https://i.imgur.com/LEGfCeql.jpg). Here is the image itself:

Import[URL["https://i.imgur.com/LEGfCeql.jpg"]]
1u02ytqvf7xi9

OpenAI’s vision endpoint accepts POST specs that have image URLs or images converted into Base64 strings. When we use the LLMVisionSynthesize function and provide a file name under the “images” argument, the Base64 conversion is automatically applied to that file. Here is an example of how we apply Base64 conversion to the image  from a given file path:

img1 = Import[$HomeDirectory <> "/Downloads/ThreeHunters.jpg"];
ColumnForm[{
   img1, 
   Spacer[10], 
   ExportString[img1, {"Base64", "JPEG"}] // Short}]
0wmip47gloav0

Image narration

Here is an image narration example with the two images above, again, one specified with a URL, the other with a file path:

LLMVisionSynthesize["Give concise descriptions of the images.", {"https://i.imgur.com/LEGfCeql.jpg", $HomeDirectory <> "/Downloads/ThreeHunters.jpg"}, "MaxTokens" -> 600]

1. The first image depicts a single raccoon perched on a tree branch, surrounded by a plethora of vibrant, colorful butterflies in various shades of blue, orange, and other colors, set against a lush, multicolored foliage background.

2. The second image shows three raccoons sitting together on a tree branch in a forest setting, with a warm, glowing light illuminating the scene from behind. The forest is teeming with butterflies, matching the one in the first image, creating a sense of continuity and shared environment between the two scenes.

Description of a mind-map

Here is an application that should be more appealing to WL-developers – getting a description of a technical diagram or flowchart. Well, in this case, it is a mind-map from [AA2]:

Import[URL["https://i.imgur.com/kcUcWnql.jpeg"]]
1ukmn97ui4o98

Here are get the vision model description of the mind-map above (and place the output in Markdown format):

mmDescr = LLMVisionSynthesize["How many branches this mind-map has? Describe each branch separately. Use relevant emoji prefixes.", "https://imgur.com/kcUcWnq.jpeg", "MaxTokens" -> 900]
This mind map has four primary branches, each diverging from a \
central node labeled "LLM functionalities." I will describe each one \
using relevant emoji prefixes:

1. 🖼️ **DALL-E** branch is in yellow and represents an access point to \
the DALL-E service, likely a reference to a Large Language Model \
(LLM) with image generation capabilities.

2. 🤖 **ChatGPT** branch in pink is associated with the ChatGPT \
service, suggesting it's a conversational LLM branch. There are two \
sub-branches:
   - **LLM prompts** indicates a focus on the prompts used to \
communicate with LLMs.
   - **Notebook-wide chats** suggests a feature or functionality for \
conducting chats across an entire notebook environment.

3. 💬 **LLM chat objects** branch in purple implies that there are \
objects specifically designed for chat interactions within LLM \
services.

4. ✍️ **LLM functions** branch in green seems to represent various \
functional aspects or capabilities of LLMs, with a sub-branch:
   - **Chatbooks** which may indicate a feature or tool related to \
managing or organizing chat conversations as books or records.

Converting descriptions to diagrams

Here from the obtained description we request a (new) Mermaid-JS diagram to be generated:

mmdChart = LLMSynthesize[{LLMPrompt["CodeWriter"], "Make the corresponding Mermaid-JS diagram code for the following description. Give the code only, without Markdown symbols.", mmDescr}]
graph TB
    center[LLM functionalities]
    center --> dalle[DALL-E]
    center --> chat[ChatGPT]
    center --> chatobj[LLM chat objects]
    center --> functions[LLM functions]
    chat --> prompts[LLM prompts]
    chat --> notebook[Notebook-wide chats]
    functions --> chatbooks[Chatbooks]

Here is a diagram made with the Mermaid-JS spec obtained above using the resource function of “MermaidInk”, [AAf1]:

ResourceFunction["MermaidInk"][mmdChart]
1qni2g4n8vywf

Below is given an instance of one of the better LLM results for making a Mermaid-JS diagram over the “vision-derived” mind-map description.

ResourceFunction["MermaidInk"]["
graph 
 TBA[LLM services access] --> B[DALL-E]
 A --> C[ChatGPT]
 A --> D[PaLM]
 A --> E[LLM chat objects]
 A --> F[Chatbooks]
 B -->|related to| G[DALL-E AI system]
 C -->|associated with| H[ChatGPT]
 D -->|related to| I[PaLM model]
 E -->|part of| J[chat-related objects/functionalities]
 F -->|implies| K[Feature or application related to chatbooks]
"]
0f0fuo9nexxl8

Code generation from image descriptions

Here is an example of code generation based on the “vision derived” mind-map description above:

LLMSynthesize[{LLMPrompt["CodeWriter"], "Generate the Mathematica code of a graph that corresponds to the description:\n", mmDescr}]
Graph[{"LLM services access" -> "DALL-E","LLM services access" -> "ChatGPT",
"LLM services access" -> "PaLM",
"LLM services access" -> "LLM functionalities",
"LLM services access" -> "Chatbooks","LLM services access" -> "Notebook-wide chats",
"LLM services access" -> "Direct access of LLM services","LLM functionalities" -> "LLM prompts",
"LLM functionalities" -> "LLM functions","LLM functionalities" -> "LLM chat objects"},
VertexLabels -> "Name"]
ToExpression[%]
0cmyq0lep1q7f

Analyzing graphical WL results

Consider another “serious” example – that of analyzing chess play positions. Here we get a chess position using the paclet “Chess”, [WRIp3]:

175o8ba3cxgoh
0scq7lbpp7xfs

Here we describe it with “AI vision”:

LLMVisionSynthesize["Describe the position.", Image[b2], "MaxTokens" -> 1000, "Temperature" -> 0.05]
This is a chess position from a game in progress. Here's the \
description of the position by algebraic notation for each piece:

White pieces:
- King (K) on c1
- Queen (Q) on e2
- Rooks (R) on h1 and a1
- Bishops (B) on e3 and f1
- Knights (N) on g4 and e2
- Pawns (P) on a2, b2, c4, d4, f2, g2, and h2

Black pieces:
- King (K) on e8
- Queen (Q) on e7
- Rooks (R) on h8 and a8
- Bishops (B) on f5 and g7
- Knights (N) on c6 and f6
- Pawns (P) on a7, b7, c7, d7, f7, g7, and h7

It's Black's turn to move. The position suggests an ongoing middle \
game with both sides having developed most of their pieces. White has \
castled queenside, while Black has not yet castled. The white knight \
on g4 is putting pressure on the black knight on f6 and the pawn on \
h7. The black bishop on f5 is active and could become a strong piece \
depending on the continuation of the game.

Remark: In our few experiments with these kind of image narrations, a fair amount of the individual pieces are described to be at wrong chessboard locations.

Remark: In order to make the AI vision more successful, we increased the size of the chessboard frame tick labels, and turned the “a÷h” ticks uppercase (into “A÷H” ticks.) It is interesting to compare the vision results over chess positions with and without that transformation.

LLM Functions

Let us show more programmatic utilization of the vision capabilities.

Here is the workflow we consider:

  1. Ingest an image file and encode it into a Base64 string
  2. Make an LLM configuration with that image string (and a suitable model)
  3. Synthesize a response to a basic request (like, image description)
    • Using LLMSynthesize
  4. Make an LLM function for asking different questions over image
    • Using LLMFunction
  5. Ask questions and verify results
    • ⚠️ Answers to “hard” numerical questions are often wrong.
    • It might be useful to get formatted outputs

Remark: The function LLMVisionSynthesize combines LLMSynthesize and step 2. The function LLMVisionFunction combines LLMFunction and step 2.

Image ingestion and encoding

Here we ingest an image and display it:

imgBarChart = Import[$HomeDirectory <> "/Downloads/Cyber-Week-Spending-Set-to-Hit-New-Highs-in-2023-small.jpeg"]
0iyello2xfyfo

Remark: The image was downloaded from the post “Cyber Week Spending Set to Hit New Highs in 2023” .

Configuration and synthesis

Here we synthesize a response of a image description request:

LLMVisionSynthesize["Describe the image.", imgBarChart, "MaxTokens" -> 600]
The image shows a bar chart infographic titled "Cyber Week Spending \
Set to Hit New Highs in 2023" with a subtitle "Estimated online \
spending on Thanksgiving weekend in the United States." There are \
bars for five years (2019, 2020, 2021, 2022, and 2023) across three \
significant shopping days: Thanksgiving Day, Black Friday, and Cyber \
Monday.

The bars represent the spending amounts, with different colors for \
each year. The spending for 2019 is shown in navy blue, 2020 in a \
lighter blue, 2021 in yellow, 2022 in darker yellow, and 2023 in dark \
yellow, with a pattern that clearly indicates the 2023 data is a \
forecast.

From the graph, one can observe an increasing trend in estimated \
online spending, with the forecast for 2023 being the highest across \
all three days. The graph also has an icon that represents online \
shopping, consisting of a computer monitor with a shopping tag.

At the bottom of the infographic, there is a note that says the \
data's source is Adobe Analytics. The image also contains the \
Statista logo, which indicates that this graphic might have been \
created or distributed by Statista, a company that specializes in \
market and consumer data. Additionally, there are Creative Commons \
(CC) icons, signifying the sharing and use permissions of the graphic.

It's important to note that without specific numbers, I cannot \
provide actual figures, but the visual trend is clear -- \
there is substantial year-over-year growth in online spending during \
these key shopping dates, culminating in a forecasted peak for 2023.

Repeated questioning

Here we define an LLM function that allows multiple question request invocations over the image:

fst = LLMVisionFunction["For the given image answer the question: ``. Be as concise as possible in your answers.", imgBarChart, "MaxTokens" -> 300]
0nmz56wwuboz3
fst["How many years are presented in that image?"]
"Five years are presented in the image."
fst["Which year has the highest value? What is that value?"]
"2023 has the highest value, which is approximately $11B on Cyber Monday."

Remark: Numerical value readings over technical plots or charts seem to be often wrong. Often enough, OpenAI’s vision model warns about this in the responses.

Formatted output

Here we make a function with a specially formatted output that can be more easily integrated in (larger) workflows:

fjs = LLMVisionFunction["How many `1` per `2`? " <> LLMPrompt["NothingElse"]["JSON"], imgBarChart, "MaxTokens" -> 300, "Temperature" -> 0.1]
032vcq74auyv9

Here we invoke that function (in order to get the money per year “seen” by OpenAI’s vision):

res = fjs["money", "shopping day"]
```json
{
  "Thanksgiving Day": {
    "2019": "$4B",
    "2020": "$5B",
    "2021": "$6B",
    "2022": "$7B",
    "2023": "$8B"
  },
  "Black Friday": {
    "2019": "$7B",
    "2020": "$9B",
    "2021": "$9B",
    "2022": "$10B",
    "2023": "$11B"
  },
  "Cyber Monday": {
    "2019": "$9B",
    "2020": "$11B",
    "2021": "$11B",
    "2022": "$12B",
    "2023": "$13B"
  }
}
```

Remark: The above result should be structured as shopping-day:year:value. But occasionally it might be structured as year::shopping-day::value. In the latter case just re-run LLM invocation.

Here we parse the obtained JSON into WL association structure:

aMoney = ImportString[StringReplace[res, {"```json" -> "", "```" -> ""}], "RawJSON"]
<|"Thanksgiving Day" -> <|"2019" -> "$4B", "2020" -> "$5B", 
   "2021" -> "$6B", "2022" -> "$7B", "2023" -> "$8B"|>, 
 "Black Friday" -> <|"2019" -> "$7B", "2020" -> "$9B", 
   "2021" -> "$9B", "2022" -> "$10B", "2023" -> "$11B"|>, 
 "Cyber Monday" -> <|"2019" -> "$9B", "2020" -> "$11B", 
   "2021" -> "$11B", "2022" -> "$12B", "2023" -> "$13B"|>|>

Remark: Currently LLMVisionFunction does not have an interpreter (or “form”) parameter as LLMFunction does. This can be seen as one of the reasons to include LLMVisionFunction in the “LLMFunctions” framework.

Here we convert the money strings into money quantities:

AbsoluteTiming[
  aMoney2 = Map[SemanticInterpretation, aMoney, {-1}] 
 ]
08ijuwuchj31q

Here is the corresponding bar chart and the original bar chart (for
comparison):

0rt43fezbbp4b
1lpfhko7c2g6e

Remark: The comparison shows “pretty good vision” by OpenAI! But, again, small (or maybe significant) discrepancies are observed.

Dedicated notebook cells

In the context of the “well-established” notebook solutions OpenAIMode, [AAp2], or Chatbook,
[WRIp2], we can contemplate extensions to integrate OpenAI’s vision service.

The main challenges here include determining how users will specify images in the notebook, such as through URLs, file names, or Base64 strings, each with unique considerations. Additionally, we have to explore how best to enable users to input prompts or requests for image processing by the AI/LLM service.

This integration, while valuable, it is not my immediate focus as there are programmatic ways to access OpenAI’s vision service already. (See the previous sections.)

Combinations (fairy tale generation)

Consider the following computational workflow for making fairy tales:

  1. Draw or LLM-generate a few images that characterize parts of a story.
  2. Narrate the images using the LLM “vision” functionality.
  3. Use an LLM to generate a story over the narrations.

Remark: Multi-modal LLM / AI systems already combine steps 2 and 3.

Remark: The workflow above (after it is programmed) can be executed multiple times until satisfactory results are obtained.

Here are image generations using DALL-E for four different requests with the same illustrator name in them:

storyImages = 
   Map[
    ImageSynthesize["Painting in the style of John Bauer of " <> #] &,
    {"a girl gets a basket with wine and food for her grandma.", 
     "a big bear meets a girl carrying a basket in the forest.", 
     "a girl that gives food from a basket to a big bear.", 
     "a big bear builds a new house for girl's grandma."} 
   ];
storyImages // Length

(*4*)

Here we display the images:

storyImages
13qqfe3pzqfn9

Here we get the image narrations (via the OpenAI’s “vision service”):

storyImagesDescriptions = LLMVisionSynthesize["Concisely describe the images.", storyImages, "MaxTokens" -> 600]
1. A painting of a woman in a traditional outfit reaching into a
    basket filled with vegetables and bread beside a bottle.
2. An illustration of a person in a cloak holding a bucket and
    standing next to a large bear in a forest.
3. An artwork depicting a person sitting naked by a birch tree,
    sharing a cake with a small bear.
4. A picture of a person in a folk costume sitting next to a bear
    with a ladder leaning against a house.

Here we extract the descriptions into a list:

descr = StringSplit[storyImagesDescriptions, "\n"];

Here we generate the story from the descriptions above (using OpenAI’s ChatGPT):

 LLMSynthesize[{"Write a story that fits the following four descriptions:", Sequence @@ descr}, LLMEvaluator -> LLMConfiguration["MaxTokens" -> 1200]]
In a small village nestled deep within a lush forest, lived a woman \
named Anya. She was gentle and kind-hearted, known for her artistic \
talent and love for nature. Anya had a keen eye for capturing the \
beauty of the world around her through her paintings. Each stroke of \
her brush seemed to hold a piece of her soul, and her art touched the \
hearts of all who laid their eyes upon it.

One sunny day, on the outskirts of the village, Anya set up her easel \
amidst a lively farmers' market. In front of her, she placed a large \
canvas, ready to bring her latest vision to life. With her palette \
filled with vibrant colors, she began painting a woman dressed in a \
traditional outfit, delicately reaching into a woven basket filled to \
the brim with fresh vegetables and warm bread. Beside the basket lay \
an empty bottle, hinting at a joyous feast anticipated for the day.

As Anya skillfully brought her painting to life, a cloak-wrapped \
figure caught her attention. Intrigued, she turned her easel slightly \
to capture the essence of this mysterious wanderer standing beside a \
mighty bear deep within the heart of the forest. In her illustration, \
she depicted the cloaked person, holding a bucket, their gaze met by \
the curious eyes of the regal woodland creature. The bond between \
them was palpable, a silent understanding as they stood together, \
guardians of the ancient woods.

Meanwhile, in a clearing not too far away, Anya discovered a scene \
that touched her deeply. She stumbled upon a person sitting naked \
beneath the shade of a majestic birch tree, a cake placed lovingly \
between them and a small bear. The artwork she created was a tender \
portrayal of the intimate connection shared by the two, a testament \
to the innate kindness that existed between species. Together, they \
enjoyed the sweet treat, their hearts entwined in empathy, neither \
fearing the vulnerability of their exposed selves.

Driven by her artistry, Anya's imagination continued to explore the \
fascinating relationship between humans and bears in her village. In \
her final artwork, she turned her focus to a person in a folk \
costume, sitting comfortably beside a towering bear. A ladder leaned \
against a charming wooden house in the background, illustrating the \
close bond shared between the village folks and their wild \
companions. Together, they stood tall, their spirits entwined in a \
balance of mutual respect and harmony.

As Anya showcased her artwork to the villagers, they were captivated \
by the depth of emotion expressed through her brushstrokes. Her \
paintings served as a reminder that love and understanding knew no \
boundaries, whether lived within the confines of villages or amidst \
the enchanting wilderness.

Anya became a celebrated artist, known far and wide for her ability \
to weave tales of compassion and unity through her exquisite \
paintings. Her work inspired generations to see the world through the \
lens of empathy, teaching them that even in unconventional \
connections between humans and animals, beauty could be found.

And so, her legacy lived on, her art continuing to touch the hearts \
of those who recognized the profound messages hidden within her \
strokes of color. For in every stroke, Anya immortalized the timeless \
bond between humanity and the natural world, forever reminding us of \
the kinship we share with the creatures that roam our earth.

Conclusions and leftover comments

  • The new OpenAI vision model, “gpt-4-vision-preview”, as all LLMs produces too much words, and it has to be reined in and restricted.
  • The functions LLMVisionSynthesize and LLMVisionFunction have to be part of the “LLMFunctions” framework.
    • For example, “LLMVision*” functions do not have an interpreter (or “form”) argument.
  • The package “LLMVision” is meant to be simple and direct, not covering all angles.
  • It would be nice a dedicated notebook cell interface and workflow(s) for interacting with “AI vision” services to be designed and implemented.
    • The main challenge is the input of images.
  • Generating code from hand-written diagrams might be really effective demo using WL.
  • It would be interesting to apply the “AI vision” functionalities over displays from, say, chess or play-cards paclets.

References

Articles

[AA1] Anton Antonov, “Workflows with LLM functions (in WL)”,​ August 4, (2023), Wolfram Community, STAFF PICKS.

[AA2] Anton Antonov, “Raku, Python, and Wolfram Language over LLM functionalities”, (2023), Wolfram Community.

[AA3] Anton Antonov, “AI vision via Raku”, (2023), Wolfram Community.

[MT1] Marco Thiel, “Direct API access to new features of GPT-4 (including vision, DALL-E, and TTS)​​”, November 8, (2023), Wolfram Community, STAFF PICKS.

[OAIb1] OpenAI team, “New models and developer products announced at DevDay” , (2023), OpenAI/blog .

Functions, packages, and paclets

[AAf1] Anton Antonov, MermaidInk, WL function, (2023), Wolfram Function Repository.

[AAp1] Anton Antonov, LLMVision.m, Mathematica package, (2023), GitHub/antononcube .

[AAp2] Anton Antonov, OpenAIMode, WL paclet, (2023), Wolfram Language Paclet Repository.

[AAp3] Anton Antonov, OpenAIRequest.m, Mathematica package, (2023), GitHub/antononcube .

[CWp1] Christopher Wolfram, OpenAILink, WL paclet, (2023), Wolfram Language Paclet Repository.

[WRIp1] Wolfram Research, Inc., LLMFunctions, WL paclet, (2023), Wolfram Language Paclet Repository.

[WRIp2] Wolfram Research, Inc., Chatbook, WL paclet, (2023), Wolfram Language Paclet Repository.

[WRIp3] Wolfram Research, Inc., Chess, WL paclet, (2023), Wolfram Language Paclet Repository.

Videos

[AAv1] Anton Antonov, “OpenAIMode demo (Mathematica)”, (2023), YouTube/@AAA4Prediction.