Python¶
Using the promptscript
package to run PromptScript embedded in Python.
There are two main ways to run PromptScript in Python using the promptscript
package: running files or commands.
Running PromptScript Files¶
1from promptscript.executor import FileExecutor
2
3
4file_executor = FileExecutor()
5file_executor.run('file.prompt')
You can also pass parameters into the executor:
1file_executor.run('file.prompt', user_prompt='What is 2+2?')
Then access them directly from your PromptScript file.
1chat_response = chat user_prompt, "gpt-4o", "API_KEY"
Running Commands¶
1from promptscript.executor import CommandExecutor
2
3
4command_executor = CommandExecutor()
5command_executor.run('show "Hello, World!"')
The CommandExecutor also supports passing in parameters.
1command_executor.run('show msg', msg='Hello, World!')
Persistent Command Execution¶
Imagine you want to run a sequence of individual commands that have access to the outputs of the previous commands. Of course,
this is possible with the base CommandExecutor
class through the use of parameters, but this approach is clunky and
inefficient. That’s where the PersistentCommandExecutor
comes in.
The PersistentCommandExecutor
will save the output of commands run previously so you can reference previously set values.
1from promptscript.executor import PersistentCommandExecutor
2
3
4persistent_command_executor = PersistentCommandExecutor()
5persistent_command_executor.run('x += 1', x=5)
6persistent_command_executor.run('show x')
6
Getting Output from PromptScript¶
To make output from PromptScript files avaliable in Python, you can use the yield
command. The first argument to yield
is
the key to make the value avaliable through, while the second argument is the value itself. If no yield statements are present
in the PromptScript code being executed, each of the command executors will return {}
.
Important
yield
does not operate like return in Python. Code after a yield
statement will be executed.
1chat_response = chat user_prompt, "gpt-4o", "API_KEY"
2yield "chat_response", chat_response
We can then access the value of chat_response:
1from promptscript.executor import FileExecutor
2
3
4file_executor = FileExecutor()
5output = file_executor.run('file.prompt', user_prompt='What is 2+2?')
6
7print(output)
{'chat_response': '2+2 equals 4.'}
Note
yield
also works the same way in the CommandExecutor
and PersistentCommandExecutor
.