gollm
자신의 AI Golems를 구축하는 데 도움이되는 GO 패키지입니다. 신비로운 전설의 골렘이 신성한 말로 생겨 났 듯이, gollm
큰 언어 모델 (LLM)의 힘을 사용하여 AI 창조물에 생명을 불어 넣을 수 있도록합니다. 이 패키지는 다양한 LLM 제공 업체와의 상호 작용을 단순화하고 간소화하여 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 )
신속한 엔지니어링 :
WithContext()
, WithDirectives()
와 같은 옵션이있는 NewPrompt()
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()
사용하십시오. 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에 따라 라이센스가 부여됩니다. 자세한 내용은 라이센스 파일을 참조하십시오.