Этот репозиторий предназначен для пакета Raku (Data), облегчающего подсказки для создания, хранения, поиска и курирования моделей крупных языков (LLM).
Вот пример использования языка с конкретным доменом (DSL) в чате Jupyter, [AA2, AAP2]:
От Zef 'Ecosystem:
zef install LLM::Prompts
От GitHub:
zef install https://github.com/antononcube/Raku-LLM-Prompts.git
Загрузите пакеты "llm :: rapts", [aap1] и "llm :: functions", [aap2]:
Используйте llm :: radpts; используйте llm :: functions;
# (Any)
Покажите запись подсказки под названием «ftfy»:
. Spe для | 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
Вот пример извлечения быстрых данных с помощью корпорации, которая применяется на именах подсказок:
. Shay для 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
Ниже приведены более быстрые примеры поиска в разделе «Распространенные данные».
Сделайте функцию LLM из подсказки с именем "ftfy":
my & f = llm-функция (llm-prompt ('ftfy'));
# -> **@args, *%args { #`(Block|5411904228544) ... }
Используйте функцию LLM, чтобы исправить грамматику предложения:
& f («Где он сейчас работает?»)
# Where does he work now?
Создайте код Raku, используя подсказку «Codewriter»:
LLM-Synthesize ([LLM-PROMPT ('Codewriter'), «Моделируйте случайную прогулку».])
RandomWalk [n_]: = accumulate [randomChoice [{-1, 1}, n]] ListLinePlot [RandomWalk [1000]]
Расширение быстрого использования с использованием Spec Spec DSL-DSL, описанного в [SW1], может быть выполнено с использованием функции llm-prompt-expand
:
LLM-PROMPT-EXPAND ('Что такое двигатель внутреннего сгорания? #eli5')
# What is an internal combustion engine? Answer questions as if the listener is a five year old child.
Здесь мы получаем фактический ответ LLM:
Используйте Text :: utils: All; 'Что такое двигатель внутреннего сгорания? #Eli5 '==> llm-prompt-expand () ==> llm-synthesize () ==> wrap-paragraph () ==> join ("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!
Вот еще один пример, использующий личность и два модификатора:
my $ prmt = llm-prompt-expand ("@southernbellesceak Что такое расстояние света до Марса? #eli5 #moodififif
# 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.
Здесь мы получаем фактический ответ LLM:
$ prmt ==> llm-prompt-expand () ==> llm-synthesize () ==> wrap-paragraph () ==> join ("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.
Более формальное описание языка, специфичного для домена (DSL) для указания подсказок имеет следующие элементы:
Приглашенные личности могут быть «адресованы» с «@». Например:
@Yoda Life can be easy, but some people instist for it to be difficult.
Одно или несколько подсказок модификатора могут быть указаны в конце подсказки. Например:
Summer is over, school is coming soon. #HaikuStyled
Summer is over, school is coming soon. #HaikuStyled #Translated|Russian
Функции могут быть указаны для применения «ячейки» с «!» и размещение подсказки в начале подсказки, которая будет расширена. Например:
!Translated|Portuguese Summer is over, school is coming soon
Функции могут быть указаны для применения к «предыдущим» сообщениям с «!» и разместить только подсказку с одним из указателей "^" или "^^". Первый означает «последнее сообщение», последнее означает «все сообщения».
Сообщения могут быть предоставлены аргументом опции :@messages
of llm-prompt-expand
.
Например:
!ShortLineIt^
Вот таблица спецификаций расширения быстрого расширения (более или менее такая же, как та такая же, как в [SW1]):
Спецификация | Интерпретация |
---|---|
@ имя | Прямой чат с персоной |
# имя | Используйте подсказки модификатора |
! имя | Используйте подсказку функции при вводе токовой ячейки |
! имя > | «То же, что и выше» |
и имя > | «То же, что и выше» |
! имя ^ | Используйте подсказку функции с предыдущим сообщением чата |
! имя ^^ | Используйте подсказку функции со всеми предыдущими сообщениями чата |
! Имя │ Param ... | Включите параметры для подсказок |
Примечание: в подсказках функции может быть обоих сигил "!" и "&".
Примечание: быстрое расширение значительно облегчает использование LLM-чат-альбомов. См. «Юпитер :: чат», [AAP3].
Вот как можно получить быстрые данные:
LLM-PROMPT-DATA.ELEMS
# 222
Вот пример извлечения быстрых данных с помощью корпорации, которая применяется на именах подсказок:
.say для LLM-prompt-data (/em/, fields => <Описание Категории>)
# 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))
Во многих случаях лучше иметь быстрые данные - или любые данные - в длинном формате. Заправленные данные в длинном формате могут быть получены с помощью функции llm-prompt-dataset
:
Используйте Data :: RESHAPERS; Используйте DATA :: Суммарализаторы; LLM-PROMPT-DATASET.PICK (6) ==> TO-PRETTY-TABLE (AIGING => 'L', Field-name => <Имя Описание переменное значение>)
# +-------------------+-----------------------------------------------------------------------------------------------------------------------------+----------+------------------+ # | 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 | # +-------------------+-----------------------------------------------------------------------------------------------------------------------------+----------+------------------+
Вот разбивка категорий подсказок:
SELECT-Columns (LLM-PROMPT-DATASET, <variable value>). grep ({$ _ <variable> eq '' категории '}) ==> records-summary
#ERROR: Do not know how to summarize the argument. # +-------------------+-------+ # | Variable | Value | # +-------------------+-------+ # | Categories => 225 | | # +-------------------+-------+
Здесь получаются все подсказки модификатора в компактном формате:
llm-prompt-dataset (): modifiers: compact ==> to-pretty-table (Field-name => <Имя Описание Категории>, 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 | # +-----------------------+------------------------------------------------------------------------------+-----------------------------------+
Замечание: Наречия :functions
:modifiers
и :personas
означают, что будут возвращены только подсказки с соответствующими категориями.
Замечание: Наречия :compact
:functions
, :modifiers
и :personas
имеют соответствующие ярлыки :c
, :f
, :m
и :p
.
Оригинальная коллекция подсказок (для этого пакета) была (не маленькая) образец быстрых текстов, размещенных в приглашенном репозитории Wolfram (WPR), [SW2]. Все подсказки из WPR в пакете имеют соответствующие участники и URL -адреса для соответствующих страниц WPR.
Пример подсказки от Google/Bard/Palm и Openai/CHATGPT добавляются с использованием формата WPR.
Важно иметь возможность программно добавлять новые подсказки. (Еще не реализовано - см. Раздел TODO ниже.)
Первоначально были реализованы Grammar DSL и соответствующие действия расширения. Однако наличие грамматики, скорее всего, не требуется, и лучше использовать «быстрое расширение» (с помощью замен на основе режима.)
Подсказки могут быть «просто расширены», используя суб llm-prompt-expand
.
Вот блок -схема, которая суммирует быстрый анализ и расширение в ячейках чата jupyter Chatbooks, [AAP3]:
Блок -схема LR
Openai {{openai}}
Palm {{palm}}
Llmfunc [[llm :: functions]]
Llmprom [[llm :: repts]]
Codb [(объекты чата)]
PDB [(подсказка)]
Ccell [/чат ячейка/]
Crcell [/result Cell/]
Cidq {идентификатор чата <br> указан?}
CIDEQ {ID CHAT <br> существует в DB?}
Reco [retave существует <br> Объект чата]
Coeval [сообщение <br> Оценка]
PROMPRASE [Подсказка <br> DSL Spec SAINING]
Kpfq {известно <br> Подсказки <br> Найдено?}
ProMexp [romproding <br> расширение]
CNCO [создать новый объект чата <br>]
Cidnone ["Предполагайте, идентификатор чата <br> - это" нет ""]
Подграф -чат -фронт
Ccell
Crcell
конец
Подграф -чат Бэкэнд
Cidq
CIDEQ
Сиднон
Реко
CNCO
Кодб
конец
Подграфская оперативная обработка
PDB
Llmprom
Промежуточный
KPFQ
ProMexp
конец
Подграф LLM взаимодействие
Коеоваль
Llmfunc
Ладонь
Openai
конец
Ccell -> cidq
Cidq -> | Да | CIDEQ
Cideq -> | Да | Реко
Reco -> Promparse
Coeval -> Crcell
Cideq -.- Codb
CIDEQ -> | Нет | CNCO
Llmfunc -.- cnco -.- codb
Cnco -> promprse -> kpfq
KPFQ -> | Да | ProMexp
KPFQ -> | Нет | Коеоваль
PROMPRESE -.- LLMPROM
ProMexp -.- llmprom
ProMexp -> Coeval
Llmprom -.- Pdb
CIDQ -> | Нет | Сиднон
Cidnone -> cideq
Coeval -.- llmfunc
Llmfunc <-.-> openai
Llmfunc <-.-> palm
ЗагрузкаВот пример быстрого расширения в общей чате LLM и мета -ячейке чата, показывающего содержание соответствующего объекта чата:
Пакет предоставляет скрипт интерфейса командной строки (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).
Вот пример с именем приглашения:
LLM-PROMPT NothingElse 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.
Вот пример с корпорацией:
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
Реализация TODO
Сделано с использованием каталога данных XDG.
Сделано призрачный трафарет
Готово проглатывание пользователя и дополнение к основным подсказкам
Todo путем изменения существующих подсказок.
TODO Автоматическое заполнение шаблона.
TODO GUIDED TEMPLATE.
Todo DSL на основе
Todo LLM на основе
Готовые оперативные наречия
Сделано приглашенная грамматика DSL и действия
Готово расширение спецификации
Готово CLI для быстрого поиска
Может CLI для быстрого набора данных
TODO добавление подсказок пользователя/локального
Сделано добавить больше подсказок
Готово Google BARD Пример подсказки
Отменено примером openai Chatgpt подсказки
Profsynapse
Google или Tyools приглашает
TODO документация
Готово использование чата
Типичное использование
Выполнено запросы (проглатываемые) подсказки
Сделано приглашенное DSL
Сделано ежедневная шутка через CLI
TODO PROMPT FORMAT
Todo при выстрел
Диаграммы TODO
[AA1] Антон Антонов, «Рабочие процессы с функциями LLM», (2023), Ракуфорппресс в WordPress.
[SW1] Стивен Вольфрам, «Новый мир функций LLM: интеграция технологии LLM в язык Wolfram», (2023), сочинения Стивена Вольфрама.
[SW2] Стивен Вольфрам, «Подсказки для работы и игры: запуск репозитория Wolfram Quicts», (2023), Стивен Вольфрам Писания.
[AAP1] Антон Антонов, LLM :: Подсказка Raku Package, (2023), Github/Antononcube.
[AAP2] Anton Antonov, LLM :: Functions Raku Package, (2023), Github/Antononcube.
[AAP3] Антон Антонов, Jupyter :: Chatbook Raku Package, (2023), Github/Antononcube.
[WRIR1] Wolfram Research, Inc., Wolfram