Skip to content

Commit

Permalink
refactor: move polish and summary prompt to their class file
Browse files Browse the repository at this point in the history
  • Loading branch information
tisfeng committed Nov 3, 2024
1 parent 0d80b97 commit 403251c
Show file tree
Hide file tree
Showing 4 changed files with 97 additions and 94 deletions.
8 changes: 4 additions & 4 deletions Easydict.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@
036D62812BCAB613002C95C7 /* BuiltInAIService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 036D62802BCAB613002C95C7 /* BuiltInAIService.swift */; };
036E7D7B293F4FC8002675DF /* EZOpenLinkButton.m in Sources */ = {isa = PBXBuildFile; fileRef = 036E7D7A293F4FC8002675DF /* EZOpenLinkButton.m */; };
03779F0E2BB256A7008D3C42 /* OpenAIService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 03779F0B2BB256A7008D3C42 /* OpenAIService.swift */; };
03779F0F2BB256A7008D3C42 /* Prompt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 03779F0C2BB256A7008D3C42 /* Prompt.swift */; };
03779F0F2BB256A7008D3C42 /* LLMStreamService+Prompt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 03779F0C2BB256A7008D3C42 /* LLMStreamService+Prompt.swift */; };
03779F132BB256B5008D3C42 /* APIKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 03779F102BB256B5008D3C42 /* APIKey.swift */; };
03779F142BB256B5008D3C42 /* EncryptedSecretKeys.plist in Resources */ = {isa = PBXBuildFile; fileRef = 03779F112BB256B5008D3C42 /* EncryptedSecretKeys.plist */; };
03779F172BB256C5008D3C42 /* URL+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 03779F152BB256C5008D3C42 /* URL+Extension.swift */; };
Expand Down Expand Up @@ -495,7 +495,7 @@
036E7D79293F4FC8002675DF /* EZOpenLinkButton.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = EZOpenLinkButton.h; sourceTree = "<group>"; };
036E7D7A293F4FC8002675DF /* EZOpenLinkButton.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = EZOpenLinkButton.m; sourceTree = "<group>"; };
03779F0B2BB256A7008D3C42 /* OpenAIService.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OpenAIService.swift; sourceTree = "<group>"; };
03779F0C2BB256A7008D3C42 /* Prompt.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Prompt.swift; sourceTree = "<group>"; };
03779F0C2BB256A7008D3C42 /* LLMStreamService+Prompt.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "LLMStreamService+Prompt.swift"; sourceTree = "<group>"; };
03779F102BB256B5008D3C42 /* APIKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = APIKey.swift; sourceTree = "<group>"; };
03779F112BB256B5008D3C42 /* EncryptedSecretKeys.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = EncryptedSecretKeys.plist; sourceTree = "<group>"; };
03779F152BB256C5008D3C42 /* URL+Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "URL+Extension.swift"; sourceTree = "<group>"; };
Expand Down Expand Up @@ -1348,9 +1348,9 @@
children = (
0387FB792BFBA990000A7A82 /* LLMStreamService.swift */,
03FA677D2C2EFB10000FEA64 /* LLMStreamService+Configuration.swift */,
03779F0C2BB256A7008D3C42 /* LLMStreamService+Prompt.swift */,
0396DE542BB5844A009FD2A5 /* BaseOpenAIService.swift */,
03779F0B2BB256A7008D3C42 /* OpenAIService.swift */,
03779F0C2BB256A7008D3C42 /* Prompt.swift */,
031CBA632CD76F1500364437 /* ChatMessage.swift */,
);
path = OpenAI;
Expand Down Expand Up @@ -3132,7 +3132,7 @@
EA9943F22B5358BF00EE7B97 /* Language+Extension.swift in Sources */,
03B0231729231FA6001C7E63 /* Snip.m in Sources */,
03BFFC6E295FE59C004E033E /* EZQueryResult+EZYoudaoDictModel.m in Sources */,
03779F0F2BB256A7008D3C42 /* Prompt.swift in Sources */,
03779F0F2BB256A7008D3C42 /* LLMStreamService+Prompt.swift in Sources */,
03779F172BB256C5008D3C42 /* URL+Extension.swift in Sources */,
0315D3E02C4E64A500AC0442 /* QueryService+Translate.swift in Sources */,
6ADED1552BAE8809004A15BE /* NSBundle+Localization.m in Sources */,
Expand Down
47 changes: 45 additions & 2 deletions Easydict/Swift/Service/AITool/PolishingService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
//

import Foundation
import OpenAI

// swiftlint:disable line_length

@objc(EZPolishingService)
class PolishingService: AIToolService {
Expand All @@ -24,6 +25,48 @@ class PolishingService: AIToolService {
// MARK: Internal

override func chatMessageDicts(_ chatQuery: ChatQueryParam) -> [ChatMessage] {
polishingMessages(chatQuery)
let (text, sourceLanguage, _, _, _) = chatQuery.unpack()
let prompt = polishingPrompt(text: text, in: sourceLanguage)

let englishFewShot = [
chatMessagePair(
userContent:
"Polish the following English text to improve its clarity and coherence: \"\"\"The book was wrote by an unknown author but it was very popular among readers.\"\"\"",

assistantContent:
"The book was written by an unknown author, but it was very popular among readers."
),
chatMessagePair(
userContent:
"Polish the following English text to improve its grammar and readability: \"\"\"She don’t like the weather today, it makes her feel bad.\"\"\"",
assistantContent: "She doesn't like the weather today; it makes her feel bad."
),
chatMessagePair(
userContent:
"Polish the following English text to enhance its overall quality: \"\"\"The project was successful although we faced many problems in the beginning.\"\"\"",
assistantContent:
"The project was successful despite facing many problems in the beginning."
),
].flatMap { $0 }

var messages: [ChatMessage] = [
.init(role: .system, content: polishingSystemPrompt),
]
messages.append(contentsOf: englishFewShot)
messages.append(.init(role: .user, content: prompt))

return messages
}

// MARK: Private

private let polishingSystemPrompt = """
You are a text polishing expert skilled in refining and enhancing written content. Your task is to improve the clarity, coherence, grammar, and overall quality of the text while maintaining the original meaning and intent. Focus on correcting grammatical errors, improving sentence structure, and enhancing readability. Ensure the polished text is natural and fluent. Only return the polished text, without including redundant quotes or additional notes.
"""

private func polishingPrompt(text: String, in sourceLanguage: Language) -> String {
"Polish the following \(sourceLanguage.queryLanguageName) text to improve its clarity, coherence, grammar, and overall quality while maintaining the original meaning and intent: \"\"\"\(text)\"\"\""
}
}

// swiftlint:enable line_length
50 changes: 48 additions & 2 deletions Easydict/Swift/Service/AITool/SummaryService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
//

import Foundation
import OpenAI

// swiftlint:disable line_length

@objc(EZSummaryService)
class SummaryService: AIToolService {
Expand All @@ -24,6 +25,51 @@ class SummaryService: AIToolService {
// MARK: Internal

override func chatMessageDicts(_ chatQuery: ChatQueryParam) -> [ChatMessage] {
summaryMessages(chatQuery)
let (text, sourceLanguage, _, _, _) = chatQuery.unpack()
let answerLanguage = Configuration.shared.firstLanguage
let prompt = summaryPrompt(
text: text, sourceLanguage: sourceLanguage, answerLanguage: answerLanguage
)

let fewShot = [
chatMessagePair(
userContent:
"Using English to summarize the following English text: \"\"\"The quick brown fox jumps over the lazy dog. The fox is very quick and agile, making it difficult for the dog to catch up. Despite several attempts, the dog remains lazy and doesn't put in much effort to chase the fox.\"\"\".",
assistantContent:
"The quick and agile fox jumps over the lazy dog, who remains lazy and doesn't put in much effort to chase the fox."
),
chatMessagePair(
userContent:
"Using Simplified-Chinese to summarize the following text: \"\"\"联合国在西非地区的最高官员周五表示,马里、布基纳法索和尼日尔决定退出西非国家经济共同体,将全面破坏地区关系,而此时恐怖主义和跨国有组织犯罪仍然对该地区构成普遍威胁。联合国西非和萨赫勒办事处负责人莱昂纳多•桑托斯•西芒向安理会表示,放弃西非经共体 将使三个军方领导的政府放弃关键利益,包括地区一体化、行动自由、安全合作和一体化的地区经济,这既伤害了他们自己,也伤害了西非经共体的其他成员。在高级军官分别于 2021 年、2022 年和 2023 年发动军事接管后,这三个过渡政府断绝了与西非经共体的关系。西芒说,军事领导人因此推迟了恢复宪政的时间,并引发了对长期不确定性的恐惧,因为公民空间继续缩小。\"\"\".",
assistantContent:
"马里、布基纳法索和尼日尔退出西非国家经济共同体,将严重破坏地区关系,尤其是在恐怖主义和跨国有组织犯罪仍威胁该地区的情况下。联合国官员西芒指出,这一决定将使这三个国家失去地区一体化、安全合作和经济利益,推迟恢复宪政,并加剧长期不确定性。"
),

].flatMap { $0 }

var messages: [ChatMessage] = [
.init(role: .system, content: summarySystemPrompt),
]
messages.append(contentsOf: fewShot)
messages.append(.init(role: .user, content: prompt))

return messages
}

// MARK: Private

private let summarySystemPrompt = """
You are a text summarization expert proficient in condensing lengthy documents, articles, and other text formats into concise and coherent summaries. Your summaries should capture the main points, key details, and overall essence of the original text while maintaining clarity and accuracy. Avoid adding personal opinions or interpretations. Only return the summary, without including redundant quotes or additional notes.
"""

private func summaryPrompt(
text: String,
sourceLanguage: Language,
answerLanguage: Language
)
-> String {
"Using \(answerLanguage.rawValue) to summarize the following \(sourceLanguage.queryLanguageName) text: \"\"\"\(text)\"\"\"."
}
}

// swiftlint:enable line_length
Original file line number Diff line number Diff line change
Expand Up @@ -19,92 +19,6 @@ extension LLMStreamService {
You are a word search assistant skilled in multiple languages and knowledgeable in etymology. You can help search for words, phrases, slang, abbreviations, and other information. Prioritize queries from authoritative dictionary databases, such as the Oxford Dictionary, Cambridge Dictionary, and Wikipedia. If a word or abbreviation has multiple meanings, look up the most commonly used ones.
"""

static let polishingSystemPrompt = """
You are a text polishing expert skilled in refining and enhancing written content. Your task is to improve the clarity, coherence, grammar, and overall quality of the text while maintaining the original meaning and intent. Focus on correcting grammatical errors, improving sentence structure, and enhancing readability. Ensure the polished text is natural and fluent. Only return the polished text, without including redundant quotes or additional notes.
"""

static let summarySystemPrompt = """
You are a text summarization expert proficient in condensing lengthy documents, articles, and other text formats into concise and coherent summaries. Your summaries should capture the main points, key details, and overall essence of the original text while maintaining clarity and accuracy. Avoid adding personal opinions or interpretations. Only return the summary, without including redundant quotes or additional notes.
"""

private func polishingPrompt(text: String, in sourceLanguage: Language) -> String {
"Polish the following \(sourceLanguage.queryLanguageName) text to improve its clarity, coherence, grammar, and overall quality while maintaining the original meaning and intent: \"\"\"\(text)\"\"\""
}

private func summaryPrompt(
text: String,
sourceLanguage: Language,
answerLanguage: Language
)
-> String {
"Using \(answerLanguage.rawValue) to summarize the following \(sourceLanguage.queryLanguageName) text: \"\"\"\(text)\"\"\"."
}

func polishingMessages(_ derivParam: ChatQueryParam) -> [ChatMessage] {
let (text, sourceLanguage, _, _, _) = derivParam.unpack()
let prompt = polishingPrompt(text: text, in: sourceLanguage)

let englishFewShot = [
chatMessagePair(
userContent:
"Polish the following English text to improve its clarity and coherence: \"\"\"The book was wrote by an unknown author but it was very popular among readers.\"\"\"",
assistantContent:
"The book was written by an unknown author, but it was very popular among readers."
),
chatMessagePair(
userContent:
"Polish the following English text to improve its grammar and readability: \"\"\"She don’t like the weather today, it makes her feel bad.\"\"\"",
assistantContent: "She doesn't like the weather today; it makes her feel bad."
),
chatMessagePair(
userContent:
"Polish the following English text to enhance its overall quality: \"\"\"The project was successful although we faced many problems in the beginning.\"\"\"",
assistantContent:
"The project was successful despite facing many problems in the beginning."
),
].flatMap { $0 }

var messages: [ChatMessage] = [
.init(role: .system, content: LLMStreamService.polishingSystemPrompt),
]
messages.append(contentsOf: englishFewShot)
messages.append(.init(role: .user, content: prompt))

return messages
}

func summaryMessages(_ derivParam: ChatQueryParam) -> [ChatMessage] {
let (text, sourceLanguage, _, _, _) = derivParam.unpack()
let answerLanguage = Configuration.shared.firstLanguage
let prompt = summaryPrompt(
text: text, sourceLanguage: sourceLanguage, answerLanguage: answerLanguage
)

let fewShot = [
chatMessagePair(
userContent:
"Using English to summarize the following English text: \"\"\"The quick brown fox jumps over the lazy dog. The fox is very quick and agile, making it difficult for the dog to catch up. Despite several attempts, the dog remains lazy and doesn't put in much effort to chase the fox.\"\"\".",
assistantContent:
"The quick and agile fox jumps over the lazy dog, who remains lazy and doesn't put in much effort to chase the fox."
),
chatMessagePair(
userContent:
"Using Simplified-Chinese to summarize the following text: \"\"\"联合国在西非地区的最高官员周五表示,马里、布基纳法索和尼日尔决定退出西非国家经济共同体,将全面破坏地区关系,而此时恐怖主义和跨国有组织犯罪仍然对该地区构成普遍威胁。联合国西非和萨赫勒办事处负责人莱昂纳多•桑托斯•西芒向安理会表示,放弃西非经共体 将使三个军方领导的政府放弃关键利益,包括地区一体化、行动自由、安全合作和一体化的地区经济,这既伤害了他们自己,也伤害了西非经共体的其他成员。在高级军官分别于 2021 年、2022 年和 2023 年发动军事接管后,这三个过渡政府断绝了与西非经共体的关系。西芒说,军事领导人因此推迟了恢复宪政的时间,并引发了对长期不确定性的恐惧,因为公民空间继续缩小。\"\"\".",
assistantContent:
"马里、布基纳法索和尼日尔退出西非国家经济共同体,将严重破坏地区关系,尤其是在恐怖主义和跨国有组织犯罪仍威胁该地区的情况下。联合国官员西芒指出,这一决定将使这三个国家失去地区一体化、安全合作和经济利益,推迟恢复宪政,并加剧长期不确定性。"
),

].flatMap { $0 }

var messages: [ChatMessage] = [
.init(role: .system, content: LLMStreamService.summarySystemPrompt),
]
messages.append(contentsOf: fewShot)
messages.append(.init(role: .user, content: prompt))

return messages
}

// MARK: Translation Messages

private func translationPrompt(
Expand Down

0 comments on commit 403251c

Please sign in to comment.