# \[DMP 2024\] Automatically generate job expressions from prompts

**URL:** <https://community.openfn.org/t/dmp-2024-automatically-generate-job-expressions-from-prompts/450>\
**Category:** Uncategorized\
**Created:** [June 13, 2024, 11:23am UTC](https://community.openfn.org/t/dmp-2024-automatically-generate-job-expressions-from-prompts/450 "2024-06-13T11:23:48Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ayodele](https://community.openfn.org/user_avatar/community.openfn.org/ayodele/32/162_2.png) [@ayodele](https://community.openfn.org/u/ayodele)\
**Post date:** [June 13, 2024, 11:23am UTC](https://community.openfn.org/t/dmp-2024-automatically-generate-job-expressions-from-prompts/450/1 "2024-06-13T11:23:48Z")

</div>

We are excited to participate in the 2024 Direct Mentoring Program by supporting two software engineers interested in contributing to Open Source Gov4Tech programs. This public channel is dedicated to discussing our sponsored feature: \*\* Automatically generate job expressions from prompts\*\*.

Mentors, contributors, and community members are welcome to ask and answer questions related to this topic here.

Feel free to engage and share your insights!

> <https://github.com/OpenFn/kit/issues/620>
>
> \## Overview
> 
> When building workflows, users spend most of their time writing s…imple to advanced jobs on OpenFn. We'd like to harness AI to write job expressions based on english text requirements
> 
> This feature is able to generate a job expression given some sample input data, the adaptor specification (name and version), and a text description of the desired output/instruction. It is expected that the generated job expression can be executed in the CLI.
> 
> \## Deliverables
> 
> \* A new service in the apollo repo called gen\_job
> \* The service should receive a bunch of inputs as JSON, and return JSON with a string expression
> 
> We are looking for a new python module to be implemented on apollo. This can be called from the existing \`openfn apollo\` command, but has no direct CLI implementation.
> 
> \### Inputs
> We expect the following JSON payload to be submitted to the endpoint:
> 
> \`\`\`
> {
> "expression": "the user's existing js expression"
> "adaptor": "@openfn/language-salesforce@1.0.0"
> "state": { /\* input state\*/ }
> "instruction": "a natural language command"
> }
> \`\`\`
> 
> All of these inputs should be considered optional - if any are excluded, the generation should continue as best it can.
> 
> We may also require metadata to be included with this request - such as which model to use, perhaps parameters to drive the model, and an api key.
> 
> \### Output
> 
> The service should return an expression nested in a JSON object
> 
> \`\`\`
> {
> expression: "fn(s =\> s)"
> }
> \`\`\`
> 
> Note that the expression string should be pure code, suitable for inserting into a code editor. No natural language, no markdown annotations of any kind.
> 
> 
> \## Implementation Notes
> 
> Highly valuable to use, and likely critical to this work, are the following two issues:
> 
> \* https://github.com/OpenFn/apollo/issues/71
> \* https://github.com/OpenFn/apollo/issues/72
> 
> Once a basic job expression generator has been created, it may be wise to implement and integrate these issues.
> 
> \## Sample Inputs 
> 
> 1. One or more sample inputs (valid JSON) which can serve as the initial \`state\` for the job
> \`\`\`json
> {
> "data": {
> "name": "bukayo saka",
> "gender": "male"
> }
> }
> \`\`\`
> 
> 2. The adaptor specification will be in the form of “@openfn/language-dhis2@1.2.3” or “@openfn/language-common@1.2.3”
> 
> \`\`\`
> @openfn/language-dhis2@4.0.3
> \`\`\`
> 
> 3. The text instructions will be in the form of: “Create a new object based on patient object, and set it’s status attribute “enrolled” or “Create a trackedEntityInstance record in DHIS2 using the data from state.person”
> 
> \`\`\`
> Create a new trackedEntityInstance "person" in dhis2 for the "dWOAzMcK2Wt" orgUnit.
> \`\`\`
> 
> \*\*Sample Output\*\*
> 
> Given the inputs above, we'd expect the output code to be:
> \`\`\`js
> create('trackedEntityInstances', {
> orgUnit: "dWOAzMcK2Wt",
> trackedEntityType: 'nEenWmSyUEp',
> attributes: \[
> { attribute: 'w75KJ2mc4zz', value: state.data.name.split(' ')\[0\] },
> { attribute: 'zDhUuAYrxNC', value: state.data.name.split(' ')\[1\] },
> { attribute: 'cejWyOfXge6', value: state.data.gender },
> \],
> });
> \`\`\`
> 
> \## Background 
> 
> OpenFn is an open source platform for data integration and workflow automation accessible to users thorough a \[CLI\](https://github.com/OpenFn/kit/tree/main/packages/cli) or a \[web UI\](http://github.com/openfn/lightning). 
> 
> To use OpenFn, users build \`workflows\` which are made up of one or more steps—at the time of writing these are all JavaScript-based "jobs" (the JS code itself is called a "job expression"). These \`jobs\` make use of adaptors to perform their tasks, e.g. Make a request to an API endpoint, update a record in a database, aggregate data, send data to an external platform. 
> 
> Here is an example of a job that uses the \[common adaptor\](https://docs.openfn.org/adaptors/packages/common-docs) to transform an input data (in state) into a new object transformedPatient
> 
> \`\`\`js
> fn(state =\> {
> const transformedPatient = { ...state.data.patient, status: "enrolled" }
> return { ...state, transformedPatient };
> })
> \`\`\`
> 
> And here is another job expression that uses the \[dhis2 adaptor\](https://docs.openfn.org/adaptors/packages/dhis2-docs) to create a new patient record referred to as trackedEntityInstance. 
> 
> \`\`\`js
> create('trackedEntityInstances', {
> orgUnit: "dWOAzMcK2Wt" /\*Alkalia CHP\*/,
> trackedEntityType: 'nEenWmSyUEp' /\*Person\*/,
> attributes: \[
> { attribute: 'w75KJ2mc4zz', value: state.person.age.first\_name },
> { attribute: 'zDhUuAYrxNC', value: state.person.age.last\_name },
> { attribute: 'cejWyOfXge6', value: state.person.age.gender },
> \],
> });
> \`\`\`
> Learn more about \[adaptors here\](https://docs.openfn.org/adaptors) and how they are used in OpenFn workflows. 
> 
> 
> \## Documentation: 
> \- \[How to write jobs\](https://docs.openfn.org/documentation/jobs/job-writing-guide)
> \- \[Workflows\](https://docs.openfn.org/documentation/build/workflows)
> \- \[Adaptors\](https://docs.openfn.org/adaptors)

---

<div class="post-metadata">

**Author:** ![satyammattoo](https://community.openfn.org/user_avatar/community.openfn.org/satyammattoo/32/189_2.png) [@satyammattoo](https://community.openfn.org/u/satyammattoo)\
**Post date:** [June 16, 2024, 11:23am UTC](https://community.openfn.org/t/dmp-2024-automatically-generate-job-expressions-from-prompts/450/2 "2024-06-16T11:23:51Z")

</div>

Thank you for giving this opportunity. I am pleased to inform you that I have been selected for this project.

For this feature, I have planned the following approach:

We can leverage the existing Apollo (formerly Gen) repository. I noticed that you have set up the initial framework for making calls to Apollo services through the CLI.

To move forward, I propose creating a service for job generation using the following inputs. Users would provide these inputs via a `.json` file:

```auto
{
  "api_key": "apiKey",
  "adaptor": "@openfn/language-dhis2@4.0.3",
  "data": {
    "name": "bukayo saka",
    "gender": "male"
  },
  "signature": "Create a new trackedEntityInstance 'person' in dhis2 for the 'dWOAzMcK2Wt' orgUnit."
}

```

The CLI command `openfn apollo job_expression_generator tmp/data.json -o tmp/output.json` would then be used to call the job generation service on the Apollo server and return the desired result.

For job generation on the server, we can create a job\_expression\_generator service. This service would parse inputs from the `.json` file and generate the required output. Below is a sample implementation:

```auto
from util import DictObj, createLogger

from .utils import (
    generate_job_prompt,
)

from inference import inference

logger = createLogger("job_expression_generator")

class Payload(DictObj):
    api_key: str
    adaptor: str
    signature: str
    data: dict

# Generate job expression based on the input data, adaptor specification, and instructions
def main(dataDict) -> str:
    data = Payload(dataDict)
    logger.info("Running job expression generator with adaptor {}".format(data.adaptor))
    result = generate(data.adaptor_spec, data.instructions, data.sample_input, data.get("api_key"))
    logger.success("Job expression generation complete!")
    return result

def generate(adaptor_spec, instructions, sample_input, key) -> str:
    prompt = generate_job_prompt(adaptor_spec, instructions, sample_input)

    result = inference.generate("gpt3_turbo", prompt, {"key": key})

    return result

```

The prompt for this might look like:

```auto
prompts = {
    "job_expression": (
        "You are a helpful Javascript code assistant.",
        "Below is a description of a task along with the adaptor specification and sample input data. "
        "Generate a JavaScript job expression that performs the task described. Ensure the job expression "
        "follows the conventions defined in the adaptor documentation.\n\n"
        "Adaptor: {adaptor}\n"
        "Instructions: {signature}\n"
        "Sample Input: {sample_input}\n"
        "====",
    ),
}

```

For testing, we can run this with sample inputs from the CLI, write tests in the Apollo repo itself, or both.

I believe this approach aligns with what you’re looking for. Could you please provide feedback on whether I am on the right track or suggest any improvements? Your guidance would be greatly appreciated.
