pi-langfuse 1.4.0 → 1.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -1
- package/index.ts +61 -44
- package/package.json +11 -1
- package/src/handlers/tool.ts +23 -6
- package/src/state.ts +126 -23
- package/src/types.ts +2 -0
- package/src/utils.ts +4 -0
- package/.agents/skills/langfuse/SKILL.md +0 -140
- package/.agents/skills/langfuse/references/cli.md +0 -51
- package/.agents/skills/langfuse/references/error-analysis.md +0 -100
- package/.agents/skills/langfuse/references/instrumentation.md +0 -140
- package/.agents/skills/langfuse/references/prompt-migration.md +0 -234
- package/.agents/skills/langfuse/references/sdk-upgrade.md +0 -181
- package/.agents/skills/langfuse/references/skill-feedback.md +0 -52
- package/.agents/skills/langfuse/references/user-feedback.md +0 -88
- package/AGENTS.md +0 -48
- package/AGENTS_CN.md +0 -57
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
# Langfuse CLI Reference
|
|
2
|
-
|
|
3
|
-
Documentation: https://langfuse.com/docs/api-and-data-platform/features/cli
|
|
4
|
-
|
|
5
|
-
## Install
|
|
6
|
-
|
|
7
|
-
```bash
|
|
8
|
-
# Run directly (recommended)
|
|
9
|
-
npx langfuse-cli api <resource> <action>
|
|
10
|
-
bunx langfuse-cli api <resource> <action>
|
|
11
|
-
|
|
12
|
-
# Or install globally
|
|
13
|
-
npm i -g langfuse-cli
|
|
14
|
-
langfuse api <resource> <action>
|
|
15
|
-
```
|
|
16
|
-
|
|
17
|
-
## Discovery
|
|
18
|
-
|
|
19
|
-
```bash
|
|
20
|
-
# List all resources and auth info
|
|
21
|
-
langfuse api __schema
|
|
22
|
-
|
|
23
|
-
# List actions for a resource
|
|
24
|
-
langfuse api <resource> --help
|
|
25
|
-
|
|
26
|
-
# Show args/options for a specific action
|
|
27
|
-
langfuse api <resource> <action> --help
|
|
28
|
-
|
|
29
|
-
# Preview the curl command without executing
|
|
30
|
-
langfuse api <resource> <action> --curl
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
## Credentials
|
|
34
|
-
|
|
35
|
-
Set environment variables:
|
|
36
|
-
|
|
37
|
-
```bash
|
|
38
|
-
export LANGFUSE_PUBLIC_KEY=pk-lf-...
|
|
39
|
-
export LANGFUSE_SECRET_KEY=sk-lf-...
|
|
40
|
-
export LANGFUSE_HOST=https://cloud.langfuse.com
|
|
41
|
-
```
|
|
42
|
-
|
|
43
|
-
## Tips
|
|
44
|
-
|
|
45
|
-
- Use `--json` for machine-readable JSON output
|
|
46
|
-
- Use `--curl` to preview the HTTP request without executing
|
|
47
|
-
- Pagination: use `--limit` and `--page` on list endpoints
|
|
48
|
-
- All list commands support filtering — check `<resource> <action> --help` for available options
|
|
49
|
-
- Prefer `observations-v2s` over `observations` — the v2 endpoint returns richer data
|
|
50
|
-
- Prefer `metrics-v2s` over `metrics` — the v2 endpoint returns richer data
|
|
51
|
-
- Prefer `score-v2s` over `scores` — the v1 `scores` resource only supports create/delete; use `score-v2s` for list and get operations
|
|
@@ -1,100 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: langfuse-error-analysis
|
|
3
|
-
description: Deep-dive error analysis of an LLM pipeline or AI application using Langfuse traces.
|
|
4
|
-
Use this skill whenever the user wants to understand why their AI system is producing
|
|
5
|
-
bad outputs, where their pipeline is failing, how to categorise or label failures,
|
|
6
|
-
what to prioritise fixing, or how to set up evaluators. Also trigger for "review my
|
|
7
|
-
traces", "my outputs look wrong", "help me debug my LLM app", "I want to analyse
|
|
8
|
-
errors", "build a failure taxonomy", "what's going wrong with my pipeline", or any
|
|
9
|
-
request to systematically inspect, annotate, or score Langfuse traces. If the user
|
|
10
|
-
is trying to understand or improve the quality of an AI system's outputs, use this skill.
|
|
11
|
-
---
|
|
12
|
-
|
|
13
|
-
# Error Analysis
|
|
14
|
-
|
|
15
|
-
## Primary Guide
|
|
16
|
-
|
|
17
|
-
**1. Fetch the guide in this blogpost**
|
|
18
|
-
|
|
19
|
-
https://langfuse.com/guides/cookbook/error-analysis-llm-applications.md
|
|
20
|
-
|
|
21
|
-
If fetch is not available query for langfuse.com error analysis guide
|
|
22
|
-
|
|
23
|
-
Read it in full. It defines the authoritative 5-step process (sample selection → open coding → clustering → labelling → deciding what to fix).
|
|
24
|
-
|
|
25
|
-
**2. Guide the user through this step by step**
|
|
26
|
-
|
|
27
|
-
You as a coding agent and the user go through this together to perform a full error analysis with their data in langfuse. Do everything you can achieve via CLI (look up traces, create annotation queues, ...) for the user. Provide them with direct links to UI wherever their action is required. Be proactive and narrate what is going on for the user.
|
|
28
|
-
|
|
29
|
-
## Rules CRITICAL
|
|
30
|
-
Use Langfuse CLI wherever possible
|
|
31
|
-
Use charts where possible to display data
|
|
32
|
-
|
|
33
|
-
---
|
|
34
|
-
|
|
35
|
-
## Langfuse Implementation Notes
|
|
36
|
-
|
|
37
|
-
The guide describes the process. These notes cover the Langfuse-specific API and CLI mechanics required to execute it.
|
|
38
|
-
|
|
39
|
-
### Credentials
|
|
40
|
-
|
|
41
|
-
```bash
|
|
42
|
-
echo $LANGFUSE_PUBLIC_KEY # pk-lf-...
|
|
43
|
-
echo $LANGFUSE_SECRET_KEY # sk-lf-...
|
|
44
|
-
echo $LANGFUSE_HOST # https://cloud.langfuse.com (EU), https://us.cloud.langfuse.com (US), https://jp.cloud.langfuse.com (JP) or self-hosted
|
|
45
|
-
```
|
|
46
|
-
|
|
47
|
-
If not set, check `.env` in the project root: `export $(grep -v '^#' .env | xargs)`. If `LANGFUSE_BASE_URL` is used instead of `LANGFUSE_HOST`, run `export LANGFUSE_HOST="$LANGFUSE_BASE_URL"`.
|
|
48
|
-
|
|
49
|
-
```bash
|
|
50
|
-
AUTH=$(echo -n "${LANGFUSE_PUBLIC_KEY}:${LANGFUSE_SECRET_KEY}" | base64)
|
|
51
|
-
|
|
52
|
-
# Verify before proceeding
|
|
53
|
-
STATUS=$(curl -s -o /dev/null -w "%{http_code}" \
|
|
54
|
-
-H "Authorization: Basic $AUTH" \
|
|
55
|
-
"${LANGFUSE_HOST}/api/public/projects")
|
|
56
|
-
echo "Auth check: $STATUS"
|
|
57
|
-
```
|
|
58
|
-
|
|
59
|
-
If status is not `200`, stop and ask the user to check their credentials and host before continuing.
|
|
60
|
-
|
|
61
|
-
### Annotation target: OBSERVATION not TRACE
|
|
62
|
-
|
|
63
|
-
> **CRITICAL:** In OpenTelemetry-instrumented apps, trace-level `input`/`output` can be null — content lives in a GENERATION observation. Always add `objectType: OBSERVATION` pointing to the GENERATION observation ID to annotation queues. Adding `objectType: TRACE` shows nothing in the UI.
|
|
64
|
-
|
|
65
|
-
### Annotation queues
|
|
66
|
-
|
|
67
|
-
> **CRITICAL:** Queues cannot be updated or deleted after creation. Create score configs first, then the queue with all config IDs. To add new configs later, create a new queue.
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
**Always give the user a direct link immediately after creating a queue:**
|
|
71
|
-
|
|
72
|
-
| Host | URL pattern |
|
|
73
|
-
|------|-------------|
|
|
74
|
-
| EU cloud | `https://cloud.langfuse.com/project/<projectId>/annotation-queues/<queueId>` |
|
|
75
|
-
| US cloud | `https://us.cloud.langfuse.com/project/<projectId>/annotation-queues/<queueId>` |
|
|
76
|
-
| Self-hosted | `<LANGFUSE_HOST>/project/<projectId>/annotation-queues/<queueId>` |
|
|
77
|
-
|
|
78
|
-
Instruction to give: *"Please open code the first ~50 examples. For each trace, write what you observe in the `open_coding` field (describe behaviour, don't diagnose root causes), then set `pass_fail_assessment` to Pass or Fail."*
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
### Prompt fixes
|
|
82
|
-
|
|
83
|
-
When a category warrants a prompt fix, always offer the user two options:
|
|
84
|
-
1. Create it as a versioned prompt in Langfuse (tracked, usable via the prompt API)
|
|
85
|
-
2. Draft the specific text change for them to review and apply
|
|
86
|
-
|
|
87
|
-
### Setup evaluators
|
|
88
|
-
|
|
89
|
-
When a category warrants an evaluator setup, propose the type of evaluator and offer to set it up for user via CLI
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
### Common gotchas
|
|
93
|
-
|
|
94
|
-
| Mistake | Fix |
|
|
95
|
-
|---------|-----|
|
|
96
|
-
| `objectType: TRACE` in queue | Use `objectType: OBSERVATION` with GENERATION obs ID |
|
|
97
|
-
| Creating score config without checking existing | `GET /api/public/score-configs` first; can't delete |
|
|
98
|
-
| Queue created before score configs | Create configs → collect IDs → create queue |
|
|
99
|
-
| `--limit` > 100 on traces list | API hard cap; paginate with `--page` |
|
|
100
|
-
| No rate limiting on queue item creation | `sleep 0.4` between calls to avoid 429 |
|
|
@@ -1,140 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: langfuse-observability
|
|
3
|
-
description: Instrument LLM applications with Langfuse tracing. Use when setting up Langfuse, adding observability to LLM calls, or auditing existing instrumentation.
|
|
4
|
-
---
|
|
5
|
-
|
|
6
|
-
# Langfuse Observability
|
|
7
|
-
|
|
8
|
-
Instrument LLM applications with Langfuse tracing, following best practices and tailored to your use case.
|
|
9
|
-
|
|
10
|
-
## When to Use
|
|
11
|
-
|
|
12
|
-
- Setting up Langfuse in a new project
|
|
13
|
-
- Auditing existing Langfuse instrumentation
|
|
14
|
-
- Adding observability to LLM calls
|
|
15
|
-
|
|
16
|
-
## Workflow
|
|
17
|
-
|
|
18
|
-
### 1. Assess Current State
|
|
19
|
-
|
|
20
|
-
Check the project:
|
|
21
|
-
|
|
22
|
-
- Is Langfuse SDK installed?
|
|
23
|
-
- What LLM frameworks are used? (OpenAI SDK, LangChain, LlamaIndex, Vercel AI SDK, etc.)
|
|
24
|
-
- Is there existing instrumentation?
|
|
25
|
-
|
|
26
|
-
**No integration yet:** Set up Langfuse using a framework integration if available. Integrations capture more context automatically and require less code than manual instrumentation.
|
|
27
|
-
|
|
28
|
-
**Integration exists:** Audit against baseline requirements below.
|
|
29
|
-
|
|
30
|
-
### 2. Verify Baseline Requirements
|
|
31
|
-
|
|
32
|
-
Every trace should have these fundamentals:
|
|
33
|
-
|
|
34
|
-
| Requirement | Check | Why |
|
|
35
|
-
| ------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------ |
|
|
36
|
-
| Model name | Is the LLM model captured? | Enables model comparison and filtering |
|
|
37
|
-
| Token usage | Are input/output tokens tracked? | Enables automatic cost calculation |
|
|
38
|
-
| Good trace names | Are names descriptive? (`chat-response`, not `trace-1`) | Makes traces findable and filterable |
|
|
39
|
-
| Span hierarchy | Are multi-step operations nested properly? | Shows which step is slow or failing |
|
|
40
|
-
| Correct observation types | Are generations marked as generations? | Enables model-specific analytics |
|
|
41
|
-
| Sensitive data masked | Is PII/confidential data excluded or masked? | Prevents data leakage |
|
|
42
|
-
| Trace input/output | Does the trace capture meaningful input/output? Is input explicitly set to show only relevant data (e.g., user message), not all function args? | Makes traces readable in the UI and avoids leaking sensitive args |
|
|
43
|
-
|
|
44
|
-
Framework integrations (OpenAI, LangChain, etc.) handle model name, tokens, and observation types automatically. Prefer integrations over manual instrumentation.
|
|
45
|
-
|
|
46
|
-
Docs: https://langfuse.com/docs/tracing
|
|
47
|
-
|
|
48
|
-
### 3. Explore Traces First
|
|
49
|
-
|
|
50
|
-
Once baseline instrumentation is working, encourage the user to explore their traces in the Langfuse UI before adding more context:
|
|
51
|
-
|
|
52
|
-
"Your traces are now appearing in Langfuse. Take a look at a few of them—see what data is being captured, what's useful, and what's missing. This will help us decide what additional context to add."
|
|
53
|
-
|
|
54
|
-
This helps the user:
|
|
55
|
-
|
|
56
|
-
- Understand what they're already getting
|
|
57
|
-
- Form opinions about what's missing
|
|
58
|
-
- Ask better questions about what they need
|
|
59
|
-
|
|
60
|
-
### 4. Discover Additional Context Needs
|
|
61
|
-
|
|
62
|
-
Determine what additional instrumentation would be valuable. **Infer from code when possible, only ask when unclear.**
|
|
63
|
-
|
|
64
|
-
**Infer from code:**
|
|
65
|
-
|
|
66
|
-
| If you see in code... | Infer | Suggest |
|
|
67
|
-
| ---------------------------------------------------- | ----------------- | ------------------------- |
|
|
68
|
-
| Conversation history, chat endpoints, message arrays | Multi-turn app | `session_id` |
|
|
69
|
-
| User authentication, `user_id` variables | User-aware app | `user_id` on traces |
|
|
70
|
-
| Multiple distinct endpoints/features | Multi-feature app | `feature` tag |
|
|
71
|
-
| Customer/tenant identifiers | Multi-tenant app | `customer_id` or tier tag |
|
|
72
|
-
| Feedback collection, ratings | Has user feedback | Capture as scores |
|
|
73
|
-
|
|
74
|
-
**Only ask when not obvious from code:**
|
|
75
|
-
|
|
76
|
-
- "How do you know when a response is good vs bad?" → Determines scoring approach
|
|
77
|
-
- "What would you want to filter by in a dashboard?" → Surfaces non-obvious tags
|
|
78
|
-
- "Are there different user segments you'd want to compare?" → Customer tiers, plans, etc.
|
|
79
|
-
|
|
80
|
-
**Additions and their value:**
|
|
81
|
-
|
|
82
|
-
| Addition | Why | Docs |
|
|
83
|
-
| ------------------- | ------------------------------------------- | --------------------------------------------------- |
|
|
84
|
-
| `session_id` | Groups conversations together | https://langfuse.com/docs/tracing-features/sessions |
|
|
85
|
-
| `user_id` | Enables user filtering and cost attribution | https://langfuse.com/docs/tracing-features/users |
|
|
86
|
-
| User feedback score | Enables quality filtering and trends | https://langfuse.com/docs/scores/overview |
|
|
87
|
-
| `feature` tag | Per-feature analytics | https://langfuse.com/docs/tracing-features/tags |
|
|
88
|
-
| `customer_tier` tag | Cost/quality breakdown by segment | https://langfuse.com/docs/tracing-features/tags |
|
|
89
|
-
|
|
90
|
-
These are NOT baseline requirements—only add what's relevant based on inference or user input.
|
|
91
|
-
|
|
92
|
-
### 5. Guide to UI
|
|
93
|
-
|
|
94
|
-
After adding context, point users to relevant UI features:
|
|
95
|
-
|
|
96
|
-
- Traces view: See individual requests
|
|
97
|
-
- Sessions view: See grouped conversations (if session_id added)
|
|
98
|
-
- Dashboard: Build filtered views using tags
|
|
99
|
-
- Scores: Filter by quality metrics
|
|
100
|
-
|
|
101
|
-
## Framework Integrations
|
|
102
|
-
|
|
103
|
-
Prefer these over manual instrumentation:
|
|
104
|
-
|
|
105
|
-
| Framework | Integration | Docs |
|
|
106
|
-
| ------------- | ---------------------- | ---------------------------------------------------- |
|
|
107
|
-
| OpenAI SDK | Drop-in replacement | https://langfuse.com/docs/integrations/openai |
|
|
108
|
-
| LangChain | Callback handler | https://langfuse.com/docs/integrations/langchain |
|
|
109
|
-
| LlamaIndex | Callback handler | https://langfuse.com/docs/integrations/llama-index |
|
|
110
|
-
| Vercel AI SDK | OpenTelemetry exporter | https://langfuse.com/docs/integrations/vercel-ai-sdk |
|
|
111
|
-
| LiteLLM | Callback or proxy | https://langfuse.com/docs/integrations/litellm |
|
|
112
|
-
|
|
113
|
-
Full list: https://langfuse.com/docs/integrations
|
|
114
|
-
|
|
115
|
-
## Always Explain Why
|
|
116
|
-
|
|
117
|
-
When suggesting additions, explain the user benefit:
|
|
118
|
-
|
|
119
|
-
```
|
|
120
|
-
"I recommend adding session_id to your traces.
|
|
121
|
-
|
|
122
|
-
Why: This groups messages from the same conversation together.
|
|
123
|
-
You'll be able to see full conversation flows in the Sessions view,
|
|
124
|
-
making it much easier to debug multi-turn interactions.
|
|
125
|
-
|
|
126
|
-
Learn more: https://langfuse.com/docs/tracing-features/sessions"
|
|
127
|
-
```
|
|
128
|
-
|
|
129
|
-
## Common Mistakes
|
|
130
|
-
|
|
131
|
-
| Mistake | Problem | Fix |
|
|
132
|
-
| ---------------------------------------------- | --------------------------------------------------- | --------------------------------------------------------------------------------- |
|
|
133
|
-
| No `flush()` in scripts | Traces never sent | Call `langfuse.flush()` before exit |
|
|
134
|
-
| Flat traces | Can't see which step failed | Use nested spans for distinct steps |
|
|
135
|
-
| Generic trace names | Hard to filter | Use descriptive names: `chat-response`, `doc-summary` |
|
|
136
|
-
| Logging sensitive data | Data leakage risk | Mask PII before tracing |
|
|
137
|
-
| Not explicitly setting input with `@observe` | All function args become trace input (including API keys, configs) | Python: use `langfuse.update_current_span(input=...)`. JS/TS: use `updateActiveObservation({ input: ... })`. Set only the relevant input (e.g., user message) |
|
|
138
|
-
| Manual instrumentation when integration exists | More code, less context | Use framework integration |
|
|
139
|
-
| Langfuse import before env vars loaded | Langfuse initializes with missing/wrong credentials | Import Langfuse AFTER loading environment variables (e.g., after `load_dotenv()`) |
|
|
140
|
-
| Wrong import order with OpenAI | Langfuse can't patch the OpenAI client | Import Langfuse and call its setup BEFORE importing OpenAI client |
|
|
@@ -1,234 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: langfuse-prompt-migration
|
|
3
|
-
description: Migrate hardcoded prompts to Langfuse for version control and deployment-free iteration. Use when user wants to externalize prompts, move prompts to Langfuse, or set up prompt management.
|
|
4
|
-
---
|
|
5
|
-
|
|
6
|
-
# Langfuse Prompt Migration
|
|
7
|
-
|
|
8
|
-
Migrate hardcoded prompts to Langfuse for version control, A/B testing, and deployment-free iteration.
|
|
9
|
-
|
|
10
|
-
## Prerequisites
|
|
11
|
-
|
|
12
|
-
Verify credentials are set before starting. Check existence only — never print the secret key, since the value would land in the agent's context and transcripts:
|
|
13
|
-
|
|
14
|
-
```bash
|
|
15
|
-
[ -n "$LANGFUSE_PUBLIC_KEY" ] && echo "LANGFUSE_PUBLIC_KEY: set" || echo "LANGFUSE_PUBLIC_KEY: missing"
|
|
16
|
-
[ -n "$LANGFUSE_SECRET_KEY" ] && echo "LANGFUSE_SECRET_KEY: set" || echo "LANGFUSE_SECRET_KEY: missing"
|
|
17
|
-
[ -n "$LANGFUSE_HOST" ] && echo "LANGFUSE_HOST: $LANGFUSE_HOST" || echo "LANGFUSE_HOST: missing"
|
|
18
|
-
```
|
|
19
|
-
|
|
20
|
-
If not set, ask the user to configure them in their shell or a `.env` file. Do not ask them to paste keys into chat.
|
|
21
|
-
|
|
22
|
-
## Migration Flow
|
|
23
|
-
|
|
24
|
-
```
|
|
25
|
-
1. Scan codebase for prompts
|
|
26
|
-
2. Analyze templating compatibility
|
|
27
|
-
3. Propose structure (names, subprompts, variables)
|
|
28
|
-
4. User approves
|
|
29
|
-
5. Create prompts in Langfuse
|
|
30
|
-
6. Refactor code to use get_prompt()
|
|
31
|
-
7. Link prompts to traces (if tracing enabled)
|
|
32
|
-
8. Verify application works
|
|
33
|
-
```
|
|
34
|
-
|
|
35
|
-
## Step 1: Find Prompts and Build an Inventory
|
|
36
|
-
|
|
37
|
-
Before writing ANY code, make a complete list of every prompt you found. For each one, note:
|
|
38
|
-
|
|
39
|
-
- Name: descriptive, lowercase, hyphenated (e.g. chat-assistant, email-classifier)
|
|
40
|
-
- Source file: where the prompt text lives
|
|
41
|
-
- Code file to refactor: the Python/JS file that USES the prompt (for asset files like .txt/.yaml/.md, this is the file that reads/loads the asset — NOT the asset file itself)
|
|
42
|
-
- Type: chat (used as a message in a chat API) or text (used as a plain string)
|
|
43
|
-
- Variables: values interpolated into the prompt, converted to {{var}} syntax:
|
|
44
|
-
f-string {var} → {{var}}
|
|
45
|
-
.format(var=...) → {{var}}
|
|
46
|
-
${var} → {{var}}
|
|
47
|
-
String concatenation + var + → {{var}}
|
|
48
|
-
YAML {var} → {{var}}
|
|
49
|
-
- Prompt content: the actual text to upload, with variables converted to {{var}} syntax
|
|
50
|
-
|
|
51
|
-
Search for these patterns:
|
|
52
|
-
|
|
53
|
-
| Framework | Look for |
|
|
54
|
-
|-----------|----------|
|
|
55
|
-
| OpenAI | `messages=[{"role": "system", "content": "..."}]` |
|
|
56
|
-
| Anthropic | `system="..."` |
|
|
57
|
-
| LangChain | `ChatPromptTemplate`, `SystemMessage` |
|
|
58
|
-
| Vercel AI | `system: "..."`, `prompt: "..."` |
|
|
59
|
-
| Raw | Multi-line strings near LLM calls |
|
|
60
|
-
|
|
61
|
-
## Step 2: Check Templating Compatibility
|
|
62
|
-
|
|
63
|
-
**CRITICAL:** Langfuse only supports simple `{{variable}}` substitution. No conditionals, loops, or filters.
|
|
64
|
-
|
|
65
|
-
| Template Feature | Langfuse Native | Action |
|
|
66
|
-
|------------------|-----------------|--------|
|
|
67
|
-
| `{{variable}}` | ✅ | Direct migration |
|
|
68
|
-
| `{var}` / `${var}` | ⚠️ | Convert to `{{var}}` |
|
|
69
|
-
| `{% if %}` / `{% for %}` | ❌ | Move logic to code |
|
|
70
|
-
| `{{ var \| filter }}` | ❌ | Apply filter in code |
|
|
71
|
-
|
|
72
|
-
**CRITICAL — Variable syntax:** Langfuse uses DOUBLE curly braces for variables: `{{var}}`. When uploading prompt content, you MUST convert every single-brace `{var}` from the original code to double-brace `{{var}}`. Never upload `{var}` — it must be `{{var}}`.
|
|
73
|
-
|
|
74
|
-
### Decision Tree
|
|
75
|
-
|
|
76
|
-
```
|
|
77
|
-
Contains {% if %}, {% for %}, or filters?
|
|
78
|
-
├─ No → Direct migration
|
|
79
|
-
└─ Yes → Choose:
|
|
80
|
-
├─ Option A (RECOMMENDED): Move logic to code, pass pre-computed values
|
|
81
|
-
└─ Option B: Store raw template, compile client-side with Jinja2
|
|
82
|
-
└─ ⚠️ Loses: Playground preview, UI experiments
|
|
83
|
-
```
|
|
84
|
-
|
|
85
|
-
### Simplifying Complex Templates
|
|
86
|
-
|
|
87
|
-
**Conditionals** → Pre-compute in code:
|
|
88
|
-
```python
|
|
89
|
-
# Instead of {% if user.is_premium %}...{% endif %} in prompt
|
|
90
|
-
# Use {{tier_message}} and compute value in code before compile()
|
|
91
|
-
```
|
|
92
|
-
|
|
93
|
-
**Loops** → Pre-format in code:
|
|
94
|
-
```python
|
|
95
|
-
# Instead of {% for tool in tools %}...{% endfor %} in prompt
|
|
96
|
-
# Use {{tools_list}} and format the list in code before compile()
|
|
97
|
-
```
|
|
98
|
-
|
|
99
|
-
For external templating details, fetch: https://langfuse.com/faq/all/using-external-templating-libraries
|
|
100
|
-
|
|
101
|
-
## Step 3: Propose Structure
|
|
102
|
-
|
|
103
|
-
### Naming Conventions
|
|
104
|
-
|
|
105
|
-
| Rule | Example | Bad |
|
|
106
|
-
|------|---------|-----|
|
|
107
|
-
| Lowercase, hyphenated | `chat-assistant` | `ChatAssistant_v2` |
|
|
108
|
-
| Feature-based | `document-summarizer` | `prompt1` |
|
|
109
|
-
| Hierarchical for related | `support/triage` | `supportTriage` |
|
|
110
|
-
| Prefix subprompts with `_` | `_base-personality` | `shared-personality` |
|
|
111
|
-
|
|
112
|
-
### Identify Subprompts
|
|
113
|
-
|
|
114
|
-
Extract when:
|
|
115
|
-
- Same text in 2+ prompts
|
|
116
|
-
- Represents distinct component (personality, safety rules, format)
|
|
117
|
-
- Would need to change together
|
|
118
|
-
|
|
119
|
-
### Variable Extraction
|
|
120
|
-
|
|
121
|
-
| Make Variable | Keep Hardcoded |
|
|
122
|
-
|---------------|----------------|
|
|
123
|
-
| User-specific (`{{user_name}}`) | Output format instructions |
|
|
124
|
-
| Dynamic content (`{{context}}`) | Safety guardrails |
|
|
125
|
-
| Per-request (`{{query}}`) | Persona/personality |
|
|
126
|
-
| Environment-specific (`{{company_name}}`) | Static examples |
|
|
127
|
-
|
|
128
|
-
## Step 4: Present Plan to User
|
|
129
|
-
|
|
130
|
-
Format:
|
|
131
|
-
```
|
|
132
|
-
Found N prompts across M files:
|
|
133
|
-
|
|
134
|
-
src/chat.py:
|
|
135
|
-
- System prompt (47 lines) → 'chat-assistant'
|
|
136
|
-
|
|
137
|
-
src/support/triage.py:
|
|
138
|
-
- Triage prompt (34 lines) → 'support/triage'
|
|
139
|
-
⚠️ Contains {% if %} - will simplify
|
|
140
|
-
|
|
141
|
-
Subprompts to extract:
|
|
142
|
-
- '_base-personality' - used by: chat-assistant, support/triage
|
|
143
|
-
|
|
144
|
-
Variables to add:
|
|
145
|
-
- {{user_name}} - hardcoded in 2 prompts
|
|
146
|
-
|
|
147
|
-
Proceed?
|
|
148
|
-
```
|
|
149
|
-
|
|
150
|
-
## Step 5: Create Prompts in Langfuse
|
|
151
|
-
|
|
152
|
-
Use `langfuse.create_prompt()` with:
|
|
153
|
-
- `name`: Your chosen name
|
|
154
|
-
- `prompt`: Template text (or message array for chat type)
|
|
155
|
-
- `type`: `"text"` or `"chat"`
|
|
156
|
-
- `labels`: `["production"]` (they're already live)
|
|
157
|
-
- `config`: Optional model settings
|
|
158
|
-
|
|
159
|
-
**Labeling strategy:**
|
|
160
|
-
- `production` → All migrated prompts
|
|
161
|
-
- `staging` → Add later for testing
|
|
162
|
-
- `latest` → Auto-applied by Langfuse
|
|
163
|
-
|
|
164
|
-
For full API: fetch https://langfuse.com/docs/prompts/get-started
|
|
165
|
-
|
|
166
|
-
## Step 6: Refactor Code
|
|
167
|
-
|
|
168
|
-
Replace hardcoded prompts with:
|
|
169
|
-
|
|
170
|
-
```python
|
|
171
|
-
prompt = langfuse.get_prompt("name", label="production")
|
|
172
|
-
messages = prompt.compile(var1=value1, var2=value2)
|
|
173
|
-
```
|
|
174
|
-
|
|
175
|
-
**Key points:**
|
|
176
|
-
- Always use `label="production"` (not `latest`) for stability
|
|
177
|
-
- Call `.compile()` to substitute variables
|
|
178
|
-
- For chat prompts, result is message array ready for API
|
|
179
|
-
|
|
180
|
-
For SDK examples (Python/JS/TS): fetch https://langfuse.com/docs/prompts/get-started
|
|
181
|
-
|
|
182
|
-
## Step 7: Link Prompts to Traces
|
|
183
|
-
|
|
184
|
-
If codebase uses Langfuse tracing, link prompts so you can see which version produced each response.
|
|
185
|
-
|
|
186
|
-
### Detect Existing Tracing
|
|
187
|
-
|
|
188
|
-
Look for:
|
|
189
|
-
- `@observe()` decorators
|
|
190
|
-
- `langfuse.trace()` calls
|
|
191
|
-
- `from langfuse.openai import openai` (instrumented client)
|
|
192
|
-
|
|
193
|
-
### Link Methods
|
|
194
|
-
|
|
195
|
-
| Setup | How to Link |
|
|
196
|
-
|-------|-------------|
|
|
197
|
-
| `@observe()` decorator | `langfuse_context.update_current_observation(prompt=prompt)` |
|
|
198
|
-
| Manual tracing | `trace.generation(prompt=prompt, ...)` |
|
|
199
|
-
| OpenAI integration | `openai.chat.completions.create(..., langfuse_prompt=prompt)` |
|
|
200
|
-
|
|
201
|
-
### Verify in UI
|
|
202
|
-
|
|
203
|
-
1. Go to **Traces** → select a trace
|
|
204
|
-
2. Click on **Generation**
|
|
205
|
-
3. Check **Prompt** field shows name and version
|
|
206
|
-
|
|
207
|
-
For tracing details: fetch https://langfuse.com/docs/prompts/get-started#link-with-langfuse-tracing
|
|
208
|
-
|
|
209
|
-
## Step 8: Verify Migration
|
|
210
|
-
|
|
211
|
-
### Checklist
|
|
212
|
-
|
|
213
|
-
- [ ] All prompts created with `production` label
|
|
214
|
-
- [ ] Code fetches with `label="production"`
|
|
215
|
-
- [ ] Variables compile without errors
|
|
216
|
-
- [ ] Subprompts resolve correctly
|
|
217
|
-
- [ ] Application behavior unchanged
|
|
218
|
-
- [ ] Generations show linked prompt in UI (if tracing)
|
|
219
|
-
|
|
220
|
-
### Common Issues
|
|
221
|
-
|
|
222
|
-
| Issue | Solution |
|
|
223
|
-
|-------|----------|
|
|
224
|
-
| `PromptNotFoundError` | Check name spelling |
|
|
225
|
-
| Variables not replaced | Use `{{var}}` not `{var}`, call `.compile()` |
|
|
226
|
-
| Subprompt not resolved | Must exist with same label |
|
|
227
|
-
| Old prompt cached | Restart app |
|
|
228
|
-
|
|
229
|
-
## Out of Scope
|
|
230
|
-
|
|
231
|
-
- Prompt engineering (writing better prompts)
|
|
232
|
-
- Evaluation setup
|
|
233
|
-
- A/B testing workflow
|
|
234
|
-
- Non-LLM string templates
|