Python: Microsoft Semantic Kernel - Process, crashes when invoked with data for the second time (or when called repeatedly in a loop, works only the first time)
I want my process to be fed one row of data at a time. Here each "row" is a json blurb, that's passed as data of the starting event.
I can't seem to get the second set of data to be processed. Symantic Kernel throws the following error:
pdl_runner is custom code, but rest is all pydantic error. Can't figure out why pydantic is okay with the first set of data but fails with the next set.
'Traceback (most recent call last):\n File "process_app.py", line 20, in dynamic_processes_app
\n await pdl_runner.run(process_name=process_name, data=data)
\n File "C:\\Workspaces\\Company\\Data\\Code\\project\\processes\\services\\process_definitions_runner.py", line 76, in run
\n await start(\n File "c:\\Workspaces\\Company\\Data\\Code\\project\\.venv\\Lib\\site-packages\\semantic_kernel\\processes\\local_runtime\\local_kernel_process.py", line 51, in start
\n await process_context.start_with_event(initial_event_str)
\n File "c:\\Workspaces\\Company\\Data\\Code\\project\\.venv\\Lib\\site-packages\\semantic_kernel\\processes\\local_runtime\\local_kernel_process_context.py", line 51, in start_with_event
\n await self.local_process.run_once(initial_event)\n File "c:\\Workspaces\\Company\\Data\\Code\\project\\.venv\\Lib\\site-packages\\semantic_kernel\\processes\\local_runtime\\local_process.py", line 103, in run_once
\n await self.start(keep_alive=False)\n File "c:\\Workspaces\\Company\\Data\\Code\\project\\.venv\\Lib\\site-packages\\semantic_kernel\\processes\\local_runtime\\local_process.py", line 90, in start
\n self.process_task = asyncio.create_task(
\n ^^^^^^^^^^^^^^^^^
\n File "c:\\Workspaces\\Company\\Data\\Code\\project\\.venv\\Lib\\site-packages\\pydantic\\main.py", line 922, in __setattr__
\n self.__pydantic_validator__.validate_assignment(self, name, value)\npydantic_core._pydantic_core.ValidationError: 1 validation error for LocalProcess\nprocess_task
\n Input should be an instance of Task [type=is_instance_of, input_value=<Task pending name=\'Task-...e\\local_process.py:191>>, input_type=Task]
\n For further information visit https://errors.pydantic.dev/2.10/v/is_instance_of\n'
In my test I am using only two "rows" of data and I've tried switching the rows around, and it is always the second row that fails.
I am starting the process using the start function
if self.process is not None and self.kernel is not None:
# Build the kernel process
kernel_process = self.process.build()
kernel_event = KernelProcessEvent(id=self.start_event, data=data)
# Start the process
await start(
process=kernel_process,
kernel=self.kernel,
initial_event=kernel_event,
)
I have tried having the same kernel fire start event multiple times. I've tried to generate a new Kernel per row of data. Both seem to fail with the same error.
Please suggest what's the recommendation on processing multiple "rows" of data using a Symantic Kernel Process OR how to invoke the same Symantic Kernel Process repeatedly, with different inputs or data to the KernelProcessEvent.
The reason I want the data load to be outside the process is because I want to run it as an Azure Function and I want each data unit/row to be processed as a long running function. But currently I am just running this locally in Windows Terminal, no Azure Function emulation in use.
Okay, I got some more details on the exception that got truncated in the original post above:
{
'type': 'is_instance_of',
'loc': "('process_task',)",
'msg': 'Input should be an instance of Task',
'input': "<Task pending name='Task-15' coro=<LocalProcess.internal_execute() running at c:\Workspaces\Company\Data\Code\Project\.venv\Lib\site-packages\semantic_kernel\processes\local_runtime\local_process.py:191>>",
'ctx':
{
'class': 'Task'
},
'url': 'https://errors.pydantic.dev/2.10/v/is_instance_of'
}
So, it looks like some task from the previous run of the process is pending...? Is that what it is?
@skm-nbrly when you run a process, there is inherent state involved. For example, when the process is run the first time, a process step may be updating/changing the KernelProcessStepState. When you run the "second row" do you need the previous state, or do you want to be running a fresh process? I'd recommend for each "row" that you build a fresh KernelProcess object, if possible.
Also, to make sure the process has run fully to completion, you can try the following:
async with await start(
process=kernel_process,
kernel=kernel,
initial_event=KernelProcessEvent(id=CommonEvents.StartProcess, data="foo"),
) as process_context:
# Check the final state of a step, for example
process_state = await process_context.get_state()
some_step_state: KernelProcessStepState[MyStepState] = next(
(s.state for s in process_state.steps if s.state.name == "<yourStepName>"), None
)
I'd recommend for each "row" that you build a fresh KernelProcess object, if possible.
Thanks @moonbox3 . I also concluded the same, and implemented a fresh KernelProcess per row of data (because each run does not need to share state with previous run) but I am still getting the issue.
Just so I understand your sample code correctly, running the loop through all my steps and retrieving their state successfully will ensure the process has run fully?
or
should I be update a state variable at end of each my steps and verify that particular variable is set to the end value? What happens if the end state is not reached? -> Do some kind of asyncio.sleep(...) and try again?
This also raises another question, if some of my steps are not executed because the current row of data didn't warrant calling those steps, would that prevent the Process from ending gracefully?
I created an executed bool attribute on my step states and set it to False by default and True at the end of each step execution. I ended up with all steps that participated for that row of data as marked executed = True, but the steps that didn't participate were (as expected) had executed = False.
Apologies if the questions are a bit noobish, my first MSK project.
Here's my code based on your suggestion:
async with await start(
process=kernel_process,
kernel=self.process_kernel,
initial_event=kernel_event,
) as process_context:
# Check the final state of a step, for example
process_state = await process_context.get_state()
print("\n Check process states \n")
for s in process_state.steps:
some_step_state: KernelProcessStepState[BaseStepState] | None = s.state
if(some_step_state is not None):
print(f"State Name: {s.state.name} has executed {s.state.state.step_definition.executed}") #type: ignore
It gives me the following output (I obfuscated the names, but the numbering gives an idea of the non-sequential execution)
Check process states
State Name: step1 has executed True
State Name: step2 has executed True
State Name: step3 has executed True
State Name: step4 has executed True
State Name: step5 has executed True
State Name: step6 has executed True
State Name: step7 has executed True
State Name: step12 has executed True
State Name: step13 has executed True
State Name: step14 has executed True
State Name: step15 has executed True
State Name: step8 has executed False
State Name: step9 has executed False
State Name: step10 has executed False
State Name: step11 has executed False
The system prints this after first row of data is executed. Prints all the logs for the setup of the second instance of KernelProcess, starts the kernel process and crashes.
Should I try to name each step differently for each row of data. e.g
step1-row1... for first row
step1-row2... for second row?
Hi @skm-nbrly, thanks for the reply and added context. To make sure I understand properly:
- You create a fresh, KernelProcess object (by building your process).
- You run that kernel process, and see the
State Name: step1 has executed True ...output for that one process. - You then create a new instance of the KernelProcess (not the same instance as before).
- You run a new run of data on the new instance, and you still see the Pydantic error "Input should be an instance of Task"?
I'll be really perplexed if when you create the fresh KernelProcess instance for that second row of data you pass in, how it could be throwing the Pydantic validation error because that particular model validation wouldn't have occurred yet (unless something still has a handle to a previous object).
This also raises another question, if some of my steps are not executed because the current row of data didn't warrant calling those steps, would that prevent the Process from ending gracefully?
That's okay that some of your steps aren't executed - certain events may lead you down one path of the graph - there's no requirement that all nodes must be hit. The process will end either when you've hit the max number of super steps (configurable via start method - I think they default to 100), there are no more messages to deliver, or an END_STEP is hit. For example, if I define a certain event being raised to stopping the process like so:
user_input_step.on_event(event_id=ChatBotEvents.Exit).stop_process()
My kernel function in my process step would be doing something like:
if "exit" in user_message:
await context.emit_event(process_event=ChatBotEvents.Exit, data=None)
return
A few other questions/ideas:
-
Have you enabled DEBUG logging via
import loggingandlogging.basicConfig(level=logging.DEBUG)in your main script? This can help understand the expected flow, and potentially shed some light on some other error that could be happening. -
If you do continue to hit the error, is there any way to provide some minimal amount of code so I can repro it on my end? Doesn't need to include any PII or proprietary info, of course.
Hi @moonbox3
You create a fresh, KernelProcess object (by building your process).
- You run that kernel process, and see the State Name: step1 has executed True ... output for that one process.
- You then create a new instance of the KernelProcess (not the same instance as before).
- You run a new run of data on the new instance, and you still see the Pydantic error "Input should be an instance of Task"?
That is correct.
I enabled logging as suggested (not sure why I didn't have it enabled) and it is spitting out about 23Mb of data for the first process run. That includes everything and kitchen sink about the process execution. However, there is no Symantic Kernel logging for the second row of data. It only has custom code's logging which shows a new Kernel Process being setup. But as soon as I hit start, it crashes and there is no log apart from the above exception message.
You are correct about the supersteps. I do see supersteps count of 100 being logged as the default value.
I am going to try and corral all my open ended steps into a "end step" and call end process explicitly in that step using the code you suggested above. Hopefully that will do the trick. But before that I have some other stuff to take care. I'll get back as soon as I am done trying the explicit end process step.
Once again, thanks for all your help so far.
The code base for my project is fairly big, so lots of chances of thing going wrong elsewhere. I'll try to eliminate as many loose ends as possible before I try and share the code.
This issue was to try and understand if I have gotten the basics wrong, from your suggestions it doesn't seem like it. I'll close the ticket for now, and either re-open if I am able to find a solid set of repro-able steps with shareable code or add in comments on what was the issue in my code.
@moonbox3
Small update, I managed to corral all the steps into an End Step but calling stop_process() did not help with the second row of data.
The second run loads all the steps (custom code), then when the start event is fired I only get one line saying kernel process running process for 100 supersteps.
DEBUG:root:========================= All steps loaded =========================
DEBUG:semantic_kernel.processes.local_runtime.local_process:Running process for 100 supersteps.
It doesn't even log the error in the logs (indicating it is potentially an unhandled error). The error comes out in console as follows
{'type': 'is_instance_of', 'loc': ('process_task',), 'msg': 'Input should be an instance of Task', 'input': <Task pending name='Task-86' coro=<LocalProcess.internal_execute() running at c:\Workspaces\Company\Data\Code\Project\.venv\Lib\site-packages\semantic_kernel\processes\local_runtime\local_process.py:191>>, 'ctx': {'class': 'Task'}, 'url': 'https://errors.pydantic.dev/2.10/v/is_instance_of'}
Separating the code out to an easily repro-able bit will be complicated. I'll see if I can narrow it down to a shareable sample.
@moonbox3 okay, looks like I managed to fix it, but I still don't know 100% why it works the first time.
This piece of code seems to use asyncio.create_task for an already async method self.internal_execute
https://github.com/microsoft/semantic-kernel/blob/90d158cbf8bd4598159a6fe64df745e56d9cbdf4/python/semantic_kernel/processes/local_runtime/local_process.py#L90
Changing above to a simple async call fixed the issue.
self.process_task = await self.internal_execute(max_supersteps=self.max_supersteps, keep_alive=keep_alive)
I am going to run more tests to ensure it actually works, but any insights on why we are using create_task in the first place would help. ~~It could be it was calling a non-async method previously which is now async and thus doesn't need the create_task (sorry haven't seen the history).~~
Edit: Ignore my reasoning and lack of deep understanding of coro and asyncio
Any suggestions, welcome.
Reopening the issue, to see if it can be incorporated into the framework instead of me lugging around a custom copy of the local_runtime folder :-)
This issue is stale because it has been open for 90 days with no activity.
@moonbox3 any chance this will be looked into, or it's too big a change and current keep lights on mode for Semantic Kernel means it's better to migrate to Agent Framework when possible? Happy to close it, given we have a workaround.
@moonbox3 any chance this will be looked into, or it's too big a change and current keep lights on mode for Semantic Kernel means it's better to migrate to Agent Framework when possible? Happy to close it, given we have a workaround.
Hi @skm-nbrly, we would highly recommend upgrading to MAF's workflows in place of SK's process framework, if possible. It's a much better architecture/design and is a lot more intuitive to use compared to the process framework. You can view some getting started samples for workflows here: https://github.com/microsoft/agent-framework/tree/main/python/samples/getting_started/workflows/_start-here (and then other samples a directory level up).
Thanks @moonbox3 . It's in our roadmap. I'll close this.