import { DynamicStructuredTool } from "@langchain/core/tools";
import { z } from "zod";
/**
* Creates a LangChain tool for generating PDFs from markdown text using the Refile API
*
* @param {string} refileApiKey - Your Refile API key
* @param {string} [theme="modern"] - PDF theme (e.g., "modern", "minimal", "academic")
* @param {string} [pageNumeration="center"] - Page number position ("center", "right", "none")
* @param {string} [pageSize="A4"] - Page size (e.g., "A4", "Letter", "Legal")
* @param {string} [refileApiBaseUrl="https://www.refile.co/api/v1"] - Refile API base URL
* @returns {DynamicStructuredTool} - LangChain compatible tool for PDF generation
*/
export function createRefileTool(
refileApiKey,
theme = "modern",
pageNumeration = "center",
pageSize = "A4",
refileApiBaseUrl = "https://www.refile.co/api/v1"
) {
return new DynamicStructuredTool({
name: "generatePdf",
description: "Generate a PDF document from markdown text",
schema: z.object({
markdown: z
.string()
.describe("The markdown content to convert into a PDF"),
}),
func: async ({ markdown }) => {
// Prepare request options
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${refileApiKey}`,
},
body: JSON.stringify({
markdown: markdown,
theme: theme,
pageNumeration: pageNumeration,
pageSize: pageSize,
output: "url",
}),
};
try {
// Make the API call
const response = await fetch(
`${refileApiBaseUrl}/pdf/markdown`,
options
);
if (!response.ok) {
const errorData = await response.json().catch(() => null);
throw new Error(
`Failed to generate PDF: ${response.status} ${response.statusText}${
errorData ? ` - ${JSON.stringify(errorData)}` : ""
}`
);
}
// Parse and return the response
const data = await response.json();
return JSON.stringify({
url: data.url,
success: true,
message: "PDF generated successfully",
});
} catch (error) {
console.error("Error generating PDF:", error);
return JSON.stringify({
success: false,
error: error.message,
message: "Failed to generate PDF",
});
}
},
});
}