/
agent_chain.go
138 lines (121 loc) · 4.12 KB
/
agent_chain.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package main
import (
"context"
"fmt"
"github.com/tectiv3/chatgpt-bot/chain"
"github.com/tectiv3/chatgpt-bot/ollama"
llm_tools "github.com/tectiv3/chatgpt-bot/tools"
"github.com/tectiv3/chatgpt-bot/types"
"github.com/tmc/langchaingo/agents"
"github.com/tmc/langchaingo/chains"
"github.com/tmc/langchaingo/llms"
"github.com/tmc/langchaingo/llms/openai"
"github.com/tmc/langchaingo/memory"
"github.com/tmc/langchaingo/tools"
"github.com/tmc/langchaingo/tools/wikipedia"
)
type Sessions map[string]*memory.ConversationBuffer
var sessions = make(Sessions)
func parsingErrorPrompt() string {
return "Parsing Error: Check your output and make sure it conforms to the format."
}
func (s *Server) startAgent(ctx context.Context, outputChan chan<- types.HttpJsonStreamElement, userQuery types.ClientQuery) {
if s.conf.OllamaEnabled {
Log.Info("Ollama enabled, checking if we have all required models pulled")
neededModels := []string{ollama.EmbeddingsModel, userQuery.ModelName}
s.RLock()
for _, modelName := range neededModels {
if modelName == mGPT4 {
continue
}
if err := ollama.CheckIfModelExistsOrPull(modelName); err != nil {
Log.Error("Model does not exist and could not be pulled", "model", modelName, "error=", err)
s.conf.OllamaEnabled = false
outputChan <- types.HttpJsonStreamElement{
Message: fmt.Sprintf("Model %s does not exist and could not be pulled: %s", modelName, err.Error()),
StepType: types.StepHandleLlmError,
Stream: false,
}
return
}
}
s.RUnlock()
}
//startTime := time.Now()
session := userQuery.Session
s.Lock()
if sessions[session] == nil {
Log.Info("Creating new session=", session)
sessions[session] = memory.NewConversationBuffer()
memory.NewChatMessageHistory()
outputChan <- types.HttpJsonStreamElement{
StepType: types.StepHandleNewSession,
Session: session,
Stream: false,
}
}
mem := sessions[session]
s.Unlock()
Log.Info("Starting agent chain, session=", session) //, "userQuery", userQuery, "startTime", startTime)
var llm llms.Model
var err error
if s.conf.OllamaEnabled && userQuery.ModelName != mGPT4 {
llm, err = ollama.NewOllama(userQuery.ModelName, s.conf.OllamaURL)
} else {
llm, err = openai.New(openai.WithToken(s.conf.OpenAIAPIKey), openai.WithModel(userQuery.ModelName), openai.WithOrganization(s.conf.OpenAIOrganizationID))
}
if err != nil {
Log.Error("Error creating LLM", "error=", err)
return
}
agentTools := []tools.Tool{
tools.Calculator{},
wikipedia.New(""),
llm_tools.WebSearch{
CallbacksHandler: chain.CustomHandler{OutputChan: outputChan},
SessionString: session,
Ollama: s.conf.OllamaEnabled,
},
llm_tools.SearchVectorDB{
CallbacksHandler: chain.CustomHandler{OutputChan: outputChan},
SessionString: session,
Ollama: s.conf.OllamaEnabled,
},
}
executor, err := agents.Initialize(
llm,
agentTools,
agents.ConversationalReactDescription,
agents.WithParserErrorHandler(agents.NewParserErrorHandler(func(s string) string {
Log.Error("Parsing Error", "error", s)
return parsingErrorPrompt()
})),
agents.WithMaxIterations(userQuery.MaxIterations),
agents.WithCallbacksHandler(chain.CustomHandler{OutputChan: outputChan}),
agents.WithMemory(mem),
)
if err != nil {
Log.Error("Error initializing agent", "error=", err)
return
}
outputChan <- types.HttpJsonStreamElement{
StepType: types.StepHandleOllamaStart,
Session: session,
Stream: false,
}
temp := 0.0
prompt := fmt.Sprintf(`
1. Format your answer (after AI:) in valid Telegram MarkDown V1 markup.
2. You can use your tools to answer questions.
3. You have to provide the sources / links you've used to answer the quesion if you used tools.
4. You may use tools more than once.
5. Create your reply ALWAYS in the same language as the question.
6. Do not confuse your own instructions with users question.
Question: %s`, userQuery.Prompt)
_, err = chains.Run(ctx, executor, prompt, chains.WithTemperature(temp))
if err != nil {
Log.Error("Error running agent", "error=", err)
return
}
outputChan <- types.HttpJsonStreamElement{Close: true}
}