-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathguidelines.go
More file actions
211 lines (175 loc) · 5.85 KB
/
Copy pathguidelines.go
File metadata and controls
211 lines (175 loc) · 5.85 KB
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package cogito
import (
"fmt"
"slices"
"github.com/mudler/cogito/prompt"
"github.com/mudler/cogito/structures"
"github.com/mudler/xlog"
"github.com/sashabaranov/go-openai"
)
type Guidelines []Guideline
type Guideline struct {
Condition string
Action string
Tools Tools
}
type GuidelineMetadataList []GuidelineMetadata
type GuidelineMetadata struct {
Condition string
Action string
Tools []string
}
func (g Guidelines) ToMetadata() GuidelineMetadataList {
metadata := GuidelineMetadataList{}
for _, guideline := range g {
toolsNames := []string{}
for _, tool := range guideline.Tools {
toolsNames = append(toolsNames, tool.Tool().Function.Name)
}
metadata = append(metadata, GuidelineMetadata{
Condition: guideline.Condition,
Action: guideline.Action,
Tools: toolsNames,
})
}
return metadata
}
func GetRelevantGuidelines(llm LLM, guidelines Guidelines, fragment Fragment, opts ...Option) (Guidelines, error) {
o := defaultOptions()
o.Apply(opts...)
prompter := o.prompts.GetPrompt(prompt.PromptGuidelinesType)
guidelineOption := struct {
Guidelines GuidelineMetadataList
Context string
AdditionalContext string
}{
Guidelines: guidelines.ToMetadata(),
Context: fragment.String(),
}
if o.deepContext && fragment.ParentFragment != nil {
guidelineOption.AdditionalContext = fragment.ParentFragment.AllFragmentsStrings()
}
guidelinePrompt, err := prompter.Render(guidelineOption)
if err != nil {
return Guidelines{}, fmt.Errorf("failed to render tool reasoner prompt: %w", err)
}
guidelineConv := NewEmptyFragment().AddMessage("user", guidelinePrompt)
guidelineResult, err := llm.Ask(o.context, guidelineConv)
if err != nil {
return Guidelines{}, fmt.Errorf("failed to ask LLM for guidelines: %w", err)
}
guidelineExtractionPrompt, err := o.prompts.GetPrompt(prompt.PromptGuidelinesExtractionType).Render(struct{}{})
if err != nil {
return Guidelines{}, fmt.Errorf("failed to render guidelines extraction prompt: %w", err)
}
structure, guides := structures.StructureGuidelines()
err = guidelineResult.AddMessage("user", guidelineExtractionPrompt).ExtractStructure(o.context, llm, structure)
if err != nil {
return Guidelines{}, fmt.Errorf("failed to extract guidelines: %w", err)
}
g := Guidelines{}
for _, guideline := range guides.Guidelines {
for ii, gg := range guidelines {
// -1 because the guidelines in the prompts starts at 1
if guideline-1 == ii {
g = append(g, gg)
}
}
}
return g, nil
}
// findUnguidedTools identifies tools that are not in any guideline's Tools list
func findUnguidedTools(tools Tools, guidelines Guidelines) Tools {
// Build a set of tool names that are in guidelines
guidedToolNames := make(map[string]bool)
for _, guideline := range guidelines {
for _, tool := range guideline.Tools {
toolName := tool.Tool().Function.Name
guidedToolNames[toolName] = true
}
}
// Find tools not in the set
unguidedTools := Tools{}
for _, tool := range tools {
toolName := tool.Tool().Function.Name
if !guidedToolNames[toolName] {
unguidedTools = append(unguidedTools, tool)
}
}
return unguidedTools
}
// createVirtualGuidelinesFromAllTools creates virtual guidelines for all tools
// When no guidelines exist, uses the tool description directly as the condition
func createVirtualGuidelinesFromAllTools(tools Tools) Guidelines {
virtualGuidelines := Guidelines{}
for _, tool := range tools {
toolFunc := tool.Tool().Function
if toolFunc == nil || toolFunc.Description == "" {
continue
}
virtualGuidelines = append(virtualGuidelines, Guideline{
Condition: toolFunc.Description,
Action: "Use this tool",
Tools: Tools{tool},
})
}
return virtualGuidelines
}
func usableTools(llm LLM, fragment Fragment, opts ...Option) (Tools, Guidelines, []openai.ChatCompletionMessage, error) {
o := defaultOptions()
o.Apply(opts...)
tools := slices.Clone(o.tools)
guidelines := slices.Clone(o.guidelines)
prompts := []openai.ChatCompletionMessage{}
for _, session := range o.mcpSessions {
mcpTools, err := mcpToolsFromTransport(o.context, session, o.mcpToolFilter)
if err != nil {
// A single MCP session that is momentarily unavailable (e.g. a client
// mid-reconnect or being closed/rebuilt by a config reload — the go-sdk
// surfaces this as "client is closing: hanging GET: failed to reconnect")
// must not abort the whole turn. Skip this session's tools/prompts for
// this turn; they come back once the session is healthy again.
xlog.Warn("cogito: skipping MCP session whose tools could not be listed", "error", err)
continue
}
for _, tool := range mcpTools {
tools = append(tools, tool)
}
if o.mcpPrompts {
toolPrompts, err := mcpPromptsFromTransport(o.context, session, o.mcpArgs)
if err != nil {
xlog.Warn("cogito: skipping MCP session whose prompts could not be listed", "error", err)
continue
}
prompts = append(prompts, toolPrompts...)
}
}
// Handle guided tools option
if o.guidedTools {
if len(o.guidelines) == 0 {
// Scenario B: No guidelines exist - create virtual guidelines for ALL tools
guidelines = createVirtualGuidelinesFromAllTools(tools)
tools = Tools{}
} else {
// Scenario A: Guidelines exist - create virtual guidelines for unguided tools
unguidedTools := findUnguidedTools(tools, o.guidelines)
if len(unguidedTools) > 0 {
guidelines = append(guidelines, createVirtualGuidelinesFromAllTools(unguidedTools)...)
}
}
}
if o.strictGuidelines {
tools = Tools{}
}
if len(guidelines) > 0 {
var err error
guidelines, err = GetRelevantGuidelines(llm, guidelines, fragment, opts...)
if err != nil {
return Tools{}, Guidelines{}, nil, fmt.Errorf("failed to get relevant guidelines: %w", err)
}
for _, guideline := range guidelines {
tools = append(tools, guideline.Tools...)
}
}
return tools, guidelines, prompts, nil
}