Skip to content

Commit 36d261f

Browse files
committedJan 2, 2025
refactor(runner): streamline template compilation and execution #157
- Refactored `processTemplateCompile` and `prepareExecute` methods to simplify logic and improve readability. - Removed redundant code and consolidated variable handling. - Updated `ShireActionPromptBuilder` to use `compileFileContext` for consistent prompt generation. - Improved error handling
1 parent d35a870 commit 36d261f

File tree

4 files changed

+161
-117
lines changed

4 files changed

+161
-117
lines changed
 

‎core/src/main/kotlin/com/phodal/shirecore/provider/streaming/OnStreamingService.kt

+2-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ class OnStreamingService {
5252
fun onStreaming(project: Project, chunk: String) {
5353
map.forEach { (sign, service) ->
5454
try {
55-
service.onStreaming(project, chunk, sign.args)
55+
service.
56+
onStreaming(project, chunk, sign.args)
5657
} catch (e: Exception) {
5758
ShirelangNotifications.error(project, "Error on streaming service: ${e.message}")
5859
}

‎shirelang/src/main/kotlin/com/phodal/shirelang/provider/ShireActionPromptBuilder.kt

+7-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import com.intellij.openapi.project.Project
44
import com.phodal.shirecore.config.ShireActionLocation
55
import com.phodal.shirecore.provider.ide.ShirePromptBuilder
66
import com.phodal.shirelang.actions.base.DynamicShireActionService
7+
import com.phodal.shirelang.run.runner.ShireRunner
8+
import kotlinx.coroutines.runBlocking
79

810
class ShireActionPromptBuilder : ShirePromptBuilder {
911
override fun build(project: Project, actionLocation: String, originPrompt: String): String {
@@ -12,7 +14,11 @@ class ShireActionPromptBuilder : ShirePromptBuilder {
1214
val action = DynamicShireActionService.getInstance(project).getActions(location)
1315
.firstOrNull() ?: return originPrompt
1416

17+
val initVariables = mapOf("chatPrompt" to originPrompt)
18+
val finalPrompt = runBlocking {
19+
ShireRunner.compileFileContext(project, action.shireFile, initVariables)
20+
}.finalPrompt
1521

16-
return action.shireFile.text?.replace("\$chatPrompt", originPrompt) ?: ""
22+
return finalPrompt
1723
}
1824
}

‎shirelang/src/main/kotlin/com/phodal/shirelang/run/runner/ShireRunner.kt

+151-114
Original file line numberDiff line numberDiff line change
@@ -49,19 +49,13 @@ class ShireRunner(
4949
private val cancelListeners = mutableSetOf<(String) -> Unit>()
5050

5151
suspend fun execute(parsedResult: ShireParsedResult): String? {
52-
prepareExecute(parsedResult)
52+
prepareExecute(parsedResult, compiledVariables, project, console)
5353

5454
val runResult = CompletableFuture<String>()
5555

56-
val varsMap = variableMap.toMutableMap()
56+
val varsMap = variableFromPostProcessorContext(variableMap)
5757

58-
val data = PostProcessorContext.getData()
59-
val variables = data?.compiledVariables
60-
if (variables?.get("output") != null && variableMap["output"] == null) {
61-
varsMap["output"] = variables["output"].toString()
62-
}
63-
64-
val runnerContext = processTemplateCompile(parsedResult, varsMap)
58+
val runnerContext = processTemplateCompile(parsedResult, varsMap, project, configuration, console)
6559
if (runnerContext.hasError) {
6660
processHandler.exitWithError()
6761
return null
@@ -127,51 +121,6 @@ class ShireRunner(
127121
}
128122
}
129123

130-
private suspend fun processTemplateCompile(
131-
compileResult: ShireParsedResult, variableMap: Map<String, String>,
132-
): ShireRunnerContext {
133-
val hobbitHole = compileResult.config
134-
val editor = ActionLocationEditor.provide(project, hobbitHole?.actionLocation)
135-
136-
val templateCompiler =
137-
ShireTemplateCompiler(project, hobbitHole, compileResult.variableTable, compileResult.shireOutput, editor)
138-
139-
variableMap.forEach { (key, value) ->
140-
templateCompiler.putCustomVariable(key, value)
141-
}
142-
143-
val promptTextTrim = templateCompiler.compile().trim()
144-
val compiledVariables = templateCompiler.compiledVariables
145-
146-
PostProcessorContext.getData()?.lastTaskOutput?.let {
147-
templateCompiler.putCustomVariable("output", it)
148-
}
149-
150-
if (console != null) {
151-
printCompiledOutput(console, promptTextTrim, configuration)
152-
}
153-
154-
var hasError = false
155-
156-
if (promptTextTrim.isEmpty()) {
157-
console?.print("No content to run", ConsoleViewContentType.ERROR_OUTPUT)
158-
hasError = true
159-
}
160-
161-
if (promptTextTrim.contains(SHIRE_ERROR)) {
162-
hasError = true
163-
}
164-
165-
return ShireRunnerContext(
166-
hobbitHole,
167-
editor = editor,
168-
compileResult,
169-
promptTextTrim,
170-
hasError,
171-
compiledVariables
172-
)
173-
}
174-
175124
fun executeNormalUiTask(runData: ShireRunnerContext, postFunction: PostFunction) {
176125
val agent = runData.compileResult.executeAgent
177126
val hobbitHole = runData.hole
@@ -235,64 +184,6 @@ class ShireRunner(
235184
}
236185
}
237186

238-
private fun printCompiledOutput(
239-
console: ConsoleViewWrapperBase,
240-
promptText: String,
241-
shireConfiguration: ShireConfiguration,
242-
) {
243-
console.print("Shire Script: ${shireConfiguration.getScriptPath()}\n", ConsoleViewContentType.SYSTEM_OUTPUT)
244-
console.print("Shire Script Compile output:\n", ConsoleViewContentType.SYSTEM_OUTPUT)
245-
PostProcessorContext.getData()?.llmModelName?.let {
246-
console.print("Used model: $it\n", ConsoleViewContentType.SYSTEM_OUTPUT)
247-
}
248-
249-
promptText.split("\n").forEach {
250-
when {
251-
it.contains(SHIRE_ERROR) -> {
252-
console.print(it, ConsoleViewContentType.LOG_ERROR_OUTPUT)
253-
}
254-
255-
else -> {
256-
console.print(it, ConsoleViewContentType.USER_INPUT)
257-
}
258-
}
259-
console.print("\n", ConsoleViewContentType.NORMAL_OUTPUT)
260-
}
261-
262-
console.print("\n--------------------\n", ConsoleViewContentType.NORMAL_OUTPUT)
263-
}
264-
265-
fun prepareExecute(parsedResult: ShireParsedResult) {
266-
val hobbitHole = parsedResult.config
267-
val editor = FileEditorManager.getInstance(project).selectedTextEditor
268-
hobbitHole?.pickupElement(project, editor)
269-
270-
val file = runReadAction {
271-
editor?.let { PsiManager.getInstance(project).findFile(it.virtualFile) }
272-
}
273-
274-
val context = PostProcessorContext.getData() ?: PostProcessorContext(
275-
currentFile = file,
276-
currentLanguage = file?.language,
277-
editor = editor,
278-
compiledVariables = compiledVariables,
279-
llmModelName = hobbitHole?.model
280-
)
281-
282-
PostProcessorContext.updateContextAndVariables(context)
283-
284-
val vars: MutableMap<String, Any?> = compiledVariables.toMutableMap()
285-
hobbitHole?.executeBeforeStreamingProcessor(project, context, console, vars)
286-
287-
val streamingService = project.getService(OnStreamingService::class.java)
288-
streamingService.clearStreamingService()
289-
hobbitHole?.onStreaming?.forEach {
290-
streamingService.registerStreamingService(it, console)
291-
}
292-
293-
hobbitHole?.setupStreamingEndProcessor(project, context)
294-
}
295-
296187
@Synchronized
297188
fun addCancelListener(listener: (String) -> Unit) {
298189
if (isCanceled) cancel(listener)
@@ -316,8 +207,154 @@ class ShireRunner(
316207
companion object {
317208
fun preAnalysisSyntax(shireFile: ShireFile, project: Project): ShireParsedResult {
318209
val syntaxAnalyzer = ShireSyntaxAnalyzer(project, shireFile, ActionLocationEditor.defaultEditor(project))
319-
val parsedResult = syntaxAnalyzer.parse()
320-
return parsedResult
210+
return syntaxAnalyzer.parse()
211+
}
212+
213+
fun prepareExecute(
214+
parsedResult: ShireParsedResult,
215+
variables: Map<String, Any>,
216+
project: Project,
217+
consoleView: ShireConsoleView?,
218+
): PostProcessorContext {
219+
val hobbitHole = parsedResult.config
220+
val editor = FileEditorManager.getInstance(project).selectedTextEditor
221+
hobbitHole?.pickupElement(project, editor)
222+
223+
val file = runReadAction {
224+
editor?.let { PsiManager.getInstance(project).findFile(it.virtualFile) }
225+
}
226+
227+
val context = PostProcessorContext.getData() ?: PostProcessorContext(
228+
currentFile = file,
229+
currentLanguage = file?.language,
230+
editor = editor,
231+
compiledVariables = variables,
232+
llmModelName = hobbitHole?.model
233+
)
234+
235+
PostProcessorContext.updateContextAndVariables(context)
236+
237+
val vars: MutableMap<String, Any?> = variables.toMutableMap()
238+
hobbitHole?.executeBeforeStreamingProcessor(project, context, consoleView, vars)
239+
240+
val streamingService = project.getService(OnStreamingService::class.java)
241+
streamingService.clearStreamingService()
242+
hobbitHole?.onStreaming?.forEach {
243+
streamingService.registerStreamingService(it, consoleView)
244+
}
245+
246+
hobbitHole?.setupStreamingEndProcessor(project, context)
247+
248+
return context
249+
}
250+
251+
private suspend fun processTemplateCompile(
252+
compileResult: ShireParsedResult,
253+
variableMap: Map<String, String>,
254+
project: Project,
255+
shireConfiguration: ShireConfiguration?,
256+
shireConsoleView: ShireConsoleView?,
257+
): ShireRunnerContext {
258+
val hobbitHole = compileResult.config
259+
val editor = ActionLocationEditor.provide(project, hobbitHole?.actionLocation)
260+
261+
val templateCompiler =
262+
ShireTemplateCompiler(
263+
project,
264+
hobbitHole,
265+
compileResult.variableTable,
266+
compileResult.shireOutput,
267+
editor
268+
)
269+
270+
variableMap.forEach { (key, value) ->
271+
templateCompiler.putCustomVariable(key, value)
272+
}
273+
274+
val promptTextTrim = templateCompiler.compile().trim()
275+
val compiledVariables = templateCompiler.compiledVariables
276+
277+
PostProcessorContext.getData()?.lastTaskOutput?.let {
278+
templateCompiler.putCustomVariable("output", it)
279+
}
280+
281+
if (shireConsoleView != null && shireConfiguration != null) {
282+
printCompiledOutput(shireConsoleView, promptTextTrim, shireConfiguration)
283+
}
284+
285+
var hasError = false
286+
287+
if (promptTextTrim.isEmpty()) {
288+
shireConsoleView?.print("No content to run", ConsoleViewContentType.ERROR_OUTPUT)
289+
hasError = true
290+
}
291+
292+
if (promptTextTrim.contains(SHIRE_ERROR)) {
293+
hasError = true
294+
}
295+
296+
return ShireRunnerContext(
297+
hobbitHole,
298+
editor = editor,
299+
compileResult,
300+
promptTextTrim,
301+
hasError,
302+
compiledVariables
303+
)
304+
}
305+
306+
private fun printCompiledOutput(
307+
console: ConsoleViewWrapperBase,
308+
promptText: String,
309+
shireConfiguration: ShireConfiguration,
310+
) {
311+
console.print("Shire Script: ${shireConfiguration.getScriptPath()}\n", ConsoleViewContentType.SYSTEM_OUTPUT)
312+
console.print("Shire Script Compile output:\n", ConsoleViewContentType.SYSTEM_OUTPUT)
313+
PostProcessorContext.getData()?.llmModelName?.let {
314+
console.print("Used model: $it\n", ConsoleViewContentType.SYSTEM_OUTPUT)
315+
}
316+
317+
promptText.split("\n").forEach {
318+
when {
319+
it.contains(SHIRE_ERROR) -> {
320+
console.print(it, ConsoleViewContentType.LOG_ERROR_OUTPUT)
321+
}
322+
323+
else -> {
324+
console.print(it, ConsoleViewContentType.USER_INPUT)
325+
}
326+
}
327+
console.print("\n", ConsoleViewContentType.NORMAL_OUTPUT)
328+
}
329+
330+
console.print("\n--------------------\n", ConsoleViewContentType.NORMAL_OUTPUT)
331+
}
332+
333+
suspend fun compileFileContext(
334+
project: Project,
335+
shireFile: ShireFile,
336+
initVariables: Map<String, String>,
337+
): ShireRunnerContext {
338+
val parsedResult = preAnalysisSyntax(shireFile, project)
339+
val variables = variableFromPostProcessorContext(initVariables)
340+
341+
/// add context
342+
prepareExecute(parsedResult, variables, project, null)
343+
344+
val runnerContext = processTemplateCompile(parsedResult, variables, project, null, null)
345+
return runnerContext
346+
347+
}
348+
349+
private fun variableFromPostProcessorContext(initValue: Map<String, String>): MutableMap<String, String> {
350+
val varsMap = initValue.toMutableMap()
351+
val data = PostProcessorContext.getData()
352+
val variables = data?.compiledVariables
353+
if (variables?.get("output") != null && initValue["output"] == null) {
354+
varsMap["output"] = variables["output"].toString()
355+
}
356+
357+
return varsMap
321358
}
322359
}
323360
}

‎src/main/kotlin/com/phodal/shire/inline/ShireInlineChatService.kt

+1-1
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ class ShireInlineChatService : Disposable {
6868
}
6969

7070
fun prompt(project: Project, prompt: String): String {
71-
return ShirePromptBuilder.provide()?.build(project, ShireActionLocation.INPUT_BOX.name, prompt) ?: prompt
71+
return ShirePromptBuilder.provide()?.build(project, ShireActionLocation.INLINE_CHAT.name, prompt) ?: prompt
7272
}
7373

7474
companion object {

0 commit comments

Comments
 (0)
Please sign in to comment.