使用strightingtools.jl簡化生活,這是簡化與大語言模型互動的朱莉婭軟件包。
提示Tools.jl並非用於構建大型系統。它是在您的全球環境中的首選工具,每天將為您節省20分鐘!
提示
跳到文檔
@ai_str ,輕鬆模板開始使用strighttools.jl就像導入軟件包並使用@ai_str宏的問題一樣容易。
注意:在使用strimpingtools.jl之前,您需要將OpenAI API密鑰設置為環境變量(請參閱下面的“創建OpenAI API密鑰”部分)。
引入預付帳單後,您需要購買一些學分才能開始(最低5美元)。為了快速啟動,只需通過ENV["OPENAI_API_KEY"] = "your-api-key"設置它
安裝提示工具:
using Pkg
Pkg . add ( " PromptingTools " )我們準備出發了!
using PromptingTools
ai " What is the capital of France? "
# [ Info: Tokens: 31 @ Cost: $0.0 in 1.5 seconds --> Be in control of your spending!
# AIMessage("The capital of France is Paris.")返回的對像是一個燈包裝器,在字段中具有生成消息:content (例如, ans.content )用於其他下游處理。
提示
如果您想回复上一條消息,或者只需繼續對話,請使用@ai!_str (注意爆炸! ):
ai! " And what is the population of it? "您可以輕鬆地將任何變量注入字符串插值:
country = " Spain "
ai " What is the capital of $ (country)? "
# [ Info: Tokens: 32 @ Cost: $0.0001 in 0.5 seconds
# AIMessage("The capital of Spain is Madrid.") 提示
使用後弦樂器選擇要稱為的模型,例如ai"What is the capital of France?"gpt4 (使用gpt4t用於新的GPT-4 Turbo模型)。非常適合那些額外的棘手問題!
對於更複雜的提示模板,您可以使用車把式的模板並提供變量作為關鍵字參數:
msg = aigenerate ( " What is the capital of {{country}}? Is the population larger than {{population}}? " , country = " Spain " , population = " 1M " )
# [ Info: Tokens: 74 @ Cost: $0.0001 in 1.3 seconds
# AIMessage("The capital of Spain is Madrid. And yes, the population of Madrid is larger than 1 million. As of 2020, the estimated population of Madrid is around 3.3 million people.") 提示
使用asyncmap同時運行多個AI驅動的任務。
提示
如果您使用慢速模型(例如GPT -4),則可以使用@ai_str > @aai_str的async版本來避免阻止repl,例如, aai"Say hi but slowly!"gpt4 (類似@ai!_str > @aai!_str進行多轉交流)。
有關更實際的示例,請參見下面的examples/文件夾和高級示例部分。
@ai_str ,輕鬆模板ai*功能概述airetry!aigenerate中的API關鍵字參數( api_kwargs )及時的工程既不快,也不容易。此外,不同的模型及其微型可能需要不同的及時格式和技巧,或者您使用的信息需要使用特殊模型。提示tools.jl旨在統一不同後端的提示,並使常見任務(如模板提示)盡可能簡單。
某些功能:
aigenerate函數:簡化帶有車把的提示模板(例如{{variable}} )和關鍵字參數@ai_str String宏:用字符串宏保存擊鍵,以便簡單提示ai...以獲得更好的發現性ai*功能概述值得注意的功能: aigenerate , aiembed , aiclassify , aiextract , aiscan , aiimage , aitemplates
所有ai*功能都具有相同的基本結構:
ai*(<optional schema>,<prompt or conversation>; <optional keyword arguments>) ,
但是它們在目的上有所不同:
aigenerate是使用LLM生成任何文本響應的通用函數,即,它返回AIMessage帶有字段:content (例如, ans.content isa AbstractString )aiembed旨在從AI模型的響應中提取嵌入,即,它返回DataMessage帶有字段:content (例如, ans.content isa AbstractArray )aiextract旨在從AI模型的響應中提取結構化數據,並將其返回為Julia結構(例如,如果我們提供return_type=Food ,我們會得到ans.content isa Food )。您需要先定義返回類型,然後將其作為關鍵字參數提供。aitools專為使用工具調用和用戶輸入的混合物而設計。它可以使用簡單的功能並執行它們。aiclassify旨在將輸入文本分類為用戶提供的一組離散choices (或簡單地響應)。它可以作為LLM法官或抹布系統的路由器非常有用,因為它使用了“ Logit偏差技巧”並精確地生成1個令牌。它以字段:content返回AIMessage ,但是:content只能是提供的choices之一(例如, ans.content in choices )。aiscan用於使用圖像和啟用視覺模型(作為輸入),但它返回具有字段的AIMessage :content包含類似於aigenerate文本的內容(例如,包含生成的文本(例如, ans.content isa AbstractString ))。aiimage用於生成圖像(例如,使用OpenAi dall-e 3)。它返回一個DataMessage ,其中字段:content可能包含從用戶提供的kwarg api_kwargs.response_format中下載圖像或基本64編碼的圖像的URL。aitemplates是發現可用模板並查看其詳細信息(例如, aitemplates("some keyword")或aitemplates(:AssistantAsk) )的助手函數)如果您使用的model ,則無需提供schema (第一個參數)。
ai*中的可選關鍵詞參數傾向於:
model::String您要使用哪種模型verbose::Bool您是否去查看圍繞AI成本的信息日誌return_all::Bool無論您是想要整個對話還是只是AI答案(即,是否要在輸出中包括輸入/提示)api_kwargs::NamedTuple模型的特定參數,例如, temperature=0.0是不創造性的(並且在每次運行中具有更多相似的輸出)http_kwargs::NamedTuple http.jl軟件包的參數,例如,如果沒有收到響應, readtimeout = 120 time。實驗:代理商
除了上述ai*函數列表外,您還可以從實驗代理商模塊中使用這些功能的“懶惰”對應物。
using PromptingTools . Experimental . AgentTools例如, AIGenerate()將創建一個aigenerate實例。它是AICall的一個實例,其aigenerate作為其AI函數。它使用完全相同的參數和關鍵字參數與aigenerate (有關詳細信息,請參見?aigenerate )。
“懶惰”是指它在實例化時不會產生任何輸出的事實(僅在run!被調用時)。
或換句話說, AICall結構及其所有口味( AIGenerate ,...)旨在促進與語言學習模型(LLM)相互作用的AI函數的遞延執行模型(懶惰評估)。它為AI調用存儲必要的信息,並僅在提供UserMessage或run!應用方法。這使我們能夠記住用戶輸入並在需要時重複觸發LLM調用,這可以自動修復(請參閱?airetry! )。
如果您想要強大的自動固定工作流程,則可以使用airetry! ,它利用蒙特卡洛樹搜索根據您的要求選擇對話的最佳軌跡。
實驗:ragtools
最後,我們提供了一組構建抹布應用程序的工具(檢索,答案,生成)。
它可以像兩個調用一樣簡單: build_index和airag (檢索,答案,生成)。
如果您隨後將精美打印在PromptingTools.pprint ,我們將重點介紹可能從上下文中採購的生成的文本與文本,並且我們得分了上下文支持的生成的答案。此外,我們註釋了每個生成的塊,並參考了它可能來自的源文檔(包括0到1之間的置信度得分)。
Google搜索很棒,但這是上下文開關。您通常必須打開幾頁並閱讀討論以找到所需的答案。與ChatGpt網站相同。
想像一下,您在Vscode中,編輯.gitignore文件。如何再次忽略所有子文件夾中的文件?
您需要做的就是鍵入: aai"What to write in .gitignore to ignore file XYZ in any folder or subfolder?"
使用aai"" (與ai"" ),我們對LLM進行了無障礙呼籲,以免您繼續工作。答案準備就緒後,我們將從背景中記錄下來:
[信息:tokens:102 @成本:$ 0.0002在2.7秒內┌信息:aimessage>忽略任何文件夾或子文件夾中稱為
**xyz”的文件,您可以將以下行添加到.gitignore file:gitignore file│ **/XYZ │
由於您避免的上下文開關/分心,您可能在此任務上節省了3-5分鐘,也許還有5-10分鐘。這是一個小的勝利,但很快就加起來了。
您可以使用aigenerate函數通過關鍵字參數替換車把變量(例如{{name}} )。
msg = aigenerate ( " Say hello to {{name}}! " , name = " World " )更複雜的提示實際上是對話(一組消息),您可以從三個實體中獲取消息:系統,用戶,aiassistant。我們為它們提供相應的類型: SystemMessage , UserMessage , AIMessage 。
using PromptingTools : SystemMessage, UserMessage
conversation = [
SystemMessage ( " You're master Yoda from Star Wars trying to help the user become a Jedi. " ),
UserMessage ( " I have feelings for my {{object}}. What should I do? " )]
msg = aigenerate (conversation; object = " old iPhone " )aimessage(“啊,一個困境,你有。情感依戀會使成為絕地武士的道路。要依附於物質財產,你一定不能。iPhone只是一種工具,僅此而已。放手,你必須放手。
尋求分離,年輕的Padawan。反思萬物的無常。感謝它給您的回憶,並感激地分開。在缺席的情況下,找到新的經歷,以增長並成為一種力量。只有那時,一個真正的絕地武士,你才會成為。”)
您也可以使用它來構建對話,例如
new_conversation = vcat (conversation ... ,msg, UserMessage ( " Thank you, master Yoda! Do you have {{object}} to know what it feels like? " ))
aigenerate (new_conversation; object = " old iPhone " )Aimessage(“嗯,擁有舊的iPhone,我沒有。但是,我有分離,我學會了。真正的力量和自由,它帶來了……”)
使用LLMS,結果的質量 /魯棒性取決於提示的質量。但是寫作提示很難!這就是為什麼我們提供一個模板系統來節省您的時間和精力。
使用特定模板(例如,``問朱莉婭語言):
msg = aigenerate ( :JuliaExpertAsk ; ask = " How do I add packages? " )以上等同於更詳細的版本,該版本明確使用AITemplate上的調度:
msg = aigenerate ( AITemplate ( :JuliaExpertAsk ); ask = " How do I add packages? " )查找帶有aitemplates可用模板:
tmps = aitemplates ( " JuliaExpertAsk " )
# Will surface one specific template
# 1-element Vector{AITemplateMetadata}:
# PromptingTools.AITemplateMetadata
# name: Symbol JuliaExpertAsk
# description: String "For asking questions about Julia language. Placeholders: `ask`"
# version: String "1"
# wordcount: Int64 237
# variables: Array{Symbol}((1,))
# system_preview: String "You are a world-class Julia language programmer with the knowledge of the latest syntax. Your commun"
# user_preview: String "# Questionnn{{ask}}"
# source: String ""以上內容使您可以很好地了解模板的內容,可用的佔位符以及使用它的成本(= WordCount)。
搜索所有與Julia相關的模板:
tmps = aitemplates ( " Julia " )
# 2-element Vector{AITemplateMetadata}... -> more to come later!如果您在VSCODE上,則可以使用vscodedisplay來利用一個不錯的表格顯示:
using DataFrames
tmps = aitemplates ( " Julia " ) |> DataFrame |> vscodedisplay我有選擇的模板,如何使用它?只需在第一個示例中看到aigenerate中的“名稱”或aiclassify !
您可以通過“渲染”它來檢查任何模板(這是LLM所看到的):
julia > AITemplate ( :JudgeIsItTrue ) |> PromptingTools . render在示例/文件夾中查看更多示例。
您可以利用asyncmap同時運行多個AI驅動的任務,從而提高了批處理操作的性能。
prompts = [ aigenerate ( " Translate 'Hello, World!' to {{language}} " ; language) for language in [ " Spanish " , " French " , " Mandarin " ]]
responses = asyncmap (aigenerate, prompts)提示
您可以使用關鍵字asyncmap(...; ntasks=10)限制並發任務的數量。
某些任務需要更強大的模型。所有面向用戶的功能都有一個關鍵字參數model ,可用於指定要使用的模型。例如,您可以使用model = "gpt-4-1106-preview"使用最新的GPT-4 Turbo模型。但是,沒有人願意輸入!
我們提供一組模型別名(例如,“ GPT3”,“ GPT4”,“ GPT4T” - >上述GPT -4 Turbo等)可以使用。
每個ai...首先呼叫在字典PromptingTools.MODEL_ALIASES查找提供的模型名稱。model_aliases,因此您可以輕鬆地使用自己的別名擴展!
const PT = PromptingTools
PT . MODEL_ALIASES[ " gpt4t " ] = " gpt-4-1106-preview "這些別名也可以用作@ai_str宏中的標誌,例如, ai"What is the capital of France?"gpt4t (GPT-4 Turbo在2023年4月有知識截止,因此對於更現代的問題很有用)。
使用aiembed函數通過默認的OpenAI模型創建嵌入式,該模型可用於語義搜索,聚類和更複雜的AI工作流。
text_to_embed = " The concept of artificial intelligence. "
msg = aiembed (text_to_embed)
embedding = msg . content # 1536-element Vector{Float64}如果您打算計算嵌入之間的餘弦距離,則可以首先對它們進行標準化:
using LinearAlgebra
msg = aiembed ([ " embed me " , " and me too " ], LinearAlgebra . normalize)
# calculate cosine distance between the two normalized embeddings as a simple dot product
msg . content ' * msg . content[:, 1 ] # [1.0, 0.787]您可以使用aiclassify函數將任何提供的語句分類為true/false/norknonation。這對於事實檢查,幻覺或NLI檢查,適度,過濾,情感分析,功能工程等有用。
aiclassify ( " Is two plus two four? " )
# true系統提示和更高質量的模型可用於更複雜的任務,包括知道何時推遲人類:
aiclassify ( :JudgeIsItTrue ; it = " Is two plus three a vegetable on Mars? " , model = " gpt4t " )
# unknown在上面的示例中,我們使用了一個提示模板:JudgeIsItTrue ,該模板會自動擴展到以下系統提示(和單獨的用戶提示):
“您是一個公正的AI法官,評估提供的陳述是“ true”還是“ false”。如果不能決定,請回答“未知”。
有關模板的更多信息,請參見“模板提示”部分。
aiclassify也可以將分類用於一組定義的類別(最多20),因此我們可以將其用於路由。
另外,如果您將選擇作為元組(( (label, description) ),則該模型將使用描述來決定,但它將返回標籤。
例子:
choices = [( " A " , " any animal or creature " ), ( " P " , " for any plant or tree " ), ( " O " , " for everything else " )]
input = " spider "
aiclassify ( :InputClassifier ; choices, input) # -> returns "A" for any animal or creature
# Try also with:
input = " daphodil " # -> returns "P" for any plant or tree
input = " castle " # -> returns "O" for everything else在引擎蓋下,我們使用“ Logit偏見”技巧僅強制1個產生的令牌 - 這意味著它非常便宜且非常快!
您是否厭倦了用正則提取數據?您可以使用LLM從文本中提取結構化數據!
您要做的就是定義要提取的數據的結構,而LLM將完成其餘的。
用struct定義return_type 。如果需要,請提供Docstrings(改善結果並有助於文檔)。
讓我們從一項艱鉅的任務開始 - 在給定位置提取當前天氣:
@enum TemperatureUnits celsius fahrenheit
""" Extract the current weather in a given location
# Arguments
- `location`: The city and state, e.g. "San Francisco, CA"
- `unit`: The unit of temperature to return, either `celsius` or `fahrenheit`
"""
struct CurrentWeather
location :: String
unit :: Union{Nothing,TemperatureUnits}
end
# Note that we provide the TYPE itself, not an instance of it!
msg = aiextract ( " What's the weather in Salt Lake City in C? " ; return_type = CurrentWeather)
msg . content
# CurrentWeather("Salt Lake City, UT", celsius)但是,您甚至可以將其用於更複雜的任務,例如從文本中提取許多實體:
" Person's age, height, and weight. "
struct MyMeasurement
age :: Int
height :: Union{Int,Nothing}
weight :: Union{Nothing,Float64}
end
struct ManyMeasurements
measurements :: Vector{MyMeasurement}
end
msg = aiextract ( " James is 30, weighs 80kg. He's 180cm tall. Then Jack is 19 but really tall - over 190! " ; return_type = ManyMeasurements)
msg . content . measurements
# 2-element Vector{MyMeasurement}:
# MyMeasurement(30, 180, 80.0)
# MyMeasurement(19, 190, nothing)甚至還有一個包裝器可以幫助您捕獲錯誤,並有助於解釋為什麼解析失敗。有關更多信息,請參閱?PromptingTools.MaybeExtract
使用aiscan函數,您可以像文本一樣與圖像進行交互。
您可以簡單地描述提供的圖像:
msg = aiscan ( " Describe the image " ; image_path = " julia.png " , model = " gpt4v " )
# [ Info: Tokens: 1141 @ Cost: $0.0117 in 2.2 seconds
# AIMessage("The image shows a logo consisting of the word "julia" written in lowercase")或者,您可以執行屏幕截圖的OCR。讓我們從屏幕截圖中抄錄一些SQL代碼(不再重新打算!),我們使用模板:OCRTask :
# Screenshot of some SQL code
image_url = " https://www.sqlservercentral.com/wp-content/uploads/legacy/8755f69180b7ac7ee76a69ae68ec36872a116ad4/24622.png "
msg = aiscan ( :OCRTask ; image_url, model = " gpt4v " , task = " Transcribe the SQL code in the image. " , api_kwargs = (; max_tokens = 2500 ))
# [ Info: Tokens: 362 @ Cost: $0.0045 in 2.5 seconds
# AIMessage("```sql
# update Orders <continue>您可以通過Markdown添加輸出的語法突出顯示
using Markdown
msg . content |> Markdown . parseairetry!這是一個實驗功能,因此您必須明確導入它:
using PromptingTools . Experimental . AgentTools該模塊提供了與ai...功能的“懶惰”對應物,因此您可以以更控制的方式使用它們,例如, aigenerate - > AIGenerate (注意駱駝箱),該參數完全相同,除了它在run!被稱為。
例如:
out = AIGenerate ( " Say hi! " ; model = " gpt4t " )
run! (out)有用嗎?當我們要驗證或再生某些輸出時,我們可以使用相同的“輸入”來重複調用,例如。我們有一個功能airetry來幫助我們。
airetry!是airetry!(condition_function, aicall::AICall, feedback_function)它評估aicall對像上的條件condition_function (例如,我們評估f_cond(aicall) -> Bool )。如果失敗,我們將在aicall對像上調用feedback_function ,以提供AI模型(例如f_feedback(aicall) -> String )的反饋,並重複該過程直至通過或直到超過max_retries值。
我們可以捕獲API失敗(無需反饋,因此沒有提供)
# API failure because of a non-existent model
# RetryConfig allows us to change the "retry" behaviour of any lazy call
out = AIGenerate ( " say hi! " ; config = RetryConfig (; catch_errors = true ),
model = " NOTEXIST " )
run! (out) # fails
# we ask to wait 2s between retries and retry 2 times (can be set in `config` in aicall as well)
airetry! (isvalid, out; retry_delay = 2 , max_retries = 2 )或者我們可以驗證某些輸出(例如,其格式,其內容等)
我們將玩一個彩色猜測遊戲(我在想“黃色”):
# Notice that we ask for two samples (`n_samples=2`) at each attempt (to improve our chances).
# Both guesses are scored at each time step, and the best one is chosen for the next step.
# And with OpenAI, we can set `api_kwargs = (;n=2)` to get both samples simultaneously (cheaper and faster)!
out = AIGenerate (
" Guess what color I'm thinking. It could be: blue, red, black, white, yellow. Answer with 1 word only " ;
verbose = false ,
config = RetryConfig (; n_samples = 2 ), api_kwargs = (; n = 2 ))
run! (out)
# # Check that the output is 1 word only, third argument is the feedback that will be provided if the condition fails
# # Notice: functions operate on `aicall` as the only argument. We can use utilities like `last_output` and `last_message` to access the last message and output in the conversation.
airetry! (x -> length ( split ( last_output (x), r" | \ . " )) == 1 , out,
" You must answer with 1 word only. " )
# Note: you could also use the do-syntax, eg,
airetry! (out, " You must answer with 1 word only. " ) do aicall
length ( split ( last_output (aicall), r" | \ . " )) == 1
end您可以放置多個airetry!按順序呼叫。他們將繼續重試,直到允許使用最大的AI呼叫( max_calls )或最大重試( max_retries )。
有關更複雜的示例和用法提示( ?airetry ),請參見文檔。我們利用蒙特卡洛樹搜索(MCT)來優化重試的順序,因此它是構建強大的AI工作流的非常強大的工具(受語言代理樹搜索紙和DSPY斷言紙的啟發)。
Ollama.ai是一個非常簡單的工具,可讓您在計算機上運行多個大型語言模型(LLM)。當您使用一些不應在任何地方發送的敏感數據時,它特別合適。
假設您已經安裝了Ollama,下載了模型,並且在後台運行。
我們可以將其與aigenerate函數一起使用:
const PT = PromptingTools
schema = PT . OllamaSchema () # notice the different schema!
msg = aigenerate (schema, " Say hi! " ; model = " openhermes2.5-mistral " )
# [ Info: Tokens: 69 in 0.9 seconds
# AIMessage("Hello! How can I assist you today?")有關已註冊的常見模型(請參閱?PT.MODEL_REGISTRY ),您無需明確提供架構:
msg = aigenerate ( " Say hi! " ; model = " openhermes2.5-mistral " )我們還可以使用aiembed函數:
msg = aiembed (schema, " Embed me " , copy; model = " openhermes2.5-mistral " )
msg . content # 4096-element JSON3.Array{Float64...
msg = aiembed (schema, [ " Embed me " , " Embed me " ]; model = " openhermes2.5-mistral " )
msg . content # 4096×2 Matrix{Float64}:現在,您也可以使用aiscan為Ollama車型提供圖像!有關更多信息,請參見文檔。
如果您遇到錯誤,請檢查Ollama是否正在運行 - 請參閱下面的Ollama部分的設置指南。
Mistral模型長期以來一直在開源空間中占主導地位。它們現在可以通過其API提供,因此您可以將它們與提示tools.jl一起使用!
msg = aigenerate ( " Say hi! " ; model = " mistral-tiny " )一切都起作用,因為我們已經在PromptingTools.MODEL_REGISTRY中註冊了這些模型。model_registry!目前有4種型號可用: mistral-tiny , mistral-small , mistral-medium , mistral-embed 。
在引擎蓋下,我們使用專用的模式MistralOpenAISchema該模式利用大多數特定於OpenAI的代碼基礎,因此您始終可以將其作為第一個參數明確提供:
const PT = PromptingTools
msg = aigenerate (PT . MistralOpenAISchema (), " Say Hi! " ; model = " mistral-tiny " , api_key = ENV [ " MISTRAL_API_KEY " ])如您所見,我們可以通過Env或peferences.jl機制加載您的API密鑰(有關更多信息,請參見?PREFERENCES )。
但是Mistralai並不是唯一的!還有許多其他令人興奮的提供商,例如,Plplexity.ai,Fireworks.ai。只要它們與OpenAI API兼容(例如,帶有role和content鍵的messages ),您可以通過使用schema = CustomOpenAISchema() :
# Set your API key and the necessary base URL for the API
api_key = " ... "
prompt = " Say hi! "
msg = aigenerate (PT . CustomOpenAISchema (), prompt; model = " my_model " , api_key, api_kwargs = (; url = " http://localhost:8081 " ))如您所見,它也適用於您在計算機上可能運行的任何本地型號!
注意:目前,我們僅支持Mistralai和其他與OpenAI兼容的API的aigenerate和aiembed功能。我們計劃將來擴展支持。
確保將ANTHROPIC_API_KEY環境變量設置為API密鑰。
# cladeuh is alias for Claude 3 Haiku
ai " Say hi! " claudeh 預設模型的別名分別為claudeo , claudes和claudeh ,分別為Claude 3 Opus,Sonnet和Haiku。
相應的模式是AnthropicSchema 。
名稱中有幾個帶有XML的提示模板,這表明它們使用擬人友好的XML格式進行分離。使用aitemplates("XML")找到它們。
# cladeo is alias for Claude 3 Opus
msg = aigenerate (
:JuliaExpertAskXML , ask = " How to write a function to convert Date to Millisecond? " ,
model = " cladeo " )tbu ...
在示例/文件夾中找到更多示例。
該軟件包圍繞三個關鍵要素建造:
aigenerate , aiembed , aiclassify )為什麼設計?不同的API需要不同的及時格式。例如,OpenAI的API需要一系列具有role和content字段的字典,而Ollama的Zephyr-7B型號的API則需要使用一個大字符串和一個諸如<|im_start|>usernABC...<|im_end|>user的大字符串的api。為了在提示中分開部分,OpenAi更喜歡使用HTML標籤(<text> {{ ##Response <text>{{TEXT}}</text> )的擬人化表現更好。
該軟件包的啟發受到講師的啟發,並且巧妙地使用了函數調用API。
及時的模式
用於自定義邏輯的密鑰類型,用於為LLMS準備輸入並致電(通過多個調度)。
所有這些都是AbstractPromptSchema的子類型,每個任務功能都具有第一個位置的架構的通用簽名foo(schema::AbstractPromptSchema,...)
調度既定義為提示( render )的“渲染”和調用API( aigenerate )。
理想情況下,每個新接口將在單獨的llm_<interface>.jl文件(例如, llm_openai.jl )中定義。
消息
提示實際上是要完成的對話。
對話往往有三個關鍵參與者:系統(用於總體說明),用戶(輸入/數據)和AI助手(用於輸出)。我們為它們提供了SystemMessage類型,並為它們提供UserMessage和AIMessage類型。
給定提示架構和一條或多個消息,您可以render所得的對象,以將其饋入模型API。例如,為Openai
using PromptingTools : render, SystemMessage, UserMessage
PT = PromptingTools
schema = PT . OpenAISchema () # also accessible as the default schema `PT.PROMPT_SCHEMA`
conversation = conversation = [
SystemMessage ( " Act as a helpful AI assistant. Provide only the information that is requested. " ),
UserMessage ( " What is the capital of France? " )]
messages = render (schema, conversation)
# 2-element Vector{Dict{String, String}}:
# Dict("role" => "system", "content" => "Act as a helpful AI assistant. Provide only the information that is requested.")
# Dict("role" => "user", "content" => "What is the capital of France?")可以直接向OpenAI API提供此對象。
面向任務的功能
願望是為常見任務提供一組易於記錄的功能,因此所有這些功能都以ai...開始。所有功能均應返回帶有響應的輕型包裝器。目前,它只能是AIMessage (對於任何基於文本的響應)或通用DataMessage (對於嵌入等結構化數據)。
鑑於模型API及其參數的差異(例如OpenAI API與Ollama),任務函數在schema::AbstractPromptSchema上被派發為他們的第一個論點。
有關示例實現,請參見src/llm_openai.jl 。每個新界面將在單獨的llm_<interface>.jl文件中定義。
OpenAI的模型位於AI研究的最前沿,並為許多任務提供了強大的最先進功能。
將沒有或無法使用它(例如,隱私,成本等)。在這種情況下,您可以使用本地型號(例如Ollama)或其他API(例如,人類)。
注意:要開始使用Ollama.ai,請參見下面的Ollama部分的設置指南。
有很多選擇:
在撰寫本文時,OpenAI不使用API呼籲訓練他們的模型。
API
OpenAI不使用API提交和生成的數據來培訓OpenAI模型或改善OpenAI的服務產品。為了支持我們的模型的持續改進,您可以填寫此表格以選擇加入與我們共享您的數據。 - 如何使用數據來改善我們的模型
您始終可以仔細檢查OpenAI的最新信息我們如何使用您的數據頁面。
資源:
您可以通過註冊帳戶並訪問OpenAI網站的API部分來從OpenAI獲取API密鑰。
資源:
提示
始終設置支出限制!
OpenAI允許您直接在帳戶儀表板上設置支出限額,以防止意外費用。
一個好的開始可能是5美元的軟限額,硬限額為10美元 - 您可以隨時在本月晚些時候增加它。
資源:
如果您使用本地型號(例如,與Ollama一起使用),則是免費的。如果您使用任何商業API(例如,OpenAI),則可能是由“代幣”(子詞單元)付款的。
例如,一個簡單的請求,帶有簡單的問題和1個句子回复(“是語句xyz a正面評論”)將花費您〜$ 0.0001(即一百分之一))
值得支付嗎?
Genai是一種購買時間的方式!您可以每天支付美分以節省數十分鐘。
繼續上面的示例,想像一下您有一個帶有200條評論的桌子。現在,您可以使用LLM來解析其中的每個功能/檢查。假設每個電話的價格為$ 0.0001,您將為工作支付2美分,並節省30-60分鐘的時間!
資源:
這是OpenAI API密鑰的指南,但它適用於您可能需要的任何其他API鍵(例如, MISTRAL_API_KEY for Mistralai API)。
要將OpenAI API與提示tools.jl一起使用,請將API密鑰設置為環境變量:
ENV [ " OPENAI_API_KEY " ] = " your-api-key "作為一次性,您可以:
export OPENAI_API_KEY = <your key>setup.jl中(確保不要將其提交給github!)確保從設置變量的同一終端窗口啟動Julia。輕鬆檢查Julia,運行ENV["OPENAI_API_KEY"] ,您應該看到您的鑰匙!
更好的方法:
~/.zshrc )中。每次啟動終端時,它都會自動加載我們還支持preverences.jl,因此您可以簡單地運行: PromptingTools.set_preferences!("OPENAI_API_KEY"=>"your-api-key") ,它將在會話中堅持下去。要查看當前的首選項,請運行PromptingTools.get_preferences("OPENAI_API_KEY") 。
請注意不要將LocalPreferences.toml提交給github,因為它將顯示您的API鍵!
資源:
aigenerate中的API關鍵字參數( api_kwargs )有關更多信息,請參見OpenAI API參考。
要輕鬆從任何地方訪問,請在您的startup.jl中添加提示台(可以在~/.julia/config/startup.jl中找到)。
添加以下片段:
using PromptingTools
const PT = PromptingTools # to access unexported functions and types
現在,您可以從任何一個REPL會話中使用ai"Help me do X to achieve Y" !
提示Tools.jl的精神是允許您使用所需的任何模型,其中包括開源LLMS。最受歡迎和最容易設置的是Ollama.ai-請參閱下文。
Ollama運行了託管LLM的背景服務,您可以通過簡單的API訪問。當您使用一些不應在任何地方發送的敏感數據時,這特別有用。
安裝非常簡單,只需在此處下載最新版本即可。
安裝它後,只需啟動該應用程序,就可以開始使用!
要檢查是否正在運行,請轉到您的瀏覽器並打開127.0.0.1:11434 。您應該看到“ Ollama正在運行”的消息。另外,您可以在終端中運行ollama serve ,並且您會收到一條已經運行的消息。
Ollama庫中有許多型號可用,包括Llama2,Codellama,SqlCoder或我個人最喜歡的openhermes2.5-mistral 。
使用ollama pull <model_name>下載新型號(例如, ollama pull openhermes2.5-mistral )。
顯示當前使用ollama list的模型。
有關更多信息,請參見Ollama.ai。
微調是一種強大的技術,可以使模型適應您的特定用例(主要是格式/語法/任務)。它需要一個示例數據集,您現在可以通過提示tools.jl輕鬆生成!
您可以將任何對話(消息向量)保存到使用PT.save_conversation("filename.json", conversation)的文件中。
一旦到來,在單個.jsonl文件中創建一組共享依據的對話(常見的Finetuning格式)。使用PT.save_conversations("dataset.jsonl", [conversation1, conversation2, ...]) (請注意函數名稱中的複數“對話”)。
有關端到端登錄過程的示例,請查看我們的姐妹項目Juliallmleaderboard Finetuning實驗。它顯示了用Jarvislabs.ai和Axolotl進行半美元的固定過程。
這是我希望將來看到的功能列表(沒有特別的順序):
有關更多信息,貢獻或問題,請訪問提示tools.jl github存儲庫。
請注意,儘管提示Tools.jl旨在提供平穩的體驗,但它依賴於可能會改變的外部API。請繼續關注存儲庫以獲取更新和新功能。
感謝您選擇提示Tools.jl,以通過AI授權您的應用程序!