Schedule and manage AI script jobs with SchedulerX

Updated at:
Copy as MD

This topic describes how to use SchedulerX to manage and schedule LangChain scripts.

Background

  • LangChain is a popular open-source framework for developing applications powered by large language models (LLMs). It lets you quickly build AI applications with Python or JavaScript.

  • Dify is an open-source, graphical development platform for LLM applications. It lets you quickly build AI agents and workflows with a visual, drag-and-drop canvas.

Hosting AI jobs on a scheduling system lets you manage script versions, configure time-based scheduling, improve resource utilization, implement throttling, and enhance observability.

image

Script management and scheduling

AI jobs are used in many business scenarios and often require time-based scheduling. Common use cases include:

  • Risk monitoring: Scan risk data every minute, use an LLM to analyze potential risk events, and send timely alerts.

  • Data analysis: Pull financial data daily, use an LLM for analysis, and provide decision-making advice for investors.

  • Content generation: Automatically summarize daily work and generate reports.

LangChain jobs are typically implemented as Python scripts. You can use the script job feature in SchedulerX to host your scripts and configure time-based scheduling.

SchedulerX supports script version history, which lets you easily compare and roll back to previous versions. For more information, see Script version history.

The following example shows a version comparison. The current version uses a chained call with PromptTemplate and LLMChain:

from langchain.prompts import PromptTemplate
from langchain.llms import Tongyi
from langchain.chains import LLMChain
llm = Tongyi(temperature=0.9)
prompt = PromptTemplate(
    input_variables=["product"],
    template="What is a good name for a company that makes {product}"
)
chain = LLMChain(llm=llm, prompt=prompt)
results = chain.invoke("colorful socks")
print(results)

The historical version v0.0.1 uses a direct call with llm.predict:

from langchain.llms import Tongyi
def main():
    llm = Tongyi(temperature=0.9)
    request = "What would be a good c..."
    response = llm.predict(request)
    print(response)
if __name__ == "__main__":
    main()

Prompt management

Prompts play a critical role in AI jobs. To achieve optimal results, you often need to adjust them. Hardcoding prompts directly into scripts increases maintenance costs and reduces flexibility. You can use the job parameters feature in SchedulerX to manage prompts effectively. In your LangChain script, use the system parameter(#{schedulerx.jobParameters}) provided by SchedulerX to dynamically retrieve job parameters. This allows for flexible configuration by replacing hardcoded prompt or PromptTemplate values.

SchedulerX provides two ways to manage prompts: obtaining prompts through time-based scheduling and passing prompts dynamically through API calls.

Prompts via time-based scheduling

  1. Log on to the MSE SchedulerX console. In the left-side navigation pane, click Tasks. In the top menu bar, select a region.

  2. Write a script when you create a script job, or edit the script of an existing job. The following code shows two examples:

    Prompt

    from langchain_community.llms import Tongyi
    from langchain.prompts import PromptTemplate
    from langchain.chains import LLMChain
    llm = Tongyi(model="qwen-plus")
    question = "#{schedulerx.jobParameters}"
    print("question:" + question)
    results = llm.invoke(question)
    print(results)

    PromptTemplate

    from langchain_community.llms import Tongyi
    from langchain.prompts import PromptTemplate
    from langchain.chains import LLMChain
    llm = Tongyi(model="qwen-plus")
    prompt = PromptTemplate(template="Please help me answer this question: {question}")
    chain = LLMChain(llm=llm, prompt=prompt)
    question = "#{schedulerx.jobParameters}"
    print("question:" + question)
    results = chain.invoke(question)
    print(results)
  3. In the Basic Configuration step of the Create task panel, configure the parameters and enter the Task parameters.

    Set Script Language to python, Execution Command topython3, File Format to unix, and Executor to Agent. Set Execution Mode to Standalone. In the Task parameters field, enter the prompt content, for example,Which is greater, 111 or 23?.

Prompts via API calls

You can also manually run jobs from the console or use API calls to dynamically set a new prompt. For example, with the PromptTemplate approach, instance parameters from a manual run override the static job parameters configured for the job. Follow these steps:

  1. In the left-side navigation pane, click Tasks. Find the target job and click Run once in the Operation column.

  2. In the Run Task Confirmation dialog box that appears, select TargetMachine, configure the Instance Parameters, and then click OK.

    The instance parameters will override the static job parameters defined in the job configuration.

Resource utilization

SchedulerX supports two modes for script execution:

  • script job: Deploy theschedulerx-agent on an ECS instance. Each execution forks a child process to run the script. This mode is suitable for low-resource jobs that are scheduled frequently.

  • Kubernetes job: Deploy theschedulerx-agent on a Kubernetes cluster. Each execution launches a new pod to run the script. This mode is suitable for resource-intensive jobs that run infrequently.

Combining them can significantly improve resource utilization.

image

The following table compares script execution on ECS instances and Kubernetes clusters.

Execution on ECS

Execution on Kubernetes

Dependency installation

Manually deploy dependencies on the ECS instance in advance.

Build dependencies into a base image. If dependencies change, you must rebuild the base image.

Frequent script scheduling

Recommended. Forking a child process for each execution is fast.

Not recommended. Pulling an image and starting a pod for each execution is relatively slow.

Infrequent script scheduling

Not recommended. ECS resources must be provisioned in advance. If a job runs only once a day, resource utilization is low.

Recommended. A pod executes the job and is automatically destroyed upon completion. This is more cost-effective for jobs that run infrequently.

Low script resource consumption

Recommended. Forking a child process reuses the resources of the ECS instance, which is cost-effective.

Not recommended. Each execution requires launching a new pod, which consumes extra resources and increases costs.

High script resource consumption

Not recommended. Very large jobs may saturate ECS resources and affect other running tasks.

Recommended. Kubernetes load balancing launches a new pod for each script execution, ensuring high stability.

Throttling

Use case: You have a set of offline jobs that need to run after midnight each day to process the previous day's data. The core jobs must be completed before business starts at 9:00 AM. Developers might schedule all these jobs to run at the same time, such as 00:30 every day.

When many jobs are scheduled simultaneously, they can overwhelm your ECS instances. Although running scripts on Kubernetes can alleviate some of this pressure, the traffic burst can still overload downstream services like databases. The best solution for these traffic bursts is throttling. Throttling is an effective strategy to manage uneven scheduling from time-based jobs, especially during traffic spikes, and improve resource utilization.

image

As shown in the preceding figure, SchedulerX supports application-level throttling:

  1. Each application has a priority queue that organizes jobs by priority to ensure that core jobs are executed first. A job's priority applies only within its application and does not affect other applications.

  2. Each application also has a concurrency queue that controls the number of concurrent job executions. The concurrency limits of different applications are isolated from each other.

  3. When a job in the concurrency queue completes and frees up a slot, the next job is taken from the head of the priority queue and moved to the concurrency queue for execution.

Automatic retry

Large language model (LLM) calls can be unstable, causing temporary issues like token limits or backend service exceptions. These issues are often transient and can be resolved with a retry.

SchedulerX provides an automatic retry feature for failed jobs, which can be dynamically configured in the console. In practice, using this feature for LangChain scripts significantly reduces failures caused by backend LLM throttling or service unavailability, improving the job success rate by at least one 'nine' (e.g., from 99% to 99.9%).

To enable automatic retry, expand the Advanced Configuration section on the job configuration page, and set the Retry Count on Task Failure and Retry Interval on Task Failure (in seconds).

Job orchestration

SchedulerX provides visual job orchestration. If your LangChain scripts have dependencies on each other, you can easily create a workflow. You can even orchestrate different job types within the same workflow.

image

As shown in the figure:

  1. First, a shell script pulls data from the big data platform.

  2. Next, a Java job cleanses the merchant and user data.

  3. Then, a LangChain job performs LLM-based analysis on the cleansed data.

  4. Finally, a Python script generates a report.

Enterprise-grade observability

SchedulerX is natively integrated with various cloud services to provide enterprise-grade observability.

Scheduling dashboard

The scheduling dashboard provides an overview of job execution status. You can filter the view by namespace and application.

The overview page includes the Professional Edition Statistics and Professional Edition Job Summary sections, which display metrics such as Total Jobs, Disabled Jobs, Online Workers, and Currently Running Job Instances. The Professional Edition Job Instance Summary section shows the number of Triggers, Successful Executions, and Failed Executions, with a line chart illustrating the trend of each metric over time.

Monitoring and alerting

A rapid response is crucial to prevent service disruptions when a job fails. SchedulerX supports application-level alerting, which can be configured down to the individual job level. The following is an example of a job-level alert configuration.

In this example of a job-level alert configuration, Timeout Alert is enabled with a timeout of60 seconds, and Terminate on Timeout is disabled. Success Notification is disabled, but Failure Alert is enabled, set to trigger after1 consecutive failure. No Available Machine Alert is also enabled. The notification channel is set to Custom, with Webhook selected. The recipient is a Contact Group named Test Group A.

Log service

When you run your script with theschedulerx-agent, the integrated log service automatically records all standard output and exceptions. Follow these steps to access the logs:

  1. In the left-side navigation pane, click Tasks. In the top menu bar, select a region.

  2. Click Create task. In the Basic Configuration step of the Create task panel, configure the required parameters.

    The script content is as follows:

    from langchain_community.llms import Tongyi
    from langchain.prompts import PromptTemplate
    from langchain.chains import LLMChain
    llm = Tongyi(model="qwen-plus")
    prompt = PromptTemplate(template="Please help me answer this question: {question}")
    chain = LLMChain(llm=llm, prompt=prompt)
    question = "#{schedulerx.jobParameters}"
    print("question:" + question)
    results = chain.invoke(question)
    print(results)

    Configure the Task parameters as needed.

  3. Complete the Timing configuration and Notification configuration steps to finish setting up the script to run withschedulerx-agent.

  4. In the job list, find the job you created and click Run once in the Operation column.

  5. In the left-side navigation pane, click Workflows. Find the target execution record and click Log in the Operation column to view the log details.

Contact us

If you have other requirements for AI job scheduling, join the DingTalk group (ID:23103656).