Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add context.callApi #37

Merged
merged 7 commits into from
Dec 23, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified bun.lockb
Binary file not shown.
7 changes: 3 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,12 @@
"husky": "^9.1.6",
"next": "^14.2.14",
"prettier": "3.3.3",
"tsc": "^2.0.4",
"tsup": "^8.3.0",
"typescript": "^5.6.3",
"typescript-eslint": "^8.8.0"
"typescript": "^5.7.2",
"typescript-eslint": "^8.18.0"
},
"dependencies": {
"@upstash/qstash": "^2.7.17"
"@upstash/qstash": "^2.7.19"
},
"directories": {
"example": "examples"
Expand Down
320 changes: 320 additions & 0 deletions src/context/context.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ import {
WORKFLOW_PROTOCOL_VERSION_HEADER,
WORKFLOW_URL_HEADER,
} from "../constants";
import { upstash, openai } from "@upstash/qstash";
import { anthropic } from "@upstash/qstash";
import { resend } from "@upstash/qstash";

describe("context tests", () => {
const token = nanoid();
Expand Down Expand Up @@ -426,4 +429,321 @@ describe("context tests", () => {
}
throw new Error("Test error: context.cancel should have thrown abort error.");
});

describe("context.callApi step", () => {
test("should throw if provider isn't provdided", async () => {
const context = new WorkflowContext({
qstashClient,
initialPayload: "my-payload",
steps: [],
url: WORKFLOW_ENDPOINT,
headers: new Headers() as Headers,
workflowRunId: "wfr-id",
retries: 2,
});

await mockQStashServer({
execute: () => {
const throws = () =>
context.callApi("call step", {
api: {
name: "llm",
},
});
expect(throws).toThrowError("A Provider must be provided.");
},
responseFields: {
status: 200,
body: "msgId",
},
receivesRequest: false,
});
});

test("should throw if provider is upstash", async () => {
const context = new WorkflowContext({
qstashClient,
initialPayload: "my-payload",
steps: [],
url: WORKFLOW_ENDPOINT,
headers: new Headers() as Headers,
workflowRunId: "wfr-id",
retries: 2,
});

await mockQStashServer({
execute: () => {
const throws = () =>
context.callApi("call step", {
api: {
name: "llm",
provider: upstash(),
},
});
expect(throws).toThrowError("Upstash provider isn't supported.");
},
responseFields: {
status: 200,
body: "msgId",
},
receivesRequest: false,
});
});

test("should work with openai provider", async () => {
const context = new WorkflowContext({
qstashClient,
initialPayload: "my-payload",
steps: [],
url: WORKFLOW_ENDPOINT,
headers: new Headers() as Headers,
workflowRunId: "wfr-id",
retries: 2,
});

const openAIToken = `hello-there`;
const stepName = "call step";
const timeout = "10s";
await mockQStashServer({
execute: () => {
const throws = () =>
context.callApi(stepName, {
timeout,
api: {
name: "llm",
provider: openai({ token: openAIToken }),
},
body: {
model: "gpt-4o",
messages: [
{
role: "system",
content: "Assistant says hello!",
},
{ role: "user", content: "User shouts there!" },
],
},
});
expect(throws).toThrowError(
"This is an Upstash Workflow error thrown after a step executes"
);
},
responseFields: {
status: 200,
body: "msgId",
},
receivesRequest: {
method: "POST",
url: `${MOCK_QSTASH_SERVER_URL}/v2/batch`,
token,
body: [
{
body: '{"model":"gpt-4o","messages":[{"role":"system","content":"Assistant says hello!"},{"role":"user","content":"User shouts there!"}]}',
destination: "https://api.openai.com/v1/chat/completions",
headers: {
"upstash-timeout": timeout,
"content-type": "application/json",
"upstash-callback": WORKFLOW_ENDPOINT,
"upstash-callback-feature-set": "LazyFetch,InitialBody",
"upstash-callback-forward-upstash-workflow-callback": "true",
"upstash-callback-forward-upstash-workflow-concurrent": "1",
"upstash-callback-forward-upstash-workflow-contenttype": "application/json",
"upstash-callback-forward-upstash-workflow-stepid": "1",
"upstash-callback-forward-upstash-workflow-stepname": stepName,
"upstash-callback-forward-upstash-workflow-steptype": "Call",
"upstash-callback-retries": "2",
"upstash-callback-workflow-calltype": "fromCallback",
"upstash-callback-workflow-init": "false",
"upstash-callback-workflow-runid": "wfr-id",
"upstash-callback-workflow-url": WORKFLOW_ENDPOINT,
"upstash-failure-callback-retries": "2",
"upstash-feature-set": "WF_NoDelete,InitialBody",
"upstash-forward-authorization": `Bearer ${openAIToken}`,
"upstash-forward-content-type": "application/json",
"upstash-method": "POST",
"upstash-retries": "0",
"upstash-workflow-calltype": "toCallback",
"upstash-workflow-init": "false",
"upstash-workflow-runid": "wfr-id",
"upstash-workflow-url": WORKFLOW_ENDPOINT,
},
},
],
},
});
});

test("should work with resend provider", async () => {
const context = new WorkflowContext({
qstashClient,
initialPayload: "my-payload",
steps: [],
url: WORKFLOW_ENDPOINT,
headers: new Headers() as Headers,
workflowRunId: "wfr-id",
retries: 2,
});

const resendToken = `hello-there`;
const stepName = "call step";
const timeout = "10s";
await mockQStashServer({
execute: () => {
const throws = () =>
context.callApi(stepName, {
timeout,
api: {
name: "email",
provider: resend({ token: resendToken }),
},
body: {
from: "Acme <onboarding@resend.dev>",
to: ["delivered@resend.dev"],
subject: "Hello World",
html: "<p>It works!</p>",
},
headers: {
"content-type": "application/json",
},
});
expect(throws).toThrowError(
"This is an Upstash Workflow error thrown after a step executes"
);
},
responseFields: {
status: 200,
body: "msgId",
},
receivesRequest: {
method: "POST",
url: `${MOCK_QSTASH_SERVER_URL}/v2/batch`,
token,
body: [
{
body: '{"from":"Acme <onboarding@resend.dev>","to":["delivered@resend.dev"],"subject":"Hello World","html":"<p>It works!</p>"}',
destination: "https://api.resend.com/emails",
headers: {
"upstash-timeout": timeout,
"content-type": "application/json",
"upstash-callback": WORKFLOW_ENDPOINT,
"upstash-callback-feature-set": "LazyFetch,InitialBody",
"upstash-callback-forward-upstash-workflow-callback": "true",
"upstash-callback-forward-upstash-workflow-concurrent": "1",
"upstash-callback-forward-upstash-workflow-contenttype": "application/json",
"upstash-callback-forward-upstash-workflow-stepid": "1",
"upstash-callback-forward-upstash-workflow-stepname": stepName,
"upstash-callback-forward-upstash-workflow-steptype": "Call",
"upstash-callback-retries": "2",
"upstash-callback-workflow-calltype": "fromCallback",
"upstash-callback-workflow-init": "false",
"upstash-callback-workflow-runid": "wfr-id",
"upstash-callback-workflow-url": WORKFLOW_ENDPOINT,
"upstash-failure-callback-retries": "2",
"upstash-feature-set": "WF_NoDelete,InitialBody",
"upstash-forward-authorization": `Bearer ${resendToken}`,
"upstash-forward-content-type": "application/json",
"upstash-method": "POST",
"upstash-retries": "0",
"upstash-workflow-calltype": "toCallback",
"upstash-workflow-init": "false",
"upstash-workflow-runid": "wfr-id",
"upstash-workflow-url": WORKFLOW_ENDPOINT,
},
},
],
},
});
});

test("should override method and add headers if passed", async () => {
const context = new WorkflowContext({
qstashClient,
initialPayload: "my-payload",
steps: [],
url: WORKFLOW_ENDPOINT,
headers: new Headers() as Headers,
workflowRunId: "wfr-id",
retries: 2,
});

const anthropicToken = `hello-there`;
const stepName = "call step";

const header = "header-foo";
const headerValue = "header-value-bar";

const method = "GET";

await mockQStashServer({
execute: () => {
const throws = () =>
context.callApi(stepName, {
api: {
name: "llm",
provider: anthropic({ token: anthropicToken }),
},
method,
headers: {
[header]: headerValue,
},
body: {
model: "gpt-4o",
messages: [
{
role: "system",
content: "Assistant says hello!",
},
{ role: "user", content: "User shouts there!" },
],
},
});
expect(throws).toThrowError(
"This is an Upstash Workflow error thrown after a step executes"
);
},
responseFields: {
status: 200,
body: "msgId",
},
receivesRequest: {
method: "POST",
url: `${MOCK_QSTASH_SERVER_URL}/v2/batch`,
token,
body: [
{
body: '{"model":"gpt-4o","messages":[{"role":"system","content":"Assistant says hello!"},{"role":"user","content":"User shouts there!"}]}',
destination: "https://api.anthropic.com/v1/messages",
headers: {
[`upstash-forward-${header}`]: headerValue,
"content-type": "application/json",
"upstash-callback": WORKFLOW_ENDPOINT,
"upstash-callback-feature-set": "LazyFetch,InitialBody",
"upstash-callback-forward-upstash-workflow-callback": "true",
"upstash-callback-forward-upstash-workflow-concurrent": "1",
"upstash-callback-forward-upstash-workflow-contenttype": "application/json",
"upstash-callback-forward-upstash-workflow-stepid": "1",
"upstash-callback-forward-upstash-workflow-stepname": stepName,
"upstash-callback-forward-upstash-workflow-steptype": "Call",
"upstash-callback-retries": "2",
"upstash-callback-workflow-calltype": "fromCallback",
"upstash-callback-workflow-init": "false",
"upstash-callback-workflow-runid": "wfr-id",
"upstash-callback-workflow-url": WORKFLOW_ENDPOINT,
"upstash-failure-callback-retries": "2",
"upstash-feature-set": "WF_NoDelete,InitialBody",
"upstash-forward-x-api-key": anthropicToken,
"upstash-forward-content-type": "application/json",
"upstash-method": method,
"upstash-retries": "0",
"upstash-workflow-calltype": "toCallback",
"upstash-workflow-init": "false",
"upstash-workflow-runid": "wfr-id",
"upstash-workflow-url": WORKFLOW_ENDPOINT,
},
},
],
},
});
});
});
});
22 changes: 22 additions & 0 deletions src/context/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import type { WorkflowLogger } from "../logger";
import { DEFAULT_RETRIES } from "../constants";
import { WorkflowAbort } from "../error";
import type { Duration } from "../types";
import { getProviderInfo } from "./provider";

/**
* Upstash Workflow context
Expand Down Expand Up @@ -351,6 +352,27 @@ export class WorkflowContext<TInitialPayload = unknown> {
}
}

public async callApi<TResult = unknown>(
stepName: string,
settings: {
api: Parameters<typeof getProviderInfo>[0];
} & Omit<Parameters<WorkflowContext["call"]>[1], "url">
): Promise<CallResponse<TResult>> {
const { url, appendHeaders, method } = getProviderInfo(settings.api);
const { method: userMethod, body, headers = {}, retries = 0, timeout } = settings;
return await this.call(stepName, {
url,
method: userMethod ?? method,
body,
headers: {
...appendHeaders,
...headers,
},
retries,
timeout,
});
}

/**
* Pauses workflow execution until a specific event occurs or a timeout is reached.
*
Expand Down
Loading
Loading