|
| 1 | +import Foundation |
| 2 | +import OpenAIService |
| 3 | + |
| 4 | +public final class RefineDocumentChain: Chain { |
| 5 | + public struct Input { |
| 6 | + var question: String |
| 7 | + var documents: [(document: Document, distance: Float)] |
| 8 | + } |
| 9 | + |
| 10 | + struct RefinementInput { |
| 11 | + var index: Int |
| 12 | + var totalCount: Int |
| 13 | + var question: String |
| 14 | + var previousAnswer: String? |
| 15 | + var document: String |
| 16 | + var distance: Float |
| 17 | + } |
| 18 | + |
| 19 | + public struct IntermediateAnswer: Decodable { |
| 20 | + public var answer: String |
| 21 | + public var usefulness: Double |
| 22 | + public var more: Bool |
| 23 | + |
| 24 | + public enum CodingKeys: String, CodingKey { |
| 25 | + case answer |
| 26 | + case usefulness |
| 27 | + case more |
| 28 | + } |
| 29 | + |
| 30 | + init(answer: String, usefulness: Double, more: Bool) { |
| 31 | + self.answer = answer |
| 32 | + self.usefulness = usefulness |
| 33 | + self.more = more |
| 34 | + } |
| 35 | + |
| 36 | + public init(from decoder: Decoder) throws { |
| 37 | + let container = try decoder.container(keyedBy: CodingKeys.self) |
| 38 | + answer = try container.decode(String.self, forKey: .answer) |
| 39 | + usefulness = (try? container.decode(Double.self, forKey: .usefulness)) ?? 0 |
| 40 | + more = (try? container.decode(Bool.self, forKey: .more)) ?? true |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + class FunctionProvider: ChatGPTFunctionProvider { |
| 45 | + var functionCallStrategy: FunctionCallStrategy? = .name("respond") |
| 46 | + var functions: [any ChatGPTFunction] = [RespondFunction()] |
| 47 | + } |
| 48 | + |
| 49 | + struct RespondFunction: ChatGPTFunction { |
| 50 | + typealias Arguments = IntermediateAnswer |
| 51 | + |
| 52 | + struct Result: ChatGPTFunctionResult { |
| 53 | + var botReadableContent: String { "" } |
| 54 | + } |
| 55 | + |
| 56 | + var reportProgress: (String) async -> Void = { _ in } |
| 57 | + |
| 58 | + var name: String = "respond" |
| 59 | + var description: String = "Respond with the refined answer" |
| 60 | + var argumentSchema: JSONSchemaValue { |
| 61 | + return [ |
| 62 | + .type: "object", |
| 63 | + .properties: [ |
| 64 | + "answer": [ |
| 65 | + .type: "string", |
| 66 | + .description: "The refined answer", |
| 67 | + ], |
| 68 | + "usefulness": [ |
| 69 | + .type: "number", |
| 70 | + .description: "How useful the page of document is in generating the answer, the higher the better. 0 to 10", |
| 71 | + ], |
| 72 | + "more": [ |
| 73 | + .type: "boolean", |
| 74 | + .description: "Whether you want to read the next page. The next page maybe less relevant to the question", |
| 75 | + ], |
| 76 | + ], |
| 77 | + .required: ["answer", "more", "usefulness"], |
| 78 | + ] |
| 79 | + } |
| 80 | + |
| 81 | + func prepare() async {} |
| 82 | + |
| 83 | + func call(arguments: Arguments) async throws -> Result { |
| 84 | + return Result() |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + func buildChatModel() -> ChatModelChain<RefinementInput> { |
| 89 | + .init( |
| 90 | + chatModel: OpenAIChat( |
| 91 | + configuration: UserPreferenceChatGPTConfiguration().overriding { |
| 92 | + $0.temperature = 0 |
| 93 | + $0.runFunctionsAutomatically = false |
| 94 | + }, |
| 95 | + memory: EmptyChatGPTMemory(), |
| 96 | + functionProvider: FunctionProvider(), |
| 97 | + stream: false |
| 98 | + ), |
| 99 | + promptTemplate: { input in [ |
| 100 | + .init( |
| 101 | + role: .system, |
| 102 | + content: { |
| 103 | + if let previousAnswer = input.previousAnswer { |
| 104 | + return """ |
| 105 | + The user will send you a question about a document, you must refine your previous answer to it only according to the document. |
| 106 | + Previous answer:### |
| 107 | + \(previousAnswer) |
| 108 | + ### |
| 109 | + Page \(input.index) of \(input.totalCount) of the document:### |
| 110 | + \(input.document) |
| 111 | + ### |
| 112 | + """ |
| 113 | + } else { |
| 114 | + return """ |
| 115 | + The user will send you a question about a document, you must answer it only according to the document. |
| 116 | + Page \(input.index) of \(input.totalCount) of the document:### |
| 117 | + \(input.document) |
| 118 | + ### |
| 119 | + """ |
| 120 | + } |
| 121 | + }() |
| 122 | + |
| 123 | + ), |
| 124 | + .init(role: .user, content: input.question), |
| 125 | + ] } |
| 126 | + ) |
| 127 | + } |
| 128 | + |
| 129 | + public init() {} |
| 130 | + |
| 131 | + public func callLogic( |
| 132 | + _ input: Input, |
| 133 | + callbackManagers: [CallbackManager] |
| 134 | + ) async throws -> String { |
| 135 | + var intermediateAnswer: IntermediateAnswer? |
| 136 | + |
| 137 | + for (index, document) in input.documents.enumerated() { |
| 138 | + if let intermediateAnswer, !intermediateAnswer.more { break } |
| 139 | + |
| 140 | + let output = try await buildChatModel().call( |
| 141 | + .init( |
| 142 | + index: index, |
| 143 | + totalCount: input.documents.count, |
| 144 | + question: input.question, |
| 145 | + previousAnswer: intermediateAnswer?.answer, |
| 146 | + document: document.document.pageContent, |
| 147 | + distance: document.distance |
| 148 | + ), |
| 149 | + callbackManagers: callbackManagers |
| 150 | + ) |
| 151 | + intermediateAnswer = extractAnswer(output) |
| 152 | + |
| 153 | + if let intermediateAnswer { |
| 154 | + callbackManagers.send( |
| 155 | + \.refineDocumentChainDidGenerateIntermediateAnswer, |
| 156 | + intermediateAnswer |
| 157 | + ) |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + return intermediateAnswer?.answer ?? "None" |
| 162 | + } |
| 163 | + |
| 164 | + public func parseOutput(_ output: String) -> String { |
| 165 | + return output |
| 166 | + } |
| 167 | + |
| 168 | + func extractAnswer(_ chatMessage: ChatMessage) -> IntermediateAnswer { |
| 169 | + if let functionCall = chatMessage.functionCall { |
| 170 | + do { |
| 171 | + let intermediateAnswer = try JSONDecoder().decode( |
| 172 | + IntermediateAnswer.self, |
| 173 | + from: functionCall.arguments.data(using: .utf8) ?? Data() |
| 174 | + ) |
| 175 | + return intermediateAnswer |
| 176 | + } catch { |
| 177 | + let intermediateAnswer = IntermediateAnswer( |
| 178 | + answer: functionCall.arguments, |
| 179 | + usefulness: 0, |
| 180 | + more: true |
| 181 | + ) |
| 182 | + return intermediateAnswer |
| 183 | + } |
| 184 | + } |
| 185 | + return .init(answer: chatMessage.content ?? "", usefulness: 0, more: true) |
| 186 | + } |
| 187 | +} |
| 188 | + |
| 189 | +public extension CallbackEvents { |
| 190 | + struct RefineDocumentChainDidGenerateIntermediateAnswer: CallbackEvent { |
| 191 | + public let info: RefineDocumentChain.IntermediateAnswer |
| 192 | + } |
| 193 | + |
| 194 | + var refineDocumentChainDidGenerateIntermediateAnswer: |
| 195 | + RefineDocumentChainDidGenerateIntermediateAnswer.Type |
| 196 | + { |
| 197 | + RefineDocumentChainDidGenerateIntermediateAnswer.self |
| 198 | + } |
| 199 | +} |
| 200 | + |
0 commit comments