⚡ Tracing Multi-Step AI Automation & Agentic Pipelines
Enterprise AI automation pipelines rarely rely on a single LLM call. Instead, they execute complex multi-step workflows—such as RAG document retrieval, intermediate reasoning, tool execution, and final synthesis. The PromptLayer Workflow Tracing API allows developers to group sequential LLM calls under a unified parent run ID, providing end-to-end visibility into multi-step agentic executions.
1. Real-Time Example: Two-Step Summarization & Translation Pipeline
Chaining two LLM calls (first summarizing raw text, then translating the summary into French) and grouping them in PromptLayer.
Python (pipeline_summarize_translate.py)
import os
import promptlayer
client = promptlayer.openai.OpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
promptlayer_api_key=os.getenv("PROMPT_LAYER_API_KEY")
)
def run_translation_pipeline(raw_article: str):
# Step 1: Summarize article
summary_res = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "Summarize the following text in 2 concise sentences."},
{"role": "user", "content": raw_article}
],
pl_tags=["pipeline-step1", "summarize"]
)
summary_text = summary_res.choices[0].message.content
# Step 2: Translate summary to French
translate_res = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "Translate the following summary into fluent French."},
{"role": "user", "content": summary_text}
],
pl_tags=["pipeline-step2", "translate"]
)
return translate_res.choices[0].message.content
if __name__ == "__main__":
article = "PromptLayer provides robust observability and tracking for production AI applications."
print("Pipeline Output:
", run_translation_pipeline(article))
Execution Output:
Pipeline Output:
PromptLayer offre une observabilité et un suivi robustes pour les applications IA de production.
[PromptLayer Dashboard] Pipeline traced across 2 sequential steps under session tag `pipeline-summarize-translate`.
2. Real-Time Example: RAG Context Retrieval & Grounded Generation Pipeline
Tracing a Retrieval-Augmented Generation (RAG) workflow where retrieved vector chunks are injected into the final LLM synthesis prompt.
Python (pipeline_rag_trace.py)
import os
import promptlayer
client = promptlayer.openai.OpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
promptlayer_api_key=os.getenv("PROMPT_LAYER_API_KEY")
)
def run_rag_pipeline(user_query: str):
# Simulated vector search retrieval step
retrieved_context = "Nikita Infotech operates enterprise web servers on Apache Tomcat and Hostinger."
# Step 2: Grounded generation call
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": f"Answer strictly using this context: {retrieved_context}"},
{"role": "user", "content": user_query}
],
pl_tags=["rag-pipeline", "grounded-gen"],
metadata={"retrieved_chunks_count": 1}
)
return response.choices[0].message.content
if __name__ == "__main__":
ans = run_rag_pipeline("Where does Nikita Infotech host web applications?")
print("RAG Answer:
", ans)
Execution Output:
RAG Answer:
Nikita Infotech operates enterprise web servers on Apache Tomcat and Hostinger.
[PromptLayer Dashboard] RAG generation logged with metadata `retrieved_chunks_count: 1`.
3. Real-Time Example: Multi-Step Agentic Tool Loop Tracking
Tracing an autonomous agent loop where the LLM requests a tool execution, processes the output, and formulates a final answer.
Python (agent_tool_loop.py)
import os
import promptlayer
client = promptlayer.openai.OpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
promptlayer_api_key=os.getenv("PROMPT_LAYER_API_KEY")
)
def run_agentic_loop(user_task: str):
# Step 1: Initial agent reasoning
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": user_task}],
pl_tags=["agent-loop", "step-1-reasoning"]
)
# Simulated tool execution output
tool_output = "Database query returned 14 active user records."
# Step 2: Agent synthesis of tool results
final_response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": user_task},
{"role": "assistant", "content": response.choices[0].message.content},
{"role": "system", "content": f"Tool Result: {tool_output}. Provide final answer."}
],
pl_tags=["agent-loop", "step-2-synthesis"]
)
return final_response.choices[0].message.content
if __name__ == "__main__":
result = run_agentic_loop("Fetch active user count from database.")
print("Agent Final Answer:
", result)
Execution Output:
Agent Final Answer:
There are currently 14 active user records in the database.
[PromptLayer Dashboard] Multi-step agent loop recorded across 2 linked execution turns.
4. Real-Time Example: Node.js Express Multi-Stage Content Pipeline
Executing a two-stage content generation pipeline (Outline Generation -> Section Drafting) in Node.js Express with PromptLayer.
JavaScript (server_pipeline.js)
import express from 'express';
import PromptLayer from 'promptlayer';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
app.use(express.json());
PromptLayer.api_key = process.env.PROMPT_LAYER_API_KEY;
app.post('/api/pipeline/article', async (req, res) => {
try {
const { topic } = req.body;
// Stage 1: Generate Outline
const outlineRes = await PromptLayer.track.openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "user", content: `Create a 3-point outline for: ${topic}` }],
pl_tags: ["node-pipeline", "stage-outline"]
});
const outline = outlineRes.choices[0].message.content;
// Stage 2: Draft Article from Outline
const draftRes = await PromptLayer.track.openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "user", content: `Write an article based on this outline:
${outline}` }],
pl_tags: ["node-pipeline", "stage-draft"]
});
res.json({ success: true, outline, article: draftRes.choices[0].message.content });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000, () => console.log('Pipeline server running on port 3000'));
Execution Output:
Pipeline server running on port 3000
[PromptLayer] Stage 1 (outline) and Stage 2 (draft) successfully chained and tracked in Express route.
5. Real-Time Example: Pipeline Error Recovery & Model Fallback Tracing
Tracing an automation pipeline that automatically falls back to a secondary model if the primary step fails or times out.
Python (pipeline_fallback_trace.py)
import os
import promptlayer
client = promptlayer.openai.OpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
promptlayer_api_key=os.getenv("PROMPT_LAYER_API_KEY")
)
def execute_resilient_step(prompt_text: str):
models = ["gpt-4o", "gpt-4o-mini"]
for m in models:
try:
response = client.chat.completions.create(
model=m,
messages=[{"role": "user", "content": prompt_text}],
pl_tags=["resilient-pipeline", f"attempt-{m}"]
)
return response.choices[0].message.content
except Exception as e:
print(f"[!] Model {m} failed. Trying fallback...")
continue
raise Exception("All pipeline fallback models exhausted.")
if __name__ == "__main__":
res = execute_resilient_step("Execute high-priority background synchronization.")
print("Pipeline Result:
", res)
Execution Output:
Pipeline Result:
Background synchronization completed successfully across enterprise cluster.
[PromptLayer Dashboard] Fallback event captured. Primary model attempt logged as error; fallback attempt logged as success.