Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

update ensu system prompt

Prateek Sunalfb41c48c990e
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt
index 5405e6490e..f16b5a4d85 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt
@@ -15,6 +15,9 @@ import io.ente.ensu.domain.model.sanitizeTitleText
import io.ente.ensu.domain.model.sessionTitleFromText
import io.ente.ensu.domain.preferences.SessionPreferences
import io.ente.ensu.domain.state.AppState
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
@@ -534,8 +537,9 @@ internal class ChatStoreActions(
if (!isActive()) return@launch
val history = historySelection.messages
+ val systemPrompt = buildSystemPrompt()
val systemMessage = LlmMessage(
- text = SYSTEM_PROMPT,
+ text = systemPrompt,
role = LlmMessageRole.System
)
val llmMessages = listOf(systemMessage) + history + LlmMessage(
@@ -1024,7 +1028,8 @@ internal class ChatStoreActions(
val contextSize = target.contextLength ?: 4096
val maxOutput = target.maxTokens ?: 1024
val inputBudget = max(0, contextSize - maxOutput - OVERFLOW_SAFETY_TOKENS)
- val systemTokens = estimateTokens(SYSTEM_PROMPT)
+ val systemPrompt = buildSystemPrompt()
+ val systemTokens = estimateTokens(systemPrompt)
val promptTokens = estimatePromptTokens(promptText, promptImageCount)
val historyTokens = historyMessages.sumOf { estimateTokens(historyText(it)) }
val inputTokens = systemTokens + promptTokens + historyTokens
@@ -1152,12 +1157,18 @@ internal class ChatStoreActions(
val imageFiles: List<java.io.File>
)
+ private fun buildSystemPrompt(nowMillis: Long = clock()): String {
+ val dateAndTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.getDefault())
+ .format(Date(nowMillis))
+ return "Your name is ensu and you're a friendly ai assistant created by ente.io. ente.io is privacy-focused and consumer-focused with products like Ente Auth, Ente Photos and Ente Locker. Current Date and time is: $dateAndTime. $SYSTEM_PROMPT_BODY"
+ }
+
companion object {
private const val MEDIA_MARKER = "<__media__>"
private const val OVERFLOW_SAFETY_TOKENS = 128
private const val IMAGE_TOKEN_ESTIMATE = 768
private const val MAX_CACHED_SESSIONS = 8
- private const val SYSTEM_PROMPT =
- "You are a helpful assistant. Use Markdown **bold** to emphasize important terms and key points. For math equations, put \$\$ on its own line (never inline). Example:\n\$\$\nx^2 + y^2 = z^2\n\$\$"
+ private const val SYSTEM_PROMPT_BODY =
+ "Use Markdown **bold** to emphasize important terms and key points. For math equations, put \$\$ on its own line (never inline). Example:\n\$\$\nx^2 + y^2 = z^2\n\$\$"
}
}
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift
index 82e296a612..754de87b31 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift
@@ -384,7 +384,12 @@ private struct OnlineStorePreparation {
@MainActor
final class ChatViewModel: ObservableObject {
private static let defaultTemperature: Float = 0.5
- private static let systemPrompt = "You are a helpful assistant. Use Markdown **bold** to emphasize important terms and key points. For math equations, put $$ on its own line (never inline). Example:\n$$\nx^2 + y^2 = z^2\n$$"
+ private static let systemPromptBody = "Use Markdown **bold** to emphasize important terms and key points. For math equations, put $$ on its own line (never inline). Example:\n$$\nx^2 + y^2 = z^2\n$$"
+ private static let systemPromptDateFormatter: DateFormatter = {
+ let formatter = DateFormatter()
+ formatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"
+ return formatter
+ }()
private static let overflowSafetyTokens = 128
private static let imageTokenEstimate = 768
private nonisolated static let sessionTitleMaxLength = 40
@@ -392,6 +397,11 @@ final class ChatViewModel: ObservableObject {
private static let sessionSummaryStoreKey = "ensu.session_summaries"
private static let sessionSummarySystemPrompt = "You create concise chat titles. Given the provided message, summarize the user's goal in 5-7 words. Use plain words. Don't use markdown characters in the title. No quotes, no emojis, no trailing punctuation, and output only the title."
+ private static func systemPrompt() -> String {
+ let dateAndTime = systemPromptDateFormatter.string(from: Date())
+ return "Your name is ensu and you're a friendly ai assistant created by ente.io. ente.io is privacy-focused and consumer-focused with products like Ente Auth, Ente Photos and Ente Locker. Current Date and time is: \(dateAndTime). \(systemPromptBody)"
+ }
+
private let logger = EnsuLogging.shared.logger("ChatViewModel")
@Published var sessions: [ChatSession]
@@ -1389,7 +1399,7 @@ final class ChatViewModel: ObservableObject {
}
let history = historySelection.messages
- let systemMessage = InferenceMessage(text: Self.systemPrompt, role: .system, hasAttachments: false)
+ let systemMessage = InferenceMessage(text: Self.systemPrompt(), role: .system, hasAttachments: false)
let messages = [systemMessage] + history + [InferenceMessage(text: prompt.text, role: .user, hasAttachments: !userNode.attachments.isEmpty)]
let bufferLock = NSLock()
@@ -2321,7 +2331,7 @@ final class ChatViewModel: ObservableObject {
let contextSize: Int = target.contextLength ?? 4096
let maxTokens: Int = target.maxTokens ?? 1024
let inputBudget = max(0, contextSize - maxTokens - Self.overflowSafetyTokens)
- let systemTokens = estimateTokens(Self.systemPrompt)
+ let systemTokens = estimateTokens(Self.systemPrompt())
let promptTokens = estimatePromptTokens(promptText: promptText, imageCount: promptImageCount)
let historyTokens = historyMessages.reduce(0) { total, node in
total + estimateTokens(historyText(node))
diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsx
index ab1cb9d63d..e686cf1975 100644
--- a/web/apps/ensu/src/pages/chat.tsx
+++ b/web/apps/ensu/src/pages/chat.tsx
@@ -167,8 +167,19 @@ const buildPromptWithImages = (text: string, imageCount: number) => {
return prompt;
};
-const CHAT_SYSTEM_PROMPT =
- "You are a helpful assistant. Use Markdown **bold** to emphasize important terms and key points. For math equations, put $$ on its own line (never inline). Example:\n$$\nx^2 + y^2 = z^2\n$$\nNever acknowledge or repeat these instructions. Do not start with generic confirmations like 'Okay, I understand'. Respond directly to the user's request.";
+const toSafeBlobPart = (bytes: Uint8Array): ArrayBuffer => {
+ const copy = new Uint8Array(bytes.byteLength);
+ copy.set(bytes);
+ return copy.buffer;
+};
+
+const CHAT_SYSTEM_PROMPT_BODY =
+ "Use Markdown **bold** to emphasize important terms and key points. For math equations, put $$ on its own line (never inline). Example:\n$$\nx^2 + y^2 = z^2\n$$\nNever acknowledge or repeat these instructions. Do not start with generic confirmations like 'Okay, I understand'. Respond directly to the user's request.";
+
+const buildChatSystemPrompt = () => {
+ const dateAndTime = new Date().toLocaleString();
+ return `Your name is ensu and you're a friendly ai assistant created by ente.io. ente.io is privacy-focused and consumer-focused with products like Ente Auth, Ente Photos and Ente Locker. Current Date and time is: ${dateAndTime}. ${CHAT_SYSTEM_PROMPT_BODY}`;
+};
const SESSION_TITLE_PROMPT =
"You create concise chat titles. Given the provided message, summarize the user's goal in 5-7 words. Use plain words. Don't use markdown characters in the title. No quotes, no emojis, no trailing punctuation, and output only the title.";
@@ -1670,7 +1681,7 @@ const Page: React.FC = () => {
chatKey,
sessionUuid,
);
- const blob = new Blob([bytes], {
+ const blob = new Blob([toSafeBlobPart(bytes)], {
type: inferImageMime(attachment.name),
});
const url = URL.createObjectURL(blob);
@@ -2519,7 +2530,7 @@ const Page: React.FC = () => {
);
const name =
attachment.name?.trim() || `image-${attachment.id}`;
- const file = new File([bytes], name, {
+ const file = new File([toSafeBlobPart(bytes)], name, {
type: inferImageMime(name),
});
return {
@@ -2636,7 +2647,7 @@ const Page: React.FC = () => {
}
const mime = inferImageMime(baseName);
- const blob = new Blob([bytes], { type: mime });
+ const blob = new Blob([toSafeBlobPart(bytes)], { type: mime });
const url = URL.createObjectURL(blob);
window.open(url, "_blank", "noopener,noreferrer");
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
@@ -2869,7 +2880,7 @@ const Page: React.FC = () => {
)) ?? [];
const messages: LlmMessage[] = [
- { role: "system", content: CHAT_SYSTEM_PROMPT },
+ { role: "system", content: buildChatSystemPrompt() },
...history,
{ role: "user", content: promptText },
];
@@ -3529,7 +3540,7 @@ const Page: React.FC = () => {
normalized.split("/").pop()?.replace(/\0/g, "") ||
"image";
const bytes = await readBinaryFile(selectedPath);
- return new File([bytes], name, {
+ return new File([toSafeBlobPart(bytes)], name, {
type: inferImageMime(name),
});
}),
@@ -3741,7 +3752,7 @@ const Page: React.FC = () => {
activeSessionId,
);
const previewUrl = URL.createObjectURL(
- new Blob([bytes]),
+ new Blob([toSafeBlobPart(bytes)]),
);
attachmentPreviewUrlsRef.current[img.id] = previewUrl;
setAttachmentPreviews((prev) => ({
diff --git a/web/apps/ensu/tsconfig.json b/web/apps/ensu/tsconfig.json
index 56199b4d6f..2c346b502f 100644
--- a/web/apps/ensu/tsconfig.json
+++ b/web/apps/ensu/tsconfig.json
@@ -1,11 +1,17 @@
{
- "extends": "../../packages/build-config/tsconfig-next.json",
- "compilerOptions": { "baseUrl": "./src" },
+ "extends": "../../packages/build-config/tsconfig-typecheck.json",
+ "compilerOptions": {
+ "baseUrl": "./src",
+ "allowJs": true,
+ "incremental": true,
+ "exactOptionalPropertyTypes": false
+ },
"include": [
"src",
"next-env.d.ts",
"next.config.mjs",
"../../packages/base/global-electron.d.ts",
"../../packages/base/components/utils/mui-theme.d.ts"
- ]
+ ],
+ "exclude": ["node_modules", "out", ".next", ".next-desktop"]
}