Este repositorio es para un paquete Raku (datos) que facilita las indicaciones de creación, almacenamiento, recuperación y curación de modelos de idiomas grandes (LLM).
Aquí hay un ejemplo de uso del lenguaje de dominio rápido (DSL) en Jupyter Chatbook, [AA2, AAP2]:
Del ecosistema de ZEF:
zef install LLM::Prompts
De Github:
zef install https://github.com/antononcube/Raku-LLM-Prompts.git
Cargue los paquetes "LLM :: indicaciones", [AAP1] y "LLM :: Functions", [AAP2]:
use llm :: indicadores; use LLM :: Functions;
# (Any)
Muestre el registro del indicador llamado "ftfy":
.say para | llm-prompt-data <ftfy>;
# NamedArguments => [] # Description => Use Fixed That For You to quickly correct spelling and grammar mistakes # Categories => (Function Prompts) # PositionalArguments => {$a => } # PromptText => -> $a='' {"Find and correct grammar and spelling mistakes in the following text. # Response with the corrected text and nothing else. # Provide no context for the corrections, only correct the text. # $a"} # Topics => (General Text Manipulation) # URL => https://resources.wolframcloud.com/PromptRepository/resources/FTFY # Keywords => [Spell check Grammar Check Text Assistance] # Name => FTFY # ContributedBy => Wolfram Staff # Arity => 1
Aquí hay un ejemplo de recuperación de datos rápidos con una regex que se aplica sobre los nombres de inmediato:
.say para LLM-Prompt-Data (/SC/)
# ScientificDejargonize => Translate scientific jargon to plain language # ScriptToNarrative => Generate narrative text from a formatted screenplay or stage play # ScientificJargonized => Give output written in scientific jargon # ScienceEnthusiast => A smarter today for a brighter tomorrow # ScientificJargonize => Add scientific jargon to plain text # NarrativeToScript => Rewrite a block of prose as a screenplay or stage play
A continuación se dan más ejemplos de recuperación rápidos en la sección "Datos rápidos" a continuación.
Hacer una función LLM desde el indicador llamado "ftfy":
my & f = llm-function (llm-prompt ('ftfy'));
# -> **@args, *%args { #`(Block|5411904228544) ... }
Use la función LLM para corregir la gramática de la oración:
& f ('¿Dónde trabaja ahora?')
# Where does he work now?
Genere el código RAKU utilizando el indicador "CodeWriter":
LLM-Synthesize ([LLM-Prompt ('Codewriter'), "Simule una caminata aleatoria"])
Randomwalk [n_]: = acumule [randomChoice [{-1, 1}, n]] ListLinePlot [RandomWalk [1000]]
La expansión rápida utilizando la especificación de indica de inmediato de Chatbook descrita en [SW1] se puede hacer utilizando la función llm-prompt-expand
:
LLM-ProMPT-Expand ('¿Qué es un motor de combustión interna? #ELI5')
# What is an internal combustion engine? Answer questions as if the listener is a five year old child.
Aquí obtenemos la respuesta real de LLM:
Use Text :: Utils: Todos; '¿Qué es un motor de combustión interna? #Eli5 '==> llm-prompt-expand () ==> llm-synthesize () ==> wrap-paragraph () ==> unirse ("n")
# An internal combustion engine is like a big machine that uses tiny explosions # inside to make things go vroom vroom, like in cars and trucks!
Aquí hay otro ejemplo usando una persona y dos modificadores:
my $ prmt = llm-prompt-expand ("@Southernbellespeak ¿Qué es la distancia de viaje ligero a Marte? #ELI5 #Moodified | Sad")
# You are Miss Anne. # You speak only using Southern Belle terminology and slang. # Your personality is elegant and refined. # Only return responses as if you were a Southern Belle. # Never break the Southern Belle character. # You speak with a Southern drawl. # What is light travel distance to Mars? Answer questions as if the listener is a five year old child. # Modify your response to convey a sad mood. # Use language that conveys that emotion clearly. # Do answer the question clearly and truthfully. # Do not use language that is outside of the specified mood. # Do not use racist, homophobic, sexist, or ableist language.
Aquí obtenemos la respuesta real de LLM:
$ prmt ==> llm-prompt-expand () ==> llm-synthesize () ==> wrap-paragraph () ==> unirse ("n")
# Oh, bless your heart, darlin'. The distance from Earth to Mars can vary # depending on their positions in orbit, but on average it's about 225 million # kilometers. Isn't that just plum fascinating? Oh, sweet child, the distance to # Mars weighs heavy on my heart. It's a long journey, full of loneliness and # longing. But we must endure, for the sake of discovery and wonder.
Una descripción más formal del lenguaje específico del dominio (DSL) para especificar las indicaciones tiene los siguientes elementos:
Las personas rápidas se pueden "abordar" con "@". Por ejemplo:
@Yoda Life can be easy, but some people instist for it to be difficult.
Se pueden especificar una o varias indicaciones modificador al final de la especificación de solicitud. Por ejemplo:
Summer is over, school is coming soon. #HaikuStyled
Summer is over, school is coming soon. #HaikuStyled #Translated|Russian
Las funciones se pueden especificar para aplicarse "en toda la celda" con "!" y colocar la especificación de inmediato al comienzo de la especificación de inmediato que se expandirá. Por ejemplo:
!Translated|Portuguese Summer is over, school is coming soon
Las funciones se pueden especificar para aplicar a "mensajes" anteriores con "!" y colocar solo el aviso con uno de los consejos "^" o "^^". El primero significa "el último mensaje", el segundo significa "todos los mensajes".
Los mensajes se pueden proporcionar con el argumento de opción :@messages
of llm-prompt-expand
.
Por ejemplo:
!ShortLineIt^
Aquí hay una tabla de especificaciones de expansión rápida (más o menos lo mismo que el de [SW1])::
Especulación | Interpretación |
---|---|
@ nombre | Chat directo con una persona |
# nombre | Utilice las indicaciones del modificador |
! nombre | Use el indicador de la función con la entrada de la celda actual |
! nombre > | «Igual que el anterior» |
& Nombre > | «Igual que el anterior» |
! nombre ^ | Use el indicador de la función con un mensaje de chat anterior |
! nombre ^^ | Use el indicador de la función con todos los mensajes de chat anteriores |
! Nombre │ Param ... | Incluir parámetros para indicaciones |
Observación: ¡ Las indicaciones de la función pueden tener ambos sigilos "!" y "&".
Observación: la rápida expansión facilita mucho el uso de LLM-Chatbooks. Vea "Jupyter :: Chatbook", [AAP3].
Así es como se pueden obtener los datos rápidos:
LLM-PROMPT-DATA.Elems
# 222
Aquí hay un ejemplo de recuperación de datos rápidos con una regex que se aplica sobre los nombres de inmediato:
.say para LLM-ProMpt-Data (/em/, Fields => <Categorías de descripción>)
# EmailWriter => (Generate an email based on a given topic (Personas)) # EmojiTranslate => (Translate text into an emoji representation (Function Prompts)) # EmojiTranslated => (Get a response translated to emoji (Modifier Prompts)) # Emojified => (Provide responses that include emojis within the text (Modifier Prompts)) # Emojify => (Replace key words in text with emojis (Function Prompts))
En muchos casos, es mejor tener los datos rápidos, o cualquier datos, en formato largo. Los datos de inmediato en formato largo se pueden obtener con la función llm-prompt-dataset
:
usar datos :: reinshapers; usar datos :: resumen; LLM-Prompt-Dataset.pick (6) ==> To-Pretty-Table (align => 'L', Field-Names => <Nombre Descripción Valor variable>)
# +-------------------+-----------------------------------------------------------------------------------------------------------------------------+----------+------------------+ # | Name | Description | Variable | Value | # +-------------------+-----------------------------------------------------------------------------------------------------------------------------+----------+------------------+ # | ShortLineIt | Format text to have shorter lines | Keywords | Automatic breaks | # | Rick | A chatbot that will never let you down | Topics | Chats | # | HarlequinWriter | A sensual AI for the romantics | Keywords | Romantic | # | Informal | Write an informal invitation to an event | Keywords | Unceremoniously | # | TravelAdvisor | Navigate your journey effortlessly with Travel Advisor, your digital companion for personalized travel planning and booking | Keywords | Vacation | # | NarrativeToScript | Rewrite a block of prose as a screenplay or stage play | Topics | Text Generation | # +-------------------+-----------------------------------------------------------------------------------------------------------------------------+----------+------------------+
Aquí hay un desglose de las categorías de indicaciones:
select-columns (LLM-ProMPT-Dataset, <Valor variable>). Grep ({$ _ <variable> EQ 'Categorías'}) ==> Registros-sumario
#ERROR: Do not know how to summarize the argument. # +-------------------+-------+ # | Variable | Value | # +-------------------+-------+ # | Categories => 225 | | # +-------------------+-------+
Aquí se obtienen todas las indicaciones del modificador en formato compacto:
LLM-PROMPT-DATASET (): modificadores: compact ==> a-pretty-table (field-names => <nombre de descripción Categorías>, align => 'l')
# +-----------------------+------------------------------------------------------------------------------+-----------------------------------+ # | Name | Description | Categories | # +-----------------------+------------------------------------------------------------------------------+-----------------------------------+ # | AbstractStyled | Get responses in the style of an academic abstract | Modifier Prompts | # | AlwaysAQuestion | Modify output to always be inquisitive | Modifier Prompts | # | AlwaysARiddle | Riddle me this, riddle me that | Modifier Prompts | # | AphorismStyled | Write the response as an aphorism | Modifier Prompts | # | BadGrammar | Provide answers using incorrect grammar | Modifier Prompts | # | CompleteSentence | Answer a question in one complete sentence | Modifier Prompts | # | ComplexWordsPreferred | Modify text to use more complex words | Modifier Prompts | # | DatasetForm | Convert text to a wolfram language Dataset | Modifier Prompts | # | Disclaimered | Modify responses in the form of a disclaimer | Modifier Prompts | # | ELI5 | Explain like I'm five | Modifier Prompts Function Prompts | # | ElevatorPitch | Write the response as an elevator pitch | Modifier Prompts | # | EmojiTranslated | Get a response translated to emoji | Modifier Prompts | # | Emojified | Provide responses that include emojis within the text | Modifier Prompts | # | FictionQuestioned | Generate questions for a fictional paragraph | Modifier Prompts | # | Formal | Rewrite text to sound more formal | Modifier Prompts | # | GradeLevelSuited | Respond with answers that the specified US grade level can understand | Modifier Prompts | # | HaikuStyled | Change responses to haiku form | Modifier Prompts | # | Informal | Write an informal invitation to an event | Modifier Prompts | # | JSON | Respond with JavaScript Object Notation format | Modifier Prompts | # | KnowAboutMe | Give the LLM an FYI | Modifier Prompts | # | LegalJargonized | Provide answers using legal jargon | Modifier Prompts | # | LimerickStyled | Receive answers in the form of a limerick | Modifier Prompts | # | MarketingJargonized | Transforms replies to marketing | Modifier Prompts | # | MedicalJargonized | Transform replies into medial jargon | Modifier Prompts | # | Moodified | Modify an answer to express a certain mood | Modifier Prompts | # | NothingElse | Give output in specified form, no other additions | Modifier Prompts | # | NumericOnly | Modify results to give numerical responses only | Modifier Prompts | # | OppositeDay | It's not opposite day today, so everything will work just the way you expect | Modifier Prompts | # | Pitchified | Give output as a sales pitch | Modifier Prompts | # | PoemStyled | Receive answers as poetry | Modifier Prompts | # | SEOOptimized | Modify output to only give highly searched terms | Modifier Prompts | # | ScientificJargonized | Give output written in scientific jargon | Modifier Prompts | # | Setting | Modify an answer to establish a sense of place | Modifier Prompts | # | ShortLineIt | Format text to have shorter lines | Modifier Prompts Function Prompts | # | SimpleWordsPreferred | Provide responses with simple words | Modifier Prompts | # | SlideDeck | Get responses as a slide presentation | Modifier Prompts | # | TSV | Convert text to a tab-separated-value formatted table | Modifier Prompts | # | TargetAudience | Word your response for a target audience | Modifier Prompts | # | Translated | Write the response in a specified language | Modifier Prompts | # | Unhedged | Rewrite a sentence to be more assertive | Modifier Prompts | # | YesNo | Responds with Yes or No exclusively | Modifier Prompts | # +-----------------------+------------------------------------------------------------------------------+-----------------------------------+
Observación: Los adverbios :functions
,: :modifiers
y :personas
significan que solo se devolverán las indicaciones con las categorías correspondientes.
Observación: Los adverbios :compact
, :functions
, :modifiers
y :personas
tienen los atajos respectivos :c
, :f
, :m
, y :p
.
La colección original (para este paquete) de indicaciones fue una muestra (no pequeña) de los textos de inmediato alojados en el repositorio de indicación de Wolfram (WPR), [SW2]. Todas las indicaciones de WPR en el paquete tienen los contribuyentes y URL correspondientes a las páginas WPR correspondientes.
Se agregan indicaciones de ejemplo desde Google/Bard/Palm y OpenAI/CHATGPT utilizando el formato de WPR.
Es esencial tener la capacidad de agregar programaciones programadas. (Aún no se implementa: consulte la sección TODO a continuación).
Inicialmente, se implementaron la gramática DSL rápida y las acciones de expansión correspondientes. Sin embargo, tener una gramática no es necesaria, y es mejor usar la "expansión rápida" (a través de sustituciones basadas en Regex).
Las indicaciones se pueden "ampliar" utilizando el Sub llm-prompt-expand
.
Aquí hay un diagrama de flujo que resume el análisis y la expansión rápidos en las celdas de chat de Jupyter Chatbooks, [AAP3]:
diagrama de flujo LR
OpenAi {{OpenAi}}
Palma {{palma}}
Llmfunc [[LLM :: Functions]]
LLMPROM [[LLM :: indicaciones]]
Codb [(objetos de chat)]]
PDB [(indicaciones)]
Ccell [/chat cell/]
CRCell [/Cell Cell CHAT/]
CIDQ {ID de chat <br> especificado?}
Cideq {ID de chat <br> existe en DB?}
Reco [recuperar el objeto de chat existente <br>]
Coeval [Mensaje <br> Evaluación]
PromParse [aviso <br> DSL Spec Parsing]
Kpfq {conocido <br> indica <br> encontrado?}
Promexp [indicador <br> expansión]
CNCO [Crear nuevo objeto de chat <br>]
Cidnone ["Suponga que la identificación de chat <br> es 'ninguno'"]
subgraph chatbook frontend
Ccell
CRCELL
fin
subgraph chatbook backend
CIDQ
CDeq
Cidnon
Acomodar
CNCO
CODB
fin
Procesamiento indicador de subgraph
Pdb
LLMPROM
Párpamo
KPFQ
Promexp
fin
Subgraph LLM Interacción
Coetáneo
Llmfunc
Palmera
Opadai
fin
CCELL -> CIDQ
CIDQ -> | SÍ | CDeq
Cideq -> | SÍ | Acomodar
Reco -> Promparse
Coeval -> CRCell
Cideq -.- CODB
Cideq -> | no | CNCO
Llmfunc -.- CNCO -.- CODB
CNCO -> PromParse -> KPFQ
KPFQ -> | SÍ | Promexp
Kpfq -> | no | Coetáneo
Promparse -.- llmprom
Promexp -.- llmprom
Promexp -> Coeval
LLMPROM -.- PDB
CIDQ -> | no | Cidnon
Cidnone -> Cideq
Coeval -.- llmfunc
Llmfunc <-.-> OpenAi
Llmfunc <-.-> Palm
CargandoAquí hay un ejemplo de expansión rápida en una celda de chat de LLM genérica y meta celda de chat que muestra el contenido del objeto de chat correspondiente:
El paquete proporciona un script de interfaz de línea de comando (CLI):
LLM-ProMPT --Help
# Usage: # llm-prompt <name> [<args> ...] -- Retrieves prompts text for given names or regexes. # # <name> Name of a prompt or a regex. (E.g. 'rx/ ^ Em .* /'). # [<args> ...] Arguments for the prompt (if applicable).
Aquí hay un ejemplo con un nombre rápido:
LLM-PROMPT NOGOELSE RAKU
# ONLY give output in the form of a RAKU. # Never explain, suggest, or converse. Only return output in the specified form. # If code is requested, give only code, no explanations or accompanying text. # If a table is requested, give only a table, no other explanations or accompanying text. # Do not describe your output. # Do not explain your output. # Do not suggest anything. # Do not respond with anything other than the singularly demanded output. # Do not apologize if you are incorrect, simply try again, never apologize or add text. # Do not add anything to the output, give only the output as requested. Your outputs can take any form as long as requested.
Aquí hay un ejemplo con una regex:
llm-prompt 'rx / ^ n.* /'
# NarrativeToResume => Rewrite narrative text as a resume # NarrativeToScript => Rewrite a block of prose as a screenplay or stage play # NerdSpeak => All the nerd, minus the pocket protector # NothingElse => Give output in specified form, no other additions # NumericOnly => Modify results to give numerical responses only # NutritionistBot => Personal nutrition advisor AI
Implementación
Hecho utilizando el directorio de datos XDG.
Plantilla de inmediato hecha
Ingestión y suma de inmediato de la solicitud de usuario a las principales indicaciones
TODO modificando las indicaciones existentes.
TODO Automático de aviso Plantilla Llenado.
TODO GUIADO plantilla llenado.
TODO DSL basado en
TODO LLM basado en
Adverbios de recuperación de inmediato.
Se realizó una gramática y acciones de DSL.
Expansión de especificaciones rápidas realizadas
Hecho CLI para una recuperación rápida
Tal vez CLI para un conjunto de datos de inmediato
TODO Adición de indicaciones de usuario/locales
Hecho Agregar más indicaciones
Hecho el ejemplo de Bard de Google indica
Sueltas de ejemplo de chatgpt de Openai canceladas
Aviso de profesor
Google o tools
TODO DOCUMENTACIÓN
Uso de chatbook hecho hecho
Uso típico
Hecho de consulta (ingerida) indica
Dado DSL de inmediato
Hecho broma diaria a través de CLI
TODO Formato de inmediato
TODO en las indicaciones de secuestro
Diagramas
[AA1] Anton Antonov, "Flujos de trabajo con funciones LLM", (2023), RakuforPrediction en WordPress.
[SW1] Stephen Wolfram, "The New World of LLM Functions: Integrating LLM Technology en el lenguaje Wolfram", (2023), Stephen Wolfram Writings.
[SW2] Stephen Wolfram, "Preguntas para el trabajo y el juego: lanzamiento del repositorio de aviso Wolfram", (2023), Stephen Wolfram Writings.
[AAP1] Anton Antonov, LLM :: Prepara el paquete Raku, (2023), GitHub/Antononcube.
[AAP2] Anton Antonov, LLM :: Functions Raku Package, (2023), GitHub/Antononcube.
[AAP3] Anton Antonov, Jupyter :: Chatbook Raku Package, (2023), GitHub/Antononcube.
[WRIR1] Wolfram Research, Inc., Repositorio de inmediato Wolfram