forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAgentExecutor.swift
More file actions
228 lines (202 loc) · 7.75 KB
/
AgentExecutor.swift
File metadata and controls
228 lines (202 loc) · 7.75 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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import Foundation
public actor AgentExecutor<InnerAgent: Agent>: Chain
where InnerAgent.Input == String, InnerAgent.Output: AgentOutputParsable
{
public typealias Input = String
public struct Output {
public typealias FinalOutput = AgentFinish<InnerAgent.Output>.ReturnValue
public let finalOutput: FinalOutput
let intermediateSteps: [AgentAction]
}
let agent: InnerAgent
let tools: [String: AgentTool]
let maxIteration: Int?
let maxExecutionTime: Double?
var earlyStopHandleType: AgentEarlyStopHandleType
var now: () -> Date = { Date() }
var isCancelled = false
var initialSteps: [AgentAction]
public init(
agent: InnerAgent,
tools: [AgentTool],
maxIteration: Int? = 10,
maxExecutionTime: Double? = nil,
earlyStopHandleType: AgentEarlyStopHandleType = .generate,
initialSteps: [AgentAction] = []
) {
self.agent = agent
self.tools = tools.reduce(into: [:]) { $0[$1.name] = $1 }
self.maxIteration = maxIteration
self.maxExecutionTime = maxExecutionTime
self.earlyStopHandleType = earlyStopHandleType
self.initialSteps = initialSteps
}
public func callLogic(
_ input: Input,
callbackManagers: [CallbackManager]
) async throws -> Output {
try agent.validateTools(tools: Array(tools.values))
let startTime = now().timeIntervalSince1970
var iterations = 0
var intermediateSteps: [AgentAction] = initialSteps
func shouldContinue() -> Bool {
if isCancelled { return false }
if let maxIteration = maxIteration, iterations >= maxIteration {
return false
}
if let maxExecutionTime = maxExecutionTime,
now().timeIntervalSince1970 - startTime > maxExecutionTime
{
return false
}
return true
}
while shouldContinue() {
try Task.checkCancellation()
let nextStepOutput = try await takeNextStep(
input: input,
intermediateSteps: intermediateSteps,
callbackManagers: callbackManagers
)
try Task.checkCancellation()
switch nextStepOutput {
case let .finish(finish):
return end(
output: finish,
intermediateSteps: intermediateSteps,
callbackManagers: callbackManagers
)
case let .actions(actions):
intermediateSteps.append(contentsOf: actions)
if actions.count == 1,
let action = actions.first,
let toolFinish = getToolFinish(action: action)
{
return end(
output: toolFinish,
intermediateSteps: intermediateSteps,
callbackManagers: callbackManagers
)
}
}
iterations += 1
}
let output = try await agent.returnStoppedResponse(
input: input,
earlyStoppedHandleType: earlyStopHandleType,
intermediateSteps: intermediateSteps,
callbackManagers: callbackManagers
)
return end(
output: output,
intermediateSteps: intermediateSteps,
callbackManagers: callbackManagers
)
}
public nonisolated func parseOutput(_ output: Output) -> String {
switch output.finalOutput {
case let .unstructured(error): return error
case let .structured(output): return output.botReadableContent
}
}
public func cancel() {
isCancelled = true
earlyStopHandleType = .force
}
}
struct InvalidToolError: Error {}
extension AgentExecutor {
func end(
output: AgentFinish<InnerAgent.Output>,
intermediateSteps: [AgentAction],
callbackManagers: [CallbackManager]
) -> Output {
for callbackManager in callbackManagers {
callbackManager.send(CallbackEvents.AgentDidFinish(info: output))
}
let finalOutput = output.returnValue
return .init(finalOutput: finalOutput, intermediateSteps: intermediateSteps)
}
/// Plan the scratch pad and let the agent decide what to do next
func takeNextStep(
input: Input,
intermediateSteps: [AgentAction],
callbackManagers: [CallbackManager]
) async throws -> AgentNextStep<InnerAgent.Output> {
let output = try await agent.plan(
input: input,
intermediateSteps: intermediateSteps,
callbackManagers: callbackManagers
)
switch output {
// If the output says finish, then return the output immediately.
case .finish: return output
// If the output contains actions, run them, and append the results to the scratch pad.
case let .actions(actions):
let completedActions = try await withThrowingTaskGroup(of: AgentAction.self) {
taskGroup in
for action in actions {
callbackManagers.send(CallbackEvents.AgentActionDidStart(info: action))
if action.observation != nil {
taskGroup.addTask { action }
continue
}
guard let tool = tools[action.toolName] else { throw InvalidToolError() }
taskGroup.addTask {
do {
let observation = try await tool.run(input: action.toolInput)
return action.observationAvailable(observation)
} catch {
let observation = error.localizedDescription
return action.observationAvailable(observation)
}
}
}
var completedActions = [AgentAction]()
for try await action in taskGroup {
try Task.checkCancellation()
completedActions.append(action)
callbackManagers.send(CallbackEvents.AgentActionDidEnd(info: action))
}
return completedActions
}
return .actions(completedActions)
}
}
func getToolFinish(action: AgentAction) -> AgentFinish<InnerAgent.Output>? {
guard let tool = tools[action.toolName] else { return nil }
guard tool.returnDirectly else { return nil }
do {
let result = try InnerAgent.Output.parse(action.observation ?? "")
return .init(returnValue: .structured(result), log: action.observation ?? "")
} catch {
return .init(
returnValue: .unstructured(action.observation ?? "no observation"),
log: action.observation ?? ""
)
}
}
}
// MARK: - AgentOutputParsable
public protocol AgentOutputParsable {
static func parse(_ string: String) throws -> Self
var botReadableContent: String { get }
}
extension String: AgentOutputParsable {
public static func parse(_ string: String) throws -> String { string }
public var botReadableContent: String { self }
}
extension Int: AgentOutputParsable {
public static func parse(_ string: String) throws -> Int {
guard let int = Int(string) else { return 0 }
return int
}
public var botReadableContent: String { String(self) }
}
extension Double: AgentOutputParsable {
public static func parse(_ string: String) throws -> Double {
guard let double = Double(string) else { return 0 }
return double
}
public var botReadableContent: String { String(self) }
}