gollm
是一個GO包,旨在幫助您構建自己的AI Golems。就像神秘的傳奇人物被神聖的單詞栩栩如生一樣, gollm
可以使用大語言模型(LLMS)的力量使您能夠將生命帶入您的AI創作中。該軟件包簡化了與各種LLM提供商的交互,並為AI工程師和開發人員提供了自己的數字僕人,為AI工程師和開發人員提供了統一,靈活和強大的界面。
文件
ChainOfThought
預構建功能進行複雜的推理任務。gollm
可以處理各種AI驅動的任務,包括:
ChainOfThought
函數逐步分析複雜問題。go get github.com/teilomillet/gollm
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/teilomillet/gollm"
)
func main () {
// Load API key from environment variable
apiKey := os . Getenv ( "OPENAI_API_KEY" )
if apiKey == "" {
log . Fatalf ( "OPENAI_API_KEY environment variable is not set" )
}
// Create a new LLM instance with custom configuration
llm , err := gollm . NewLLM (
gollm . SetProvider ( "openai" ),
gollm . SetModel ( "gpt-4o-mini" ),
gollm . SetAPIKey ( apiKey ),
gollm . SetMaxTokens ( 200 ),
gollm . SetMaxRetries ( 3 ),
gollm . SetRetryDelay ( time . Second * 2 ),
gollm . SetLogLevel ( gollm . LogLevelInfo ),
)
if err != nil {
log . Fatalf ( "Failed to create LLM: %v" , err )
}
ctx := context . Background ()
// Create a basic prompt
prompt := gollm . NewPrompt ( "Explain the concept of 'recursion' in programming." )
// Generate a response
response , err := llm . Generate ( ctx , prompt )
if err != nil {
log . Fatalf ( "Failed to generate text: %v" , err )
}
fmt . Printf ( "Response: n %s n " , response )
}
## Quick Reference
Here 's a quick reference guide for the most commonly used functions and options in the `gollm` package :
### LLM Creation and Configuration
`` `go
llm, err := gollm.NewLLM(
gollm.SetProvider("openai"),
gollm.SetModel("gpt-4"),
gollm.SetAPIKey("your-api-key"),
gollm.SetMaxTokens(100),
gollm.SetTemperature(0.7),
gollm.SetMemory(4096),
)
prompt := gollm . NewPrompt ( "Your prompt text here" ,
gollm . WithContext ( "Additional context" ),
gollm . WithDirectives ( "Be concise" , "Use examples" ),
gollm . WithOutput ( "Expected output format" ),
gollm . WithMaxLength ( 300 ),
)
response , err := llm . Generate ( ctx , prompt )
response , err := tools . ChainOfThought ( ctx , llm , "Your question here" )
optimizer := optimizer . NewPromptOptimizer ( llm , initialPrompt , taskDescription ,
optimizer . WithCustomMetrics ( /* custom metrics */ ),
optimizer . WithRatingSystem ( "numerical" ),
optimizer . WithThreshold ( 0.8 ),
)
optimizedPrompt , err := optimizer . OptimizePrompt ( ctx )
results , err := tools . CompareModels ( ctx , promptText , validateFunc , configs ... )
gollm
軟件包提供了一系列高級功能來增強您的AI應用程序:
創建具有多個組件的複雜提示:
prompt := gollm . NewPrompt ( "Explain the concept of recursion in programming." ,
gollm . WithContext ( "The audience is beginner programmers." ),
gollm . WithDirectives (
"Use simple language and avoid jargon." ,
"Provide a practical example." ,
"Explain potential pitfalls and how to avoid them." ,
),
gollm . WithOutput ( "Structure your response with sections: Definition, Example, Pitfalls, Best Practices." ),
gollm . WithMaxLength ( 300 ),
)
response , err := llm . Generate ( ctx , prompt )
if err != nil {
log . Fatalf ( "Failed to generate explanation: %v" , err )
}
fmt . Printf ( "Explanation of Recursion: n %s n " , response )
使用ChainOfThought
功能進行逐步推理:
question := "What is the result of 15 * 7 + 22?"
response , err := tools . ChainOfThought ( ctx , llm , question )
if err != nil {
log . Fatalf ( "Failed to perform chain of thought: %v" , err )
}
fmt . Printf ( "Chain of Thought: n %s n " , response )
直接從文件加載示例:
examples , err := utils . ReadExamplesFromFile ( "examples.txt" )
if err != nil {
log . Fatalf ( "Failed to read examples: %v" , err )
}
prompt := gollm . NewPrompt ( "Generate a similar example:" ,
gollm . WithExamples ( examples ... ),
)
response , err := llm . Generate ( ctx , prompt )
if err != nil {
log . Fatalf ( "Failed to generate example: %v" , err )
}
fmt . Printf ( "Generated Example: n %s n " , response )
創建可重複使用的提示模板,以始終如一的提示生成:
// Create a new prompt template
template := gollm . NewPromptTemplate (
"AnalysisTemplate" ,
"A template for analyzing topics" ,
"Provide a comprehensive analysis of {{.Topic}}. Consider the following aspects: n " +
"1. Historical context n " +
"2. Current relevance n " +
"3. Future implications" ,
gollm . WithPromptOptions (
gollm . WithDirectives (
"Use clear and concise language" ,
"Provide specific examples where appropriate" ,
),
gollm . WithOutput ( "Structure your analysis with clear headings for each aspect." ),
),
)
// Use the template to create a prompt
data := map [ string ] interface {}{
"Topic" : "artificial intelligence in healthcare" ,
}
prompt , err := template . Execute ( data )
if err != nil {
log . Fatalf ( "Failed to execute template: %v" , err )
}
// Generate a response using the created prompt
response , err := llm . Generate ( ctx , prompt )
if err != nil {
log . Fatalf ( "Failed to generate response: %v" , err )
}
fmt . Printf ( "Analysis: n %s n " , response )
確保您的LLM輸出為有效的JSON格式:
prompt := gollm . NewPrompt ( "Analyze the pros and cons of remote work." ,
gollm . WithOutput ( "Respond in JSON format with 'topic', 'pros', 'cons', and 'conclusion' fields." ),
)
response , err := llm . Generate ( ctx , prompt , gollm . WithJSONSchemaValidation ())
if err != nil {
log . Fatalf ( "Failed to generate valid analysis: %v" , err )
}
var result AnalysisResult
if err := json . Unmarshal ([] byte ( response ), & result ); err != nil {
log . Fatalf ( "Failed to parse response: %v" , err )
}
fmt . Printf ( "Analysis: %+v n " , result )
使用PromptOptimizer
自動完善並改善您的提示:
initialPrompt := gollm . NewPrompt ( "Write a short story about a robot learning to love." )
taskDescription := "Generate a compelling short story that explores the theme of artificial intelligence developing emotions."
optimizerInstance := optimizer . NewPromptOptimizer (
llm ,
initialPrompt ,
taskDescription ,
optimizer . WithCustomMetrics (
optimizer. Metric { Name : "Creativity" , Description : "How original and imaginative the story is" },
optimizer. Metric { Name : "Emotional Impact" , Description : "How well the story evokes feelings in the reader" },
),
optimizer . WithRatingSystem ( "numerical" ),
optimizer . WithThreshold ( 0.8 ),
optimizer . WithVerbose (),
)
optimizedPrompt , err := optimizerInstance . OptimizePrompt ( ctx )
if err != nil {
log . Fatalf ( "Optimization failed: %v" , err )
}
fmt . Printf ( "Optimized Prompt: %s n " , optimizedPrompt . Input )
比較來自不同LLM提供商或模型的響應:
configs := [] * gollm. Config {
{
Provider : "openai" ,
Model : "gpt-4o-mini" ,
APIKey : os . Getenv ( "OPENAI_API_KEY" ),
MaxTokens : 500 ,
},
{
Provider : "anthropic" ,
Model : "claude-3-5-sonnet-20240620" ,
APIKey : os . Getenv ( "ANTHROPIC_API_KEY" ),
MaxTokens : 500 ,
},
{
Provider : "groq" ,
Model : "llama-3.1-70b-versatile" ,
APIKey : os . Getenv ( "GROQ_API_KEY" ),
MaxTokens : 500 ,
},
}
promptText := "Tell me a joke about programming. Respond in JSON format with 'setup' and 'punchline' fields."
validateJoke := func ( joke map [ string ] interface {}) error {
if joke [ "setup" ] == "" || joke [ "punchline" ] == "" {
return fmt . Errorf ( "joke must have both a setup and a punchline" )
}
return nil
}
results , err := tools . CompareModels ( context . Background (), promptText , validateJoke , configs ... )
if err != nil {
log . Fatalf ( "Error comparing models: %v" , err )
}
fmt . Println ( tools . AnalyzeComparisonResults ( results ))
使內存能夠維護多個交互的上下文:
llm , err := gollm . NewLLM (
gollm . SetProvider ( "openai" ),
gollm . SetModel ( "gpt-3.5-turbo" ),
gollm . SetAPIKey ( os . Getenv ( "OPENAI_API_KEY" )),
gollm . SetMemory ( 4096 ), // Enable memory with a 4096 token limit
)
if err != nil {
log . Fatalf ( "Failed to create LLM: %v" , err )
}
ctx := context . Background ()
// First interaction
prompt1 := gollm . NewPrompt ( "What's the capital of France?" )
response1 , err := llm . Generate ( ctx , prompt1 )
if err != nil {
log . Fatalf ( "Failed to generate response: %v" , err )
}
fmt . Printf ( "Response 1: %s n " , response1 )
// Second interaction, referencing the first
prompt2 := gollm . NewPrompt ( "What's the population of that city?" )
response2 , err := llm . Generate ( ctx , prompt2 )
if err != nil {
log . Fatalf ( "Failed to generate response: %v" , err )
}
fmt . Printf ( "Response 2: %s n " , response2 )
及時工程:
NewPrompt()
與WithContext()
, WithDirectives()
和WithOutput()
之類的選項來創建結構良好的提示。 prompt := gollm . NewPrompt ( "Your main prompt here" ,
gollm . WithContext ( "Provide relevant context" ),
gollm . WithDirectives ( "Be concise" , "Use examples" ),
gollm . WithOutput ( "Specify expected output format" ),
)
使用及時的模板:
PromptTemplate
對象。 template := gollm . NewPromptTemplate (
"CustomTemplate" ,
"A template for custom prompts" ,
"Generate a {{.Type}} about {{.Topic}}" ,
gollm . WithPromptOptions (
gollm . WithDirectives ( "Be creative" , "Use vivid language" ),
gollm . WithOutput ( "Your {{.Type}}:" ),
),
)
利用預構建功能:
ChainOfThought()
。 response , err := tools . ChainOfThought ( ctx , llm , "Your complex question here" )
與示例一起工作:
ReadExamplesFromFile()
從文件中加載示例以進行一致的輸出。 examples , err := utils . ReadExamplesFromFile ( "examples.txt" )
if err != nil {
log . Fatalf ( "Failed to read examples: %v" , err )
}
實施結構化輸出:
WithJSONSchemaValidation()
一起使用以確保有效的JSON輸出。 response , err := llm . Generate ( ctx , prompt , gollm . WithJSONSchemaValidation ())
優化提示:
PromptOptimizer
自動完善提示。 optimizer := optimizer . NewPromptOptimizer ( llm , initialPrompt , taskDescription ,
optimizer . WithCustomMetrics (
optimizer. Metric { Name : "Relevance" , Description : "How relevant the response is to the task" },
),
optimizer . WithRatingSystem ( "numerical" ),
optimizer . WithThreshold ( 0.8 ),
)
比較模型性能:
CompareModels()
評估不同的模型或提供商。 results , err := tools . CompareModels ( ctx , promptText , validateFunc , configs ... )
實現上下文交互的內存:
llm , err := gollm . NewLLM (
gollm . SetProvider ( "openai" ),
gollm . SetModel ( "gpt-3.5-turbo" ),
gollm . SetMemory ( 4096 ),
)
錯誤處理並進行檢索:
llm , err := gollm . NewLLM (
gollm . SetMaxRetries ( 3 ),
gollm . SetRetryDelay ( time . Second * 2 ),
)
安全API密鑰處理:
llm , err := gollm . NewLLM (
gollm . SetAPIKey ( os . Getenv ( "OPENAI_API_KEY" )),
)
查看我們的示例目錄以獲取更多用法示例,包括:
gollm
積極維護並在持續發展中。通過最近的重構,我們簡化了代碼庫,使其更簡單,更容易為新貢獻者訪問。我們歡迎社區的捐款和反饋。
gollm
建立在務實的極簡主義和前瞻性簡單的哲學上:
構建必要的內容:我們在需要的情況下添加功能,以避免投機性發展。
首先簡單:在實現其目的的同時,加法應該很簡單。
未來兼容:我們考慮當前的變化如何影響未來的發展。
可讀性計數:代碼應清楚且不言自明。
模塊化設計:每個組件應該做得很好。
我們歡迎與我們的哲學保持一致的貢獻!無論您是修復錯誤,改進文檔還是提出新功能,都要感謝您的努力。
開始:
感謝您幫助使gollm
更好!
該項目已根據Apache許可證2.0的許可 - 有關詳細信息,請參見許可證文件。