Skip to content

Commit

Permalink
parameter config Follow session
Browse files Browse the repository at this point in the history
  • Loading branch information
CoderLineChan committed Apr 20, 2023
1 parent 5bcde83 commit bfd719a
Show file tree
Hide file tree
Showing 9 changed files with 278 additions and 49 deletions.
8 changes: 8 additions & 0 deletions OSXChatGPT/OSXChatGPT.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@
CB27657529D33D7A00897E0E /* AIPromptInputView.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB27657429D33D7A00897E0E /* AIPromptInputView.swift */; };
CB28A52229C07BE500F0286A /* KeyboardMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB28A52129C07BE500F0286A /* KeyboardMonitor.swift */; };
CB28A52829C1569900F0286A /* ThinkingAnimationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB28A52729C1569900F0286A /* ThinkingAnimationView.swift */; };
CB2D438929F0183A007742AE /* ChatGPT+CoreDataClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB2D438729F0183A007742AE /* ChatGPT+CoreDataClass.swift */; };
CB2D438A29F0183A007742AE /* ChatGPT+CoreDataProperties.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB2D438829F0183A007742AE /* ChatGPT+CoreDataProperties.swift */; };
CB2F971F29CE12B6004EBD96 /* MarkdownUI in Frameworks */ = {isa = PBXBuildFile; productRef = CB2F971E29CE12B6004EBD96 /* MarkdownUI */; };
CB2F972029CE1ADC004EBD96 /* OSXChatGPT.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = CBC4B0FD29B8BF9600650296 /* OSXChatGPT.xcdatamodeld */; };
CB2F972229CED6AE004EBD96 /* ChatRoomInputView.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB2F972129CED6AE004EBD96 /* ChatRoomInputView.swift */; };
Expand Down Expand Up @@ -132,6 +134,8 @@
CB27657429D33D7A00897E0E /* AIPromptInputView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AIPromptInputView.swift; sourceTree = "<group>"; };
CB28A52129C07BE500F0286A /* KeyboardMonitor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = KeyboardMonitor.swift; sourceTree = "<group>"; };
CB28A52729C1569900F0286A /* ThinkingAnimationView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThinkingAnimationView.swift; sourceTree = "<group>"; };
CB2D438729F0183A007742AE /* ChatGPT+CoreDataClass.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ChatGPT+CoreDataClass.swift"; sourceTree = "<group>"; };
CB2D438829F0183A007742AE /* ChatGPT+CoreDataProperties.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ChatGPT+CoreDataProperties.swift"; sourceTree = "<group>"; };
CB2F972129CED6AE004EBD96 /* ChatRoomInputView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatRoomInputView.swift; sourceTree = "<group>"; };
CB2F972729CEFB65004EBD96 /* ChatRoomToolBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatRoomToolBar.swift; sourceTree = "<group>"; };
CB53A3BC29D48C8F00A5B8FC /* Prompt+CoreDataClass.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Prompt+CoreDataClass.swift"; sourceTree = "<group>"; };
Expand Down Expand Up @@ -332,6 +336,8 @@
CBC4B11429B8CB1B00650296 /* Models */ = {
isa = PBXGroup;
children = (
CB2D438729F0183A007742AE /* ChatGPT+CoreDataClass.swift */,
CB2D438829F0183A007742AE /* ChatGPT+CoreDataProperties.swift */,
CB1F015D29EB9D05009CF942 /* Message+CoreDataClass.swift */,
CB1F015E29EB9D05009CF942 /* Message+CoreDataProperties.swift */,
CB1F015729EAFBF5009CF942 /* MessageText+CoreDataClass.swift */,
Expand Down Expand Up @@ -463,6 +469,7 @@
182B437329BC5D1B00F06778 /* CoreDataManager.swift in Sources */,
188FB46729C1FA9700E3C18F /* EidtSessionRemarkView.swift in Sources */,
CB27656A29D1E65100897E0E /* Conversation+CoreDataProperties.swift in Sources */,
CB2D438929F0183A007742AE /* ChatGPT+CoreDataClass.swift in Sources */,
CB1F014229E99B5E009CF942 /* CharacterSet+Contains.swift in Sources */,
CB1F014629E99B5E009CF942 /* String+IsNumber.swift in Sources */,
182B436629BC5C8700F06778 /* View.swift in Sources */,
Expand Down Expand Up @@ -498,6 +505,7 @@
CBD5AB6629E6EFE3007B6625 /* MarkdownView.swift in Sources */,
CBD5AB6B29E707F0007B6625 /* MarkdownTokenType.swift in Sources */,
182B437529BC5D1B00F06778 /* ChatGPTManager.swift in Sources */,
CB2D438A29F0183A007742AE /* ChatGPT+CoreDataProperties.swift in Sources */,
CB2F972229CED6AE004EBD96 /* ChatRoomInputView.swift in Sources */,
CB1F014529E99B5E009CF942 /* String+Removing.swift in Sources */,
CB2F972829CEFB65004EBD96 /* ChatRoomToolBar.swift in Sources */,
Expand Down
103 changes: 70 additions & 33 deletions OSXChatGPT/OSXChatGPT/DataProvider/ChatGPTManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,27 @@ struct ChatGPTResponse {

}
struct ChatGPTRequest {
let model: ChatGPTModel
let temperature: Double = 0.5
let gpt: ChatGPT?
var model: ChatGPTModel = .gpt35turbo
var temperature: String = "1"
let messages: [Message]
let answerType: ChatGPTAnswerType//是否流式回答
let contextCount: ChatGPTContext
var contextCount: ChatGPTContext = .context3
let systemMsg: String?//修饰语
let apiKey: String

init(gpt: ChatGPT?, messages: [Message], answerType: ChatGPTAnswerType, apiKey: String, systemMsg: String?) {
self.gpt = gpt
if let chatG = gpt {
self.model = chatG.modelType
self.contextCount = chatG.context
self.temperature = chatG.temperatureValue
}
self.messages = messages
self.answerType = answerType
self.systemMsg = systemMsg
self.apiKey = apiKey
}

// static let completions = URL(string: "https://api.openai.com/v1/completions")!
// static let images = URL(string: "https://api.openai.com/v1/images/generations")!
Expand All @@ -47,7 +62,7 @@ struct ChatGPTRequest {

}
}
let apiKey: String

var headers: [String: String] {
let dict = ["Content-Type": "application/json",
"Authorization": "Bearer \(apiKey)"]
Expand Down Expand Up @@ -76,8 +91,10 @@ struct ChatGPTRequest {
let par = [
"model": model.value,
"messages": msg,
"stream": answerType.valueBool
"stream": answerType.valueBool,
"temperature": Float(temperature) ?? 1
] as [String : Any]
print("请求参数:\(par)")
return par
}
}
Expand All @@ -100,8 +117,8 @@ enum ChatGPTAnswerType: CaseIterable, ToolBarMenuProtocol {
return [.stream, .oneTime]
}
}
enum ChatGPTContext: CaseIterable, ToolBarMenuProtocol {
case context0
enum ChatGPTContext: Int16, CaseIterable, ToolBarMenuProtocol {
case context0 = 0
case context1
case context2
case context3
Expand All @@ -116,30 +133,10 @@ enum ChatGPTContext: CaseIterable, ToolBarMenuProtocol {

var value: String {
switch self {
case .context0:
return "0"
case .context1:
return "1"
case .context2:
return "2"
case .context3:
return "3"
case .context4:
return "4"
case .context5:
return "5"
case .context6:
return "6"
case .context7:
return "7"
case .context8:
return "8"
case .context9:
return "9"
case .context10:
return "10"
case .infinite:
return "999"
default:
return "\(self.rawValue)"
}
}
var valyeInt: Int {
Expand All @@ -160,7 +157,7 @@ enum ChatGPTContext: CaseIterable, ToolBarMenuProtocol {
.infinite]
}
}
enum ChatGPTModel: CaseIterable, ToolBarMenuProtocol {
enum ChatGPTModel: Int16, CaseIterable, ToolBarMenuProtocol {
var value: String {
switch self {
case .textDavinci001:
Expand Down Expand Up @@ -278,13 +275,12 @@ extension ChatGPTManager {


}
func askChatGPTStream(messages: [Message], prompt: String?, complete:((ChatGPTResponse) -> ())?) {
func askChatGPTStream(messages: [Message], prompt: String?, chatGpt: ChatGPT?, complete:((ChatGPTResponse) -> ())?) {
if chatGPTSpeaking == true {
return
}
chatGPTSpeaking = true
let request = ChatGPTRequest(model: model, messages: messages, answerType: answerType, contextCount: askContextCount, systemMsg: prompt, apiKey: apiKey)

let request = ChatGPTRequest(gpt: chatGpt, messages: messages, answerType: answerType, apiKey: apiKey, systemMsg: prompt)
Task {
do {
let stream = try await httpClient.postStream(chatRequest: request)
Expand Down Expand Up @@ -319,6 +315,47 @@ extension ChatGPTManager {
}
}
}
// func askChatGPTStream(messages: [Message], prompt: String?, complete:((ChatGPTResponse) -> ())?) {
// if chatGPTSpeaking == true {
// return
// }
// chatGPTSpeaking = true
// let request = ChatGPTRequest(model: model, messages: messages, answerType: answerType, contextCount: askContextCount, systemMsg: prompt, apiKey: apiKey)
//
// Task {
// do {
// let stream = try await httpClient.postStream(chatRequest: request)
// let res = ChatGPTResponse(request: request ,state: .replyStart, text: "", stream: "")
// await tempMessagePool.reset()
// if self.chatGPTSpeaking == false {
// return
// }
// complete?(res)
// var newMsg: String = ""
// for try await line in stream {
// await tempMessagePool.append(line: line)
// let newMessage = await tempMessagePool.message
// print("回复1:\(line)")
// print("回复2:\(newMessage)")
// newMsg += newMessage
// let res = ChatGPTResponse(request: request ,state: .replying, text: newMessage, stream: line)
// complete?(res)
// }
// let re = ChatGPTResponse(request: request ,state: .replyFinish, text: newMsg, stream: newMsg)
// await tempMessagePool.reset()
// self.chatGPTSpeaking = false
// complete?(re)
// }catch let err {
// await tempMessagePool.reset()
// if let error = err as? HTTPError {
// let res = ChatGPTResponse(request: request ,state: .replyFial, text: error.message, stream: "")
// self.chatGPTSpeaking = false
// complete?(res)
// }
//
// }
// }
// }

/// 提问
func askChatGPT(messages: [Message], complete:(([String: Any]?, String?) -> ())?) {
Expand Down
46 changes: 38 additions & 8 deletions OSXChatGPT/OSXChatGPT/DataProvider/ViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,21 @@ import Splash
init() {
fetchConversations()
}
func checkGPT(sesstion: Conversation?) {
if sesstion?.chatGPT == nil {
var gpt = ChatGPT(context: CoreDataManager.shared.container.viewContext)
configChatGPT(&gpt)
sesstion?.chatGPT = gpt
if let idx = conversations.firstIndex(where: {$0.sesstionId == sesstion?.sesstionId}) {
conversations[idx] = sesstion!
}
CoreDataManager.shared.saveData()
}
}
func updateConversation(sesstion: Conversation?) {
CoreDataManager.shared.saveData()
}

func updateConversation(sesstionId: String, prompt: Prompt) {
var con = fetchConversation(sesstionId: sesstionId)
if con == nil {
Expand All @@ -62,6 +77,7 @@ import Splash
}
con!.updateData = Date()
con?.prompt = prompt

CoreDataManager.shared.saveData()
if let index = conversations.firstIndex(where: { $0.sesstionId == sesstionId}) {
conversations[index] = con!
Expand Down Expand Up @@ -100,22 +116,25 @@ import Splash
conversations[index] = con!
}
}
class func addNewConversation() -> Conversation {
let con = Conversation(context: CoreDataManager.shared.container.viewContext)
con.sesstionId = createSesstionId()
con.id = UUID()
con.updateData = Date()
return con
}
//**这里是一个Fake会话, 不需要存入数据库
func addNewConversation() -> Conversation {
let con = Conversation(context: CoreDataManager.shared.container.viewContext)
con.sesstionId = createSesstionId()
con.id = UUID()
con.updateData = Date()
if con.chatGPT == nil {
var gpt = ChatGPT(context: CoreDataManager.shared.container.viewContext)
configChatGPT(&gpt)
con.chatGPT = gpt
}
currentConversation = con
return con
}
func configChatGPT(_ gpt: inout ChatGPT) {
gpt.temperature = 1
gpt.context = .context3
gpt.modelType = .gpt35turbo
}
func addConversation() {
let con = Conversation(context: CoreDataManager.shared.container.viewContext)
con.sesstionId = createSesstionId()
Expand Down Expand Up @@ -293,7 +312,7 @@ extension ViewModel {
self.showStopAnswerBtn = true
}
var stream: String = ""
ChatGPTManager.shared.askChatGPTStream(messages: messages, prompt: prompt) { rsp in
ChatGPTManager.shared.askChatGPTStream(messages: messages, prompt: prompt, chatGpt: currentConversation?.chatGPT) { rsp in
if rsp.request.answerType == .stream {
isFeedback = true
//流式请求
Expand Down Expand Up @@ -394,6 +413,9 @@ extension ViewModel {
newMsg?.id = UUID()
newMsg?.msgType = .fialMsg
newMsg?.createdDate = Date()
if self.currentConversation?.sesstionId == sesstionId {
self.messages.append(newMsg!)
}
}
newMsg?.text = rsp.text
//失败
Expand Down Expand Up @@ -607,6 +629,14 @@ extension ViewModel {
let remove = aa.filter { $0.lastMessage == nil && $0.prompt == nil }
CoreDataManager.shared.delete(objects: remove)
aa.removeAll { $0.lastMessage == nil && $0.prompt == nil}
aa.forEach { con in
if con.chatGPT == nil {
var gpt = ChatGPT(context: CoreDataManager.shared.container.viewContext)
configChatGPT(&gpt)
con.chatGPT = gpt
}
}
CoreDataManager.shared.saveData()
conversations = aa
}
private func fetchConversation(sesstionId: String) -> Conversation? {
Expand Down
34 changes: 34 additions & 0 deletions OSXChatGPT/OSXChatGPT/Models/ChatGPT+CoreDataClass.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//
// ChatGPT+CoreDataClass.swift
// OSXChatGPT
//
// Created by CoderChan on 2023/4/19.
//
//

import Foundation
import CoreData


public class ChatGPT: NSManagedObject {
var modelType: ChatGPTModel {
get {
return ChatGPTModel(rawValue: model) ?? .gpt432k0314
}
set {
model = newValue.rawValue
}
}
var context: ChatGPTContext {
get {
return ChatGPTContext(rawValue: contextCount) ?? .context3
}
set {
contextCount = newValue.rawValue
}
}
var temperatureValue: String {
let formattedValue = String(format: "%.1f", temperature)
return formattedValue
}
}
28 changes: 28 additions & 0 deletions OSXChatGPT/OSXChatGPT/Models/ChatGPT+CoreDataProperties.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//
// ChatGPT+CoreDataProperties.swift
// OSXChatGPT
//
// Created by CoderChan on 2023/4/19.
//
//

import Foundation
import CoreData


extension ChatGPT {

@nonobjc public class func fetchRequest() -> NSFetchRequest<ChatGPT> {
return NSFetchRequest<ChatGPT>(entityName: "ChatGPT")
}

@NSManaged public var contextCount: Int16
@NSManaged public var model: Int16
@NSManaged public var temperature: Double
@NSManaged public var id: UUID?

}

extension ChatGPT : Identifiable {

}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ extension Conversation {
@NSManaged public var updateData: Date?
@NSManaged public var lastMessage: Message?
@NSManaged public var prompt: Prompt?
@NSManaged public var chatGPT: ChatGPT?

}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="21513" systemVersion="22A380" minimumToolsVersion="Automatic" sourceLanguage="Swift" userDefinedModelVersionIdentifier="">
<entity name="ChatGPT" representedClassName=".ChatGPT" syncable="YES">
<attribute name="contextCount" optional="YES" attributeType="Integer 16" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO"/>
<attribute name="model" optional="YES" attributeType="Integer 16" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="temperature" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>
</entity>
<entity name="Conversation" representedClassName=".Conversation" syncable="YES">
<attribute name="id" attributeType="UUID" usesScalarValueType="NO"/>
<attribute name="remark" optional="YES" attributeType="String"/>
<attribute name="sesstionId" attributeType="String"/>
<attribute name="updateData" optional="YES" attributeType="Date" usesScalarValueType="NO"/>
<relationship name="chatGPT" optional="YES" maxCount="1" deletionRule="Nullify" destinationEntity="ChatGPT"/>
<relationship name="lastMessage" optional="YES" maxCount="1" deletionRule="Nullify" destinationEntity="Message"/>
<relationship name="prompt" optional="YES" maxCount="1" deletionRule="Nullify" destinationEntity="Prompt" inverseName="sesstion" inverseEntity="Prompt"/>
</entity>
Expand Down
Loading

0 comments on commit bfd719a

Please sign in to comment.