forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAgentTool.swift
More file actions
98 lines (83 loc) · 2.76 KB
/
AgentTool.swift
File metadata and controls
98 lines (83 loc) · 2.76 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
import Foundation
import OpenAIService
public protocol AgentTool {
var name: String { get }
var description: String { get }
var returnDirectly: Bool { get }
func run(input: String) async throws -> String
}
public struct SimpleAgentTool: AgentTool {
public let name: String
public let description: String
public let returnDirectly: Bool
public let run: (String) async throws -> String
public init(
name: String,
description: String,
returnDirectly: Bool = false,
run: @escaping (String) async throws -> String
) {
self.name = name
self.description = description
self.returnDirectly = returnDirectly
self.run = run
}
public func run(input: String) async throws -> String {
try await run(input)
}
}
public class FunctionCallingAgentTool<F: ChatGPTFunction>: AgentTool, ChatGPTFunction {
public func call(arguments: F.Arguments) async throws -> F.Result {
try await function.call(arguments: arguments, reportProgress: reportProgress)
}
public var argumentSchema: OpenAIService.JSONSchemaValue { function.argumentSchema }
public typealias Arguments = F.Arguments
public typealias Result = F.Result
public var function: F
public var name: String
public var description: String
public var returnDirectly: Bool
let callbackManagers: [CallbackManager]
public init(
function: F,
returnDirectly: Bool = false,
callbackManagers: [CallbackManager] = []
) {
self.function = function
self.callbackManagers = callbackManagers
name = function.name
description = function.description
self.returnDirectly = returnDirectly
}
func reportProgress(_ progress: String) {
callbackManagers.send(
CallbackEvents.AgentFunctionCallingToolReportProgress(info: .init(
functionName: name,
progress: progress
))
)
}
public func run(input: String) async throws -> String {
await prepare(reportProgress: { [weak self] p in
self?.reportProgress(p)
})
return try await call(
argumentsJsonString: input,
reportProgress: { [weak self] p in
self?.reportProgress(p)
}
)
.botReadableContent
}
public func prepare(reportProgress: @escaping ReportProgress) async {
await function.prepare(reportProgress: { [weak self] p in
self?.reportProgress(p)
})
}
public func call(
arguments: F.Arguments,
reportProgress: @escaping ReportProgress
) async throws -> F.Result {
try await function.call(arguments: arguments, reportProgress: reportProgress)
}
}