-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathprovider.go
283 lines (247 loc) · 6.39 KB
/
provider.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
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package ollama
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/charmbracelet/log"
"github.com/mark3labs/mcphost/pkg/history"
"github.com/mark3labs/mcphost/pkg/llm"
api "github.com/ollama/ollama/api"
)
func boolPtr(b bool) *bool {
return &b
}
// Provider implements the Provider interface for Ollama
type Provider struct {
client *api.Client
model string
}
// NewProvider creates a new Ollama provider
func NewProvider(model string) (*Provider, error) {
client, err := api.ClientFromEnvironment()
if err != nil {
return nil, err
}
return &Provider{
client: client,
model: model,
}, nil
}
func (p *Provider) CreateMessage(
ctx context.Context,
prompt string,
messages []llm.Message,
tools []llm.Tool,
) (llm.Message, error) {
log.Debug("creating message",
"prompt", prompt,
"num_messages", len(messages),
"num_tools", len(tools))
// Convert generic messages to Ollama format
ollamaMessages := make([]api.Message, 0, len(messages)+1)
// Add existing messages
for _, msg := range messages {
// Handle tool responses
if msg.IsToolResponse() {
var content string
// Handle HistoryMessage format
if historyMsg, ok := msg.(*history.HistoryMessage); ok {
for _, block := range historyMsg.Content {
if block.Type == "tool_result" {
content = block.Text
break
}
}
}
// If no content found yet, try standard content extraction
if content == "" {
content = msg.GetContent()
}
if content == "" {
continue
}
ollamaMsg := api.Message{
Role: "tool",
Content: content,
}
ollamaMessages = append(ollamaMessages, ollamaMsg)
continue
}
// Skip completely empty messages (no content and no tool calls)
if msg.GetContent() == "" && len(msg.GetToolCalls()) == 0 {
continue
}
ollamaMsg := api.Message{
Role: msg.GetRole(),
Content: msg.GetContent(),
}
// Add tool calls for assistant messages
if msg.GetRole() == "assistant" {
for _, call := range msg.GetToolCalls() {
if call.GetName() != "" {
args := call.GetArguments()
ollamaMsg.ToolCalls = append(
ollamaMsg.ToolCalls,
api.ToolCall{
Function: api.ToolCallFunction{
Name: call.GetName(),
Arguments: args,
},
},
)
}
}
}
ollamaMessages = append(ollamaMessages, ollamaMsg)
}
// Add the new prompt if not empty
if prompt != "" {
ollamaMessages = append(ollamaMessages, api.Message{
Role: "user",
Content: prompt,
})
}
// Convert tools to Ollama format
ollamaTools := make([]api.Tool, len(tools))
for i, tool := range tools {
ollamaTools[i] = api.Tool{
Type: "function",
Function: api.ToolFunction{
Name: tool.Name,
Description: tool.Description,
Parameters: struct {
Type string `json:"type"`
Required []string `json:"required"`
Properties map[string]struct {
Type string `json:"type"`
Description string `json:"description"`
Enum []string `json:"enum,omitempty"`
} `json:"properties"`
}{
Type: tool.InputSchema.Type,
Required: tool.InputSchema.Required,
Properties: convertProperties(tool.InputSchema.Properties),
},
},
}
}
var response api.Message
log.Debug("creating message",
"prompt", prompt,
"num_messages", len(messages),
"num_tools", len(tools))
log.Debug("sending messages to Ollama",
"messages", ollamaMessages,
"num_tools", len(tools))
err := p.client.Chat(ctx, &api.ChatRequest{
Model: p.model,
Messages: ollamaMessages,
Tools: ollamaTools,
Stream: boolPtr(false),
}, func(r api.ChatResponse) error {
if r.Done {
response = r.Message
}
return nil
})
if err != nil {
return nil, err
}
return &OllamaMessage{Message: response}, nil
}
func (p *Provider) SupportsTools() bool {
// Check if model supports function calling
resp, err := p.client.Show(context.Background(), &api.ShowRequest{
Model: p.model,
})
if err != nil {
return false
}
return strings.Contains(resp.Modelfile, "<tools>")
}
func (p *Provider) Name() string {
return "ollama"
}
func (p *Provider) CreateToolResponse(
toolCallID string,
content interface{},
) (llm.Message, error) {
log.Debug("creating tool response",
"tool_call_id", toolCallID,
"content_type", fmt.Sprintf("%T", content),
"content", content)
contentStr := ""
switch v := content.(type) {
case string:
contentStr = v
log.Debug("using string content directly")
default:
bytes, err := json.Marshal(v)
if err != nil {
log.Error("failed to marshal tool response",
"error", err,
"content", content)
return nil, fmt.Errorf("error marshaling tool response: %w", err)
}
contentStr = string(bytes)
log.Debug("marshaled content to JSON string",
"result", contentStr)
}
// Create message with explicit tool role
msg := &OllamaMessage{
Message: api.Message{
Role: "tool", // Explicitly set role to "tool"
Content: contentStr,
// No need to set ToolCalls for a tool response
},
ToolCallID: toolCallID,
}
log.Debug("created tool response message",
"role", msg.GetRole(),
"content", msg.GetContent(),
"tool_call_id", msg.GetToolResponseID(),
"raw_content", contentStr)
return msg, nil
}
// Helper function to convert properties to Ollama's format
func convertProperties(props map[string]interface{}) map[string]struct {
Type string `json:"type"`
Description string `json:"description"`
Enum []string `json:"enum,omitempty"`
} {
result := make(map[string]struct {
Type string `json:"type"`
Description string `json:"description"`
Enum []string `json:"enum,omitempty"`
})
for name, prop := range props {
if propMap, ok := prop.(map[string]interface{}); ok {
prop := struct {
Type string `json:"type"`
Description string `json:"description"`
Enum []string `json:"enum,omitempty"`
}{
Type: getString(propMap, "type"),
Description: getString(propMap, "description"),
}
// Handle enum if present
if enumRaw, ok := propMap["enum"].([]interface{}); ok {
for _, e := range enumRaw {
if str, ok := e.(string); ok {
prop.Enum = append(prop.Enum, str)
}
}
}
result[name] = prop
}
}
return result
}
// Helper function to safely get string values from map
func getString(m map[string]interface{}, key string) string {
if v, ok := m[key].(string); ok {
return v
}
return ""
}