Ash FrameworkAF
Ash Frameworkโ€ข7mo agoโ€ข
35 replies
hyperion_zw

How to conditionally do `run_oban_trigger`?

I am modifing code from the Ash.AI chat example. I could understand that whenever a message is created, it goes through one of the change change run_oban_trigger(:respond) which triggers
the trigger :respond.

So, whenever user type a message and enter, an LLM response is generated. I want to change it to only user explicitly type like "@M, xxxx", then the response from LLM should be triggered.
How to do that?

One solution is to modify the Response module, is it a good thing? because once reach here, I belive an Oban job is already enqueued.
Can I do trigger the oban in with some condition? especially it would be better to do so in a seperate module, so I could implement complex logic.

Thanks a lot ๐Ÿ™‚
Solution
  @impl true
  def change(changeset, _opts, _context) do
    case Ash.Changeset.get_attribute(changeset, :text) do
      nil ->
        changeset

      text ->
        Logger.info("->> text: #{text}")

        if String.contains?(text, "@M") do
          new_text = String.replace(text, "@M", "")
          Logger.info("->> need to generate LLM response")

          changeset
          |> Ash.Changeset.set_argument(:text, new_text)
          |> Ash.Changeset.after_action(fn changeset, result -> 
            AshOban.run_trigger(result, :respond)
            {:ok, result}
          end)
        else
          Logger.info("->> do not generate LLM response")
          changeset
        end
    end
  end
Was this page helpful?