Compare commits

...
259 Commits
Author SHA1 Message Date
Marc Klingen 33d3ab80cb chore: release v3.34.0 2025-02-27 22:54:18 +01:00
Marc KlingenandGitHub 6b9773caec feat(models): add openai gpt-4.5-preview (#5772) 2025-02-27 21:47:24 +00:00
Steffen SchmitzandGitHub c90b477d40 fix: disable tracing for resetPassword route (#5763) 2025-02-27 15:36:36 +00:00
Max DeichmannGitHubellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
0f448ccdde fix: always return 422 for signup error handler (#5761)
* fix: always return 422 for signup error handler

* Update web/src/features/auth-credentials/server/signupApiHandler.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* Update web/src/features/auth-credentials/server/signupApiHandler.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-02-27 15:33:41 +00:00
marliessophieandGitHub 74f93aad79 chore: move dashboard button to the right, unify eval headers (#5762)
chore: move dashboard button to the right
2025-02-27 15:15:40 +00:00
Max DeichmannandGitHub 9650e87f64 fix: standardize way to get sso blocked domains (#5760)
fix: standardise way to get sso blocked domains
2025-02-27 15:15:10 +00:00
Steffen SchmitzandGitHub c5fc30a9d0 feat: map otel environment config to langfuse environment (#5757) 2025-02-27 14:46:43 +00:00
steffen911 4a26f47971 chore: release v3.33.1 2025-02-27 15:34:24 +01:00
Steffen SchmitzGitHubellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
e3a9e61d07 perf: filter relevant observation for data set run item stats (#5752)
* perf: filter relevant observation for data set run item stats

* Update web/src/features/datasets/server/service.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-02-27 14:08:07 +00:00
Hassieb Pakzad a12c2a3a97 fix(model-prices): bedrock claude 3-7 version 2025-02-27 13:14:05 +01:00
Hassieb PakzadandGitHub 80681e08af fix(model-prices): bedrock claude sonnet 3-7 version (#5753) 2025-02-27 13:10:08 +01:00
steffen911 4e97494390 chore: release v3.33.0 2025-02-27 11:58:10 +01:00
Steffen SchmitzandGitHub 346e5fe7b6 feat: map environment to score within eval service (#5749)
* feat: map environment to score within eval service

* chore: adjust tests

* chore: drop unused imports
2025-02-27 10:50:36 +00:00
Steffen SchmitzandGitHub 16482f588a fix: create traces via otel for empty parent span buffer (#5748)
* fix: create traces via otel for empty parent span buffer

* chore: test range for session duration
2025-02-27 10:10:51 +00:00
Marc KlingenandGitHub f047e21e13 chore: improved domain handling and early return in signupApiHandler (#5744) 2025-02-26 21:56:20 +00:00
marliessophieandGitHub 534e832c13 fix(ui): overlapping variables for chat prompt (#5740) 2025-02-26 17:47:03 +00:00
marliessophieandGitHub 5dbfec24f0 fix(ui): experiment from the prompt screen -> window does not fit screen (#5738) 2025-02-26 17:21:05 +00:00
Hassieb PakzadandGitHub 700705be84 chore(llm-keys): update bedrock form description (#5737) 2025-02-26 17:58:49 +01:00
Hassieb Pakzad 611c31ce54 chore: release v3.32.1 2025-02-26 17:06:23 +01:00
Hassieb PakzadandGitHub bdb5ddadd9 fix(ingestion): environment to immutable keys (#5736) 2025-02-26 16:01:26 +00:00
Hassieb PakzadandGitHub 0fd1f065bd fix(api): add environment to ingestion spec (#5735) 2025-02-26 16:02:49 +01:00
Marc KlingenandGitHub 8aa063303a chore(ui): move "configure tracing" to the right in dashboard header (#5731) 2025-02-26 13:59:21 +00:00
Marc KlingenandGitHub d0ff8a87fe chore(ui): minor improvements to onboarding pages (#5730)
chore: minor improvements to onboarding pages
2025-02-26 13:56:39 +00:00
marliessophieandGitHub 0e61ffd621 style(prompts): always show edit label button for prompt versions (#5729) 2025-02-26 13:41:01 +00:00
steffen911 9f20926bc4 chore: release v3.32.0 2025-02-26 14:36:38 +01:00
Steffen SchmitzandGitHub 81a232e4a4 fix: fallback to "default" for missing environment (#5728) 2025-02-26 13:34:33 +00:00
Marc KlingenandGitHub c7e7d62f47 feat(ui): add onboarding screens for core features (#5706)
* feat: add in-ui-onboarding for tracing

* feat(ui): add onboarding screens for core features

* add annotation queues

* move videos to static, add eval onboarding

* push

* push

* push

* push

* push
2025-02-26 13:13:43 +00:00
steffen911 2aa8971dff chore: release v3.31.0 2025-02-26 13:53:58 +01:00
Steffen SchmitzandGitHub 85f4cb0c13 fix: show retention settings for self-hosters (#5727) 2025-02-26 12:34:14 +00:00
Hassieb PakzadandGitHub 4bbba9d983 feat(api): add environment property to traces, scores, obs (#5724) 2025-02-26 13:32:03 +01:00
Steffen SchmitzandGitHub 0b7dd5a1a7 feat: process environment in ingestion pipeline (#5671)
* feat: process environment in ingestion pipeline

* chore: remove unnecessary status

* chore: typing

* chore: more typing

* chore: score env prop

* chore: adjust apis to pass tests

* chore: adjust ingestion service test

* chore: restrict allowed prefix
2025-02-26 12:18:38 +00:00
Steffen SchmitzandGitHub b5cad2693f fix: exclude clickhouse default date from session duration calc (#5726) 2025-02-26 09:51:52 +00:00
Max Deichmann 58d85d66b3 chore: release v3.30.0 2025-02-26 10:30:59 +01:00
Max DeichmannandGitHub 55a5a896f1 chore: track distribution of ingested event body size (#5723)
push
2025-02-26 09:05:08 +00:00
Steffen SchmitzandGitHub 5437beec48 Revert "fix: return nulls for left-joins for correct session durations (#5697)" (#5717)
This reverts commit ce967bac12.
2025-02-25 18:14:26 +01:00
Steffen SchmitzandGitHub 418e33a333 fix: only delete media items with no remaining references (#5713)
* fix: only delete media items with no remaining references

* chore: expand filter condition
2025-02-25 15:18:02 +00:00
Hassieb PakzadandGitHub e9bbd4488f feat(playground+evals): add Google AI Studio support (#5711) 2025-02-25 14:48:22 +01:00
Steffen SchmitzandGitHub 668ca24d5e fix: support gzip encoding on otel endpoint (#5710)
* fix: support gzip encoding on otel endpoint

* chore: check for includes
2025-02-25 10:41:43 +00:00
Hassieb PakzadandGitHub 7c746c7cfc feat(models): add claude-3-7-sonnet-20250219 (#5709) 2025-02-25 10:07:41 +00:00
Hassieb Pakzad de0eb76153 chore: release v3.29.1 2025-02-24 20:53:46 +01:00
Hassieb PakzadandGitHub 85088574b2 fix(public-api): list observations with name filter (#5700) 2025-02-24 20:52:58 +01:00
Steffen SchmitzandGitHub ce967bac12 fix: return nulls for left-joins for correct session durations (#5697)
* fix: return nulls for left-joins for correct session durations

* chore: comment updates

* chore: adjust trace_count
2025-02-24 15:57:47 +00:00
Steffen SchmitzandGitHub b8d0a4bbe8 chore: remove prisma references to traces, observations, scores (#5672)
* chore: remove prisma references to traces, observations, scores

* chore: separate enum and type name

* chore: type overwrites

* chore: chore

* chore: drop views

* chore: reduce diff

* chore: diff

* chore: types gen

* chore: lint

* chore: adjust tests

* chore: remove unused objects in test utils

* chore: adjust tests

* chore: score type parsing

* chore: fix otelmapping

* chore: make observation level internal
2025-02-24 15:43:25 +00:00
marliessophieandGitHub 1e7aeb8fc5 chore(llmCompletion): support system/developer messages for o3 (#5661) 2025-02-24 09:25:33 +00:00
marliessophieandGitHub 9d5cc39cd4 style(ui): improvements to prompt details screen (#5678)
* fix: header

* fix: search always show current version

* chore: adjust code block

* chore: re-add copy in code editor if no title

* chore: do not match current version always

* adjust margins

* chore: remove breadcrumb

* fix: typo

* fix: final margin

* style: eval template

* small design nits
2025-02-22 09:16:44 +00:00
Marc KlingenandGitHub 5c5dfcbac6 chore(ui): improve consistency of prompt and eval template forms (#5679)
* chore(ui): consistency in prompt form labels

* eval prompt form
2025-02-21 18:10:12 +00:00
marliessophieandGitHub 628d180051 feat(ui): new prompt detail screen; adjust design of IO and message view components (#5537)
* style(ui): adjust design of IO and message view components

* chore: adjust final style and fix imports

* style

* nit: show "null" if no output in dataset compare view

* style: add header and tertiary colors

* chore: add Header levels

* chore: add Timeline component

* feat: make JSONView optionally scrollable

* chore: refactor TagManager styling

* style: button variants for header

* chore: ensure chatml message overflow behaves within chat message

* feat: new prompt screen outline

* chore: refactor `extractVariables` to return count

* chore: ensure robust mobile behaviour

* style: small component adjustments

* chore: refactor style of `Comment` button

* feat: add search functionality to prompt nodes

* style: restyle tags

* revert: variable extraction count

* style: prompts page overflow

* chore: control label behaviour

* labels: show buttons on hover

* fix: formatting of titles

* eslint

* push

* push

* fix: overflows

* push

* diabled view
2025-02-21 13:46:59 +00:00
Max Deichmann 57708f0219 chore: release v3.29.0 2025-02-21 13:42:45 +01:00
Max DeichmannandGitHub 5d30aefcb3 fix: do not allow to deactivate eval configs which are only on existing objects (#5675)
* fix: do not allow to deactivate eval configs which rano on historic traces only

* fix: do not allow to deactivate eval configs which rano on historic traces only

* fix: do not allow to deactivate eval configs which rano on historic traces only

* fix: do not allow to deactivate eval configs which rano on historic traces only

* fix: do not allow to deactivate eval configs which rano on historic traces only
2025-02-21 12:40:18 +00:00
Max DeichmannandGitHub dd14e11535 perf: reduce eval create queue concurrency (#5665) 2025-02-20 19:24:38 +00:00
Max DeichmannandGitHub 5f87980013 fix: do not return all executions for eval config list trpc (#5663)
* fix: do not return all executions for eval config list trpc

* fix: do not return all executions for eval config list trpc

* fix: do not return all executions for eval config list trpc

* fix: do not return all executions for eval config list trpc
2025-02-20 17:56:38 +00:00
Max DeichmannandGitHub 2edc2487ae perf: limit concurrency for eval job creations (#5660)
* push

* push
2025-02-20 16:05:41 +00:00
Steffen SchmitzandGitHub 18508187f6 chore: add environment column to trace_sessions (#5656)
* chore: add environment column to trace_sessions

* chore: update test
2025-02-20 15:06:39 +00:00
Max DeichmannGitHubellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
eb5ee957e6 feat: apply evals on history of datasets + traces (#5488)
* push

* push

* push

* push

* fix

* fix

* add tests

* add tests

* add tests

* add tests

* add tests

* add tests

* fic

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* push

* push

* Update web/src/ee/features/evals/components/evaluator-form.tsx

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* push

* fix: fix dompurify

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-02-20 13:59:14 +00:00
Steffen SchmitzandGitHub 582f150b72 chore: add environment columns in clickhouse (#5649)
* chore: add environment columns in clickhouse

* chore: replace logger.warning with logger.warn
2025-02-20 13:05:35 +00:00
Steffen SchmitzandGitHub 7ce4e24cab chore: replace logger.warning with logger.warn (#5650) 2025-02-20 12:12:31 +00:00
marliessophieandGitHub b2d3080790 chore(prompts): support developer message (#5639)
* chore(prompts): support developer message

* chore: fix eslint config

* push
2025-02-20 09:40:32 +00:00
steffen911 3590608d30 chore: increase event log deletion timeout to 5min 2025-02-19 15:56:11 +01:00
Steffen SchmitzandGitHub 78e6c882ba chore: reduce attempts and increase delay on trace delete errors (#5637) 2025-02-19 14:24:28 +00:00
Steffen SchmitzandGitHub d5ea44b33c perf: only validate response schema on dev servers (#5630) 2025-02-19 13:11:42 +00:00
Steffen SchmitzandGitHub 8b601eed20 fix: re-enable trace deletion and remove trace S3 files (#5594)
* fix: re-enable trace deletion and remove trace S3 files

* chore: lint

* chore: lint

* chore: increase query timeout

* chore: reduce query result to only return event log

* chore: keep condition pattern

* chore: revert entitlement changes

* chore: move permission check

* chore: explain semi join and shift entitlement comment
2025-02-19 12:45:37 +00:00
Steffen SchmitzandGitHub caebc92051 chore: bump static page generation timeout (#5621) 2025-02-18 14:44:33 +00:00
Steffen SchmitzandGitHub e41f1c5e5b build: notify slack on failed deployment (#5617) 2025-02-18 14:40:29 +01:00
Steffen SchmitzandGitHub c419fd69fa chore: remove superfluous container_name overwrites (#5615) 2025-02-18 13:03:45 +00:00
Steffen SchmitzandGitHub 485dc94444 feat: map langfuse data model to further otel attributes (#5614)
* feat: map langfuse data model to further otel attributes

* chore: expand tests
2025-02-18 11:29:17 +00:00
Steffen SchmitzandGitHub c233c7fa8d feat: parse mlflow attributes on otel spans (#5609)
* feat: parse mlflow attributes on otel spans

* chore: correct failing test
2025-02-18 09:07:12 +00:00
marliessophieandGitHub 0263b40987 perf(sessions): display only first 10 users; show rest in paginated popover (#5599)
* perf(sessions): show only up to 10 initial users and the rest in popover

* nit: fix header on traces page
2025-02-17 19:01:01 +00:00
Marc KlingenandGitHub 44621d0d1f chore: remove the unnecessary file (#5598)
chore: remove unnecessary file
2025-02-17 18:34:01 +00:00
marliessophieandGitHub 5bd891ddc7 style(traces): style traces delete button in more menu in table (#5596) 2025-02-17 14:59:12 +00:00
marliessophieandGitHub 8e02f86fa7 chore(page-header): add new tabsComponent (#5593)
* chore(page-header): add tabs component

* style: replace tabs component on datasets pages

* style: replace tabs component on evals pages

* nit: fix dataset item page formatting

* style: replace tabs component on prompts pages

* chore: adjust col behaviour on header

* eslint
2025-02-17 13:34:57 +00:00
Max DeichmannandGitHub d7582c66ee security: upgrade jsonpath plus (#5591) 2025-02-17 12:41:12 +00:00
marliessophieandGitHub 75bef08f0b style(page-header): optimise for mobile view (#5590)
* chore: fix demo banner

* fix(page-header): info icon relative positioning

* fix: header title wrap behaviour

* fix(page-header): have info icon follow title

* style: move dataset level buttons to more menu

* push

* push
2025-02-17 12:36:33 +00:00
Max Deichmann 5f7b50cea8 chore: release v3.28.3 2025-02-17 09:56:07 +01:00
Steffen SchmitzandGitHub a9757d144f chore: fallback to LLM http status for /api/chatCompletion (#5554) 2025-02-17 08:42:49 +00:00
Steffen SchmitzandGitHub 12fb26388c fix: accept further content type formats on otel endpoint (#5584) 2025-02-17 08:41:14 +00:00
Max Deichmann 95d9aef705 chore: release v3.28.2 2025-02-15 13:29:06 +01:00
Max Deichmann 15fea028c2 chore: release v3.28.1 2025-02-15 01:04:28 +01:00
Max DeichmannandGitHub ac6e94ee3c security: upgrade release-it (#5558)
* security: upgrade release-it

* security: upgrade release-it

* security: upgrade release-it
2025-02-14 18:59:53 +00:00
Max DeichmannandGitHub e7332bd1e5 security: upgrade dompurify (#5557) 2025-02-14 19:39:59 +01:00
Max Deichmann fe8b2ba7ae chore: release v3.28.0 2025-02-14 19:20:25 +01:00
marliessophieandGitHub 652e96ee9d fix(header): breakpoint header behaviour (#5555)
fix(header): fix breakpoint header behaviour
2025-02-14 17:49:13 +00:00
Steffen SchmitzandGitHub 40ce493b06 fix: change numeric type parsing for sessions table filters (#5553) 2025-02-14 16:21:43 +00:00
Max DeichmannGitHubellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
aa7ba1a9c5 chore: add dashboard time filter test case (#5526)
* add tests

* Update web/src/__tests__/async/repositories/dashboard-repository.servertest.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-02-14 15:22:15 +00:00
Jannik MaierhöferandGitHub 869b027110 docs: fix gif on Readme (#5502) 2025-02-14 15:18:05 +00:00
Hassieb PakzadandGitHub 1243d9022e feat(trace-ui): add graph view (#5511)
* feat(trace-ui): add graph view

* push

* rename

* fix build error
2025-02-14 15:08:15 +00:00
marliessophieandGitHub d988c07d46 style(header): adjust minor paddings and relative scroll behaviour (#5551)
* style(header): relative positioning on scroll page

* style: add padding to container layout

* chore: rm top margin
2025-02-14 14:27:46 +00:00
0a53682ed6 chore: Update README.ja.md (#5545)
Update README.ja.md

modification in Japanese and put Japanese support info.

Co-authored-by: Marc Klingen <git@marcklingen.com>
2025-02-14 14:24:15 +00:00
Steffen SchmitzandGitHub ac517c1849 chore: enhance ingestion api documentation (#5550) 2025-02-14 14:17:45 +00:00
Iaroslav VolkovandGitHub 2778be5abb feat: add TLS env variable support for Redis (#5393) 2025-02-14 13:28:15 +01:00
56e4b92fd7 feat(ui): add new langfuse header (#5451)
* chore: extract PageContainer component

* chore: add ItemBadge component

* style: redesign publish trace switch

* style: redesign detail page nav

* chore: extract copybutton

* chore: wrap all pages in `PageContainer`

* chore: add settings-container; style nits

* chore: simplify langfuse header

* chore: replace session icon in itembadge

* chore: mv lg:container to settings-container level

* chore: refactor component logic in ProjectOverview

* style: make project button primary

* style: adjust light mode sidebar colors

* fix: rm unneccessary class

* fix: eslint

* chore: update readme

* chore: adjust page header to <h2/>

* chore: adjust colors

* style: button color

* style: refactor public/private highlight

* push

* chore: rename components

* style: add breadcrumb to pages

* style: add sidebar border

* style: adjust sharing logic

* push

* chore: eslint

* fix: header alignment

* push

* push

* eslint

---------

Co-authored-by: Max Deichmann <m.deichmann@tum.de>
2025-02-14 10:39:42 +00:00
Steffen SchmitzandGitHub 613126bbfb chore: add clickhouse tags to queries (#5535) (#5538)
* chore: add clickhouse tags to queries (#5535)

* chore: add clickhouse tags to queries

* chore: linting

* chore: add dashboard tags

(cherry picked from commit 95d67d65d7)

* chore: move tags to json

* chore: move to json format

* chore: fix build

* chore: remove redundant fallback
2025-02-14 10:09:08 +00:00
Max Deichmann d8738e7594 chore: release v3.27.2 2025-02-13 23:01:58 +01:00
Max DeichmannandGitHub b4f7aded4f chore: increase static page generation timeout nextjs (#5539)
* add tests

* push
2025-02-13 21:59:17 +00:00
Max Deichmann dd1ac129d1 chore: release v3.27.1 2025-02-13 20:19:28 +01:00
steffen911 7fd8c03aca Revert "chore: add clickhouse tags to queries (#5535)"
This reverts commit 95d67d65d7.
2025-02-13 19:03:13 +01:00
Steffen SchmitzandGitHub 95d67d65d7 chore: add clickhouse tags to queries (#5535)
* chore: add clickhouse tags to queries

* chore: linting

* chore: add dashboard tags
2025-02-13 15:59:54 +00:00
Hassieb PakzadandGitHub 8b7b3570e8 fix(prompts-api): handle unique constraint errors (#5534) 2025-02-13 15:34:34 +00:00
Hassieb PakzadandGitHub 7fa738693a fix(model-prices): move gemini prices to Google AI values (#5533) 2025-02-13 14:46:23 +00:00
Hassieb PakzadandGitHub b554068713 fix(batch-exports): handle retries on stalled jobs for killed workers (#5532) 2025-02-13 14:42:50 +00:00
Marc Klingen 3396cc86a2 chore: release v3.27.0 2025-02-13 15:22:28 +01:00
Marc KlingenandGitHub e41ca6baa1 fix(env): standardize AZURE_AD auth environment variables and add all to .env.prod.example (#5530)
* fix(env): standardize AZURE_AD auth environment variables and add all to .env.prod.example

* push
2025-02-13 14:05:15 +00:00
marliessophieandGitHub 2001630e4d perf(tables): truncate large I/O content preview in tables (#5531)
* perf(tables): truncate large I/O content preview in tables

* push
2025-02-13 14:01:58 +00:00
Steffen SchmitzandGitHub e9da31f26a chore: delay project delete queue to allow for remaining events to be processed (#5528) 2025-02-13 12:58:59 +00:00
Steffen SchmitzandGitHub 6dd1a12bfc chore: reduce authed request logging to debug (#5527) 2025-02-13 12:24:09 +00:00
marliessophieandGitHub 922f846ce8 chore: re-enable sentry; reverts #5505 (#5524)
* chore: re-enable sentry

* chore: revert back to original version

* chore: revert removing client config
2025-02-13 09:21:13 +00:00
marliessophieandGitHub 7f16fc353d fix(datasets): broken link in compare view (#5521) 2025-02-13 09:01:39 +00:00
marliessophieandGitHub becae4c720 chore: revert changes to session storage hook from #5314 (#5513) 2025-02-12 21:45:45 +00:00
Hassieb PakzadandGitHub fede3480d1 perf(exports): increase max row limit to 1M (#5512) 2025-02-12 22:01:14 +01:00
Steffen SchmitzandGitHub 9bf5b829a7 fix: delete event files from s3 after retention period end (#5509)
* fix: delete event files from s3 after retention period end

* chore: lint
2025-02-12 17:03:36 +00:00
marliessophieandGitHub 92d5591171 perf(tables): disable link prefetching in viewport, only prefetch on link hover (#5508) 2025-02-12 16:59:29 +00:00
40f7849444 fix: disable sentry (#5505)
* fix: disable sentry

* chore: remove usages of sentry

* dep: remove sentry dependency

* Revert "dep: remove sentry dependency"

This reverts commit 63fb207fce4fafc17993cc6be9905db3b4e5713c.

* dep: remove sentry dependency

* chore: lint

---------

Co-authored-by: Marlies Mayerhofer <74332854+marliessophie@users.noreply.github.com>
2025-02-12 16:44:00 +00:00
Steffen SchmitzandGitHub 9f21b1044f chore: upgrade dd-trace-js (#5506) 2025-02-12 16:36:55 +01:00
Steffen SchmitzandGitHub 030e759c0d fix: delete media and event files from S3 on project delete (#5504)
* fix: delete media and event files from S3 on project delete

* chore: update comment

* chore: test cleanup
2025-02-12 14:07:24 +00:00
Steffen SchmitzandGitHub 90a0b67ea2 chore: propagate otel trace context to clickhouse spans (#5501) 2025-02-12 12:45:13 +00:00
Steffen SchmitzandGitHub 731958ca11 chore: add additional attributes to ingestion spans (#5499) 2025-02-12 10:25:12 +00:00
marliessophieandGitHub 9d37cc4d34 chore(csv-upload): reduce min chunk size (#5496)
* chore(csv-upload): reduce min chunk size

* push
2025-02-12 09:15:09 +00:00
marliessophieandGitHub 55e0ff4169 chore: hide trace deletion button on cloud until enabled again (#5495)
* chore: hide trace deletion button on cloud until enabled again

* docs: add reasoning
2025-02-12 08:39:35 +00:00
Steffen SchmitzandGitHub 304c4fcb7e chore: link to docs for batch export config errors (#5484) 2025-02-11 16:14:29 +00:00
Steffen SchmitzandGitHub 8ede19d263 feat: log all created s3 event files in clickhouse (#5476)
* feat: log all created s3 event files in clickhouse

* chore: remove empty module

* chore: bucket path for clickhouse events

* chore: add test

* chore: lint
2025-02-11 15:38:04 +00:00
Steffen SchmitzandGitHub eda925c686 fix: map token filters for ui table to fitting clickhouse types (#5482) 2025-02-11 13:59:19 +00:00
Jannik MaierhöferandGitHub 57e8de852e docs: add translations of README for Chinese, Japanese and Korean (#5479) 2025-02-11 13:34:23 +00:00
ClemoandGitHub 7d77c36817 Update LICENSE
add clarification
2025-02-11 13:06:38 +01:00
c821d1b2fe docs: new readme (#5446)
* docs: readme rework

* banner update

* docs: minor edits

* add star us cta

* add feature overview image

* delete image and careers

* push

---------

Co-authored-by: Clemo <121163007+clemra@users.noreply.github.com>
Co-authored-by: Marc Klingen <git@marcklingen.com>
2025-02-11 12:04:24 +00:00
Steffen SchmitzandGitHub 0ea80605b1 chore: drop postgres events table (#5472)
* chore: drop postgres events table

* chore: celanup

* chore: drop events table
2025-02-11 11:45:43 +00:00
Steffen SchmitzandGitHub 05e16e7d00 chore: remove event_log table (#5471)
* chore: remove event_log table

* chore: add fileKey for score events
2025-02-11 11:28:41 +00:00
Max DeichmannandGitHub 67876d4e4f fix: add clickhouse final for traces grouped by name dashboard (#5474)
fix
2025-02-11 10:58:51 +00:00
marliessophieandGitHub 179751db91 style(dashboard): round to two decimals on model latencies chart (#5473) 2025-02-11 10:35:08 +00:00
marliessophieandGitHub e2164c2f00 fix(dataset-upsert): filter on dataset evals triggered in trace-upsert queue (#5353) 2025-02-11 09:38:28 +00:00
marliessophieandGitHub 778dc24324 chore(datasets): reduce max payload size in csv upload (#5466) 2025-02-11 09:02:39 +00:00
Steffen SchmitzandGitHub d48da06274 chore: instrument api authentication (#5465) 2025-02-11 08:54:49 +00:00
Steffen SchmitzandGitHub 185cb10d7c feat(otel): map traceloop.entity.input/output to input/output (#5460)
* feat(otel): map traceloop.entity.input/output to input/output in langfuse

* chore: workaround to have `null` detections parsed in snyk

* chore: add workaround source note

* chore: formatting

* chore: add replace for worker
2025-02-11 08:43:13 +00:00
Steffen SchmitzandGitHub 92d5f3524b chore: enable tracing on all platforms (#5461) 2025-02-11 07:41:16 +00:00
Steffen SchmitzandGitHub e490147d73 feat(otel): accept application/json content type spans (#5450)
* feat(otel): accept application/json content type spans

* chore: apply suggestion
2025-02-11 07:22:02 +00:00
Max Deichmann 5a7ba1fcbc chore: release v3.26.0 2025-02-10 22:44:15 +01:00
Max DeichmannandGitHub 8204fb2a24 fix: fix cost calculation discrepancies in dashboards (#5448)
* fix: fix charts

* security: upgrade jsonpath-plus

* security: upgrade jsonpath-plus

* fix

* fix

* fix

* fix

* push

* push
2025-02-10 21:13:05 +00:00
Steffen SchmitzandGitHub 2559a388aa feat(otel): add input/output and name on traces (#5449) 2025-02-10 17:22:44 +00:00
Max DeichmannandGitHub 27e1785362 security: upgrade jsonpath-plus (#5445)
* security: upgrade jsonpath-plus

* push
2025-02-10 15:25:15 +00:00
Hassieb PakzadandGitHub 3fc9cee53d fix(model-prices): gemini 2 vertex AI prices (#5444) 2025-02-10 14:28:03 +00:00
Steffen SchmitzandGitHub 0dfefd2793 perf: skip processing of already seen events in worker (#5437)
* perf: skip processing of already seen events in worker

* chore: add queue delay to make use of seen events processing
2025-02-10 09:45:45 +00:00
Max DeichmannGitHubellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
25bc0fc660 perf: improve trpc session.id performance (#5431)
* perf: improve trpc session.id performance

* perf: improve trpc session.id performance

* push

* perf: improve trpc session.id performance

* Update web/src/server/api/routers/sessions.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-02-09 10:28:36 +00:00
Max DeichmannandGitHub ccd5ab97a4 perf: improve performance for trace.id trpc route (#5430)
* push

* fix
2025-02-08 10:54:38 +00:00
Steffen SchmitzandGitHub bf68a7edd5 feat: map additional properties for otel llm spans (#5422) 2025-02-07 15:40:20 +00:00
marliessophieandGitHub 2a697a9048 feat(tables): add select all interface to tables (#5314)
* feat(ui): extract generalized `TableActionMenu`

* chore(select-all): add queue infra

* chore(select-all): add `POST` selectAll trpc route

* fixup: register queue

* chore: improve state management

* fixup: handle select all job

* chore: handle streamed records in actions

* chore(ui): add `DataTableSelectAllBanner`

* chore: handle multi-select in interface

* chore: skip processed chunks on retries

* chore: clear select all state on route nav

* chore: extract select-column components

* feat: query options for create action

* refactor: rename router

* chore: add annotation queue item processing in select all job

* fix: TS typo

* fix: sync session storage across modals and tabs

* chore: block select all if job on table for project is in progress

* chore: fix blocking select all jobs

* chore: make specific to table name

* push

* revert: commited by mistake

* remove dead code

* fixup: test

* push

* push

* chore: simplify `TableSelectionManager`

* chore(ui): refactor `SelectAll` -> `BulkAction`

* chore(fixup): refactor `SelectAll` -> `BatchAction`

* chore: set a deterministic `jobId` on redis

* chore: drop progress indicator

* chore: refactor remove selectAll route and extend existing routes instead

* push

* chore: remove dead code

* chore: refactor extract `processPostgresTraceDelete`

* push

* fix test

* chore: add batch action capability to annotation queue

* eslint

* push

* push

* push

* push

* push

* push

* push

* fix: add trace entitlement check to trace.deleteMany

* style: show note if batch action is in progress

* push

* fix imports

* cleanup
2025-02-07 10:21:44 +00:00
marliessophieandGitHub 87a961be47 fix(gemini): pricing units (#5420)
* fix(gemini): pricing units

* push
2025-02-07 10:03:52 +00:00
Max DeichmannandGitHub 3a52c59f2a fix: do not run snyk in merge groups (#5415)
fix
2025-02-06 22:55:23 +00:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
1722703623 chore(deps): bump jsonpath-plus from 10.0.7 to 10.2.0 (#5411)
Bumps [jsonpath-plus](https://github.com/s3u/JSONPath) from 10.0.7 to 10.2.0.
- [Release notes](https://github.com/s3u/JSONPath/releases)
- [Changelog](https://github.com/JSONPath-Plus/JSONPath/blob/main/CHANGES.md)
- [Commits](https://github.com/s3u/JSONPath/compare/v10.0.7...v10.2.0)

---
updated-dependencies:
- dependency-name: jsonpath-plus
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-02-06 21:32:03 +00:00
Max DeichmannandGitHub 129c94c455 security: upgrade jsonpath-plus (#5409)
* fix

* fix
2025-02-06 14:24:19 +00:00
Steffen SchmitzandGitHub 23a62e3a03 chore: deduplicate postgres event list by bucketPath (#5407) 2025-02-06 13:56:46 +00:00
steffen911 d2a8d4e4b1 chore: release v3.25.0 2025-02-06 14:29:41 +01:00
Steffen SchmitzandGitHub 431f8ed941 chore: fetch file list for worker processing from s3 event log (#5405) 2025-02-06 13:08:35 +00:00
Iaroslav VolkovandGitHub f50b69cbc8 feat: add custom gid and uid support (#5355) 2025-02-06 14:06:07 +01:00
Max DeichmannandGitHub cdde86d96e fix: improve working for eval jsonpath selector (#5406)
* fix

* push
2025-02-06 12:54:02 +00:00
marliessophieandGitHub 9e84150ce0 feat(model): add playground and eval support for Gemini 2.0 Flash, Gemini 2.0 Flash-Lite, and Gemini 2.0 Pro (#5403)
* feat(model): add playground and eval support for Gemini 2.0 Flash, Gemini 2.0 Flash-Lite, and Gemini 2.0 Pro

* chore: add costs
2025-02-06 11:51:38 +00:00
Max DeichmannandGitHub a6fbceff84 feat: use json-path to select from tracing data for evals (#5402)
* push

* push

* push

* error handling
2025-02-06 11:02:57 +00:00
Max DeichmannandGitHub 3ca6dd48c0 fix: return empty results in dashboard if from is larger than to (#5389)
push
2025-02-05 16:36:22 +00:00
marliessophieandGitHub 03e80bac76 fix(ui-markdown): fallback to json view if markdown parsing is unsucessful (#5386)
fix(ui-markdown): fallback to json view if markdown parsing is unsuccessful
2025-02-05 15:13:10 +00:00
Steffen SchmitzandGitHub 005ba31740 chore: remove unused imports (#5388) 2025-02-05 15:00:49 +00:00
Max DeichmannandGitHub 727797e0ec perf: do not load all models by default in the dashboards (#5387)
* fix

* push

* fix
2025-02-05 14:31:51 +00:00
Steffen SchmitzandGitHub 123f513199 chore: optionally log s3 event bucket uploads in postgres (#5381)
* chore: optionally log s3 event bucket uploads in postgres

* chore: reduce uniqueness constraints and separate eventId from eventLog id field
2025-02-05 14:05:45 +00:00
89896c70ee fix: model aggregation for daily metrics (#5384)
* fix: model aggregation for daily metrics

* fix query

* remove comment

---------

Co-authored-by: Hassieb Pakzad <68423100+hassiebp@users.noreply.github.com>
2025-02-05 11:23:02 +00:00
marliessophieandGitHub e52f9dd1e2 fix(dataset-evals): reference job.observationId rather than sourceObservationId (#5350)
* fix(dataset-evals): reference `job.observationId` rather than `sourceObservationId`

* chore: typo
2025-02-05 10:53:36 +00:00
marliessophieandGitHub ace69419b3 fix(ui): input changes lost on focus in dataset item edit (#5380)
* fix(ui): input changes lost on focus in dataset item edit

* push
2025-02-05 09:21:01 +00:00
marliessophieandGitHub 6f3cc8982a style(dataset-analytics): decrease chart height and width (#5379) 2025-02-05 08:55:09 +00:00
Steffen SchmitzandGitHub c612109948 chore: fix flaky traces-api test (#5370) 2025-02-04 16:43:03 +00:00
Marc Klingen 2359d7f9ae chore: release v3.24.1 2025-02-04 15:55:02 +01:00
Steffen SchmitzandGitHub 1baa0aaaed chore: decrease ingestion queue delay outside of date boundaries (#5364)
* chore: decrease ingestion queue delay outside of date boundaries

* chore: check for non-null delay instead of truthy
2025-02-04 13:33:29 +00:00
c4186102eb fix: fix flaky dataset test (#5366)
* fix(dataset-evals): reference `job.observationId` rather than `sourceObservationId`

* chore: typo

* push

* push

---------

Co-authored-by: Marlies Mayerhofer <74332854+marliessophie@users.noreply.github.com>
2025-02-04 13:29:27 +00:00
Steffen SchmitzandGitHub 016993c117 fix: instantiate the ratelimit redis client on first use to avoid connection errors (#5362) 2025-02-04 07:23:44 +00:00
Marc Klingen 909bdde9d8 chore: release v3.24.0 2025-02-03 20:54:10 +01:00
Marc KlingenandGitHub 6f074dc59f feat(ui): add local iso date with utc on hover and ms precision on traces (#5359)
* feat(ui): add local iso date with utc on hover and ms precision on traces

* fixes
2025-02-03 19:48:06 +00:00
Hassieb PakzadandGitHub b8bc474b83 fix(playground): allow o3 (#5357) 2025-02-03 16:16:31 +00:00
Marc KlingenandGitHub 334d34ac15 chore: add cmd_k_menu:opened event for main menu "go to..." button (#5351) 2025-02-03 13:13:55 +00:00
marliessophieandGitHub 1efb37f3c1 fix(filter-ui): support mouse wheel scroll behaviour on desktop and mobile (#5346) 2025-02-03 10:26:23 +00:00
Steffen SchmitzandGitHub 5fc87cabeb chore: upgrade prisma to version 6 (#5266)
* chore: upgrade prisma to version 6

* chore: update dockerfile

* chore: upgrade prisma
2025-02-03 10:03:07 +00:00
marliessophieandGitHub a14fb003e6 fix(score-analytics): display categorical data in dashboard (#5341) 2025-02-03 08:36:24 +00:00
Max DeichmannandGitHub e1521b4ef1 fix: add bedrock throttling exception to retries for evals (#5338)
push
2025-02-02 22:52:13 +00:00
Hassieb PakzadandGitHub fd8756ff4c chore(media): add retries on media record write (#5336) 2025-02-02 09:14:11 +01:00
Marc KlingenandGitHub d69808747c chore(models): updated price for o1-mini (#5335) 2025-02-01 13:58:44 +00:00
Max DeichmannandGitHub 854e2c60c8 fix: fix observation frontend exception (#5334)
* fix

* push

* fix

* push
2025-02-01 10:57:40 +00:00
Hassieb PakzadandGitHub 4567ed473e chore(media-api): add instrumentation (#5333) 2025-02-01 10:00:08 +01:00
Steffen SchmitzandGitHub 2abc9fed7a fix: handle multiple number types in otel parser (#5323)
* chore: add more otel logging

* chore: logging

* chore: enhance log message

* chore: handle number timestamps correctly

* chore: handle non-object intvalue
2025-02-01 07:19:55 +00:00
Marc KlingenandGitHub f6de06d695 chore: remove polynomial regex from MUSTACHE_REGEX (#5328)
fix: optimize MUSTACHE_REGEX to remove polynomial regex
2025-01-31 21:53:42 +00:00
Marc Klingen 02b9220c14 chore: release v3.23.0 2025-01-31 22:09:29 +01:00
Marc KlingenandGitHub e15a26d1de feat(models): add o3-mini and o3-mini-2025-01-31 (#5327) 2025-01-31 22:08:50 +01:00
Max Deichmann 1c5c072eed chore: release v3.22.0 2025-01-31 20:00:46 +01:00
Max DeichmannandGitHub b805b9c93f perf: improve observation list endpoint CH performance (#5325)
fix
2025-01-31 18:56:49 +00:00
Hassieb PakzadandGitHub da147ea5aa fix(media-api): handle retries on existing UUIDs (#5320) 2025-01-31 18:07:29 +01:00
Marc KlingenandGitHub 8e15c9770b chore(ui): improve sizing of chat message role button (#5321) 2025-01-31 16:12:04 +00:00
Steffen SchmitzandGitHub 799c7cf940 feat: create otel/v1/traces endpoint to accept otel spans (#5241)
* feat: create otel/v1/traces endpoint to accept otel spans

* chore: add comments

* chore: otel test

* chore: fallback for buffers

* chore: attribute parsing

* chore: empty fallback on attributes

* chore: remove otel collector

* chore: remove otlp-transformer dependency

* chore: remove unrelated test case

* chore: remove header logging

* chore: add traceloop example

* chore: update lockfile

* chore: revert lock

* chore: reduce delta

* chore: add otel specific rate limits

* chore: reuse ingestion rate-limit config

* chore: document generated code

* chore: test setup

* chore: adjust result parsing

* chore: typing

* chore: otel typing
2025-01-31 15:58:43 +00:00
Steffen SchmitzandGitHub 64d784e16e fix: retry failed connections in RateLimiter and disable offlinequeue (#5317) 2025-01-31 14:58:57 +00:00
Marc KlingenandGitHub 096467d7dd feat(ui): open cmd+k menu from main menu (#5318)
* feat(ui): open cmd+k menu from main menu

* fix lint and naming

* move provider to fix issue
2025-01-31 14:51:13 +00:00
Marc KlingenandGitHub dc995ff377 fix(ui): deduplicate prompt variables in variable preview (#5316) 2025-01-31 13:46:57 +00:00
Marc KlingenandGitHub 935aa20dda fix(ui): correct value for accent-foreground color (#5315) 2025-01-31 13:43:51 +00:00
Steffen SchmitzandGitHub 543ee3fb77 fix: disable autopipelining for rate limits to avoid uncaught exceptions (#5300)
* fix: disable autopipelining for rate limits to avoid uncaught exceptions

* chore: adjust

* chore: add shutdown logic for ratelimitservice

* chore: adjust tests

* chore: test setup
2025-01-31 10:13:13 +00:00
Max Deichmann 95c6047724 chore: release v3.21.0 2025-01-30 23:31:27 +01:00
Max DeichmannandGitHub 6e31e559f0 fix: parse inputs and outputs correctly when adding to datasets (#5307)
* fix

* fix

* fix
2025-01-30 22:18:31 +00:00
Marc KlingenandGitHub 4ec1fc53d1 feat(ui): customize codemirror theme (#5305)
* remove existing theme

* init themes

* push

* doesnt work

* hide gutters when no line numbers

* push

* push

* fix import
2025-01-30 22:13:29 +00:00
Max DeichmannandGitHub 7e24f5f42c chore: download 20 S3 ingestion events at a time (#5306) 2025-01-30 21:54:58 +01:00
Marc KlingenandGitHub fe00afa627 fix(ui): hide project-level routes in project overview main menu, disable active project in cmd+k menu (#5303) 2025-01-30 20:10:19 +00:00
Max DeichmannandGitHub 3e5dc4a551 fix: pass tracing input / output as string via trpc (#5302)
* fix

* fix

* fix

* fix
2025-01-30 19:37:46 +00:00
Marc KlingenandGitHub fa75fb9245 feat(ui): use codemirror for text area input, highlighting/linting of prompt variables (#5296)
* abstract editor to support "text" mode in addition to "json" mode

* always use CodeMirrorEditor for prompts

* minheight on editor

* upgrade codemirror and add language package

* add linting for prompts and switch to githubDark theme

* package

* use codemirror for chat prompts

* imrpove scroll behavior of new dataset form

* improve dataset item editor view

* push

* remove dep pinning

* align editor linting with current variable definition

* defauklt value to value
2025-01-30 19:36:40 +00:00
Max Deichmann a640a6a139 chore: release v3.20.0 2025-01-30 19:50:57 +01:00
Hassieb PakzadandGitHub b0c12f02ec fix(llm-api-key): overwrite default top_p on key test (#5301) 2025-01-30 18:47:28 +01:00
Max DeichmannandGitHub 774efa4eaa perf: batch read single S3 events (#5298)
* push

* fix

* push

* fix
2025-01-30 17:13:40 +00:00
Max DeichmannandGitHub a866cba228 chore: improve 429 error handling (#5282) 2025-01-30 16:46:38 +00:00
Marc KlingenandGitHub 92b6963347 feat: add posthog events to cmd+k menu (#5288)
* feat: add posthog events to cmd+k menu

* ellipsis fix
2025-01-30 17:27:33 +01:00
Steffen SchmitzandGitHub ba55837b71 chore: move create export job log to internal lib (#5295) 2025-01-30 15:50:27 +00:00
Marc KlingenandGitHub 966efa1b92 docs(tracing-users): add header tooltips to user table (#5290)
docs: add header tooltips to user table
2025-01-30 15:12:37 +00:00
Marc KlingenandGitHub dbe5b93a8a fix(ui): do not close dialogs on outside interactions by default (#5294) 2025-01-30 15:11:52 +00:00
Marc KlingenandGitHub 22371b4c32 feat(prompts): scroll selected prompt version into view (#5293)
* feat(prompts): scroll prompt versions independently from prompt itself

* feat(prompts): scroll selected prompt version into view
2025-01-30 15:00:23 +00:00
marliessophieandGitHub 8d1c381d46 fix(media-ui): fetch i/o media only for authed project member (#5284) 2025-01-30 15:57:49 +01:00
Marc KlingenandGitHub 1efce634e7 feat(prompts): scroll prompt versions independently from prompt itself (#5292) 2025-01-30 14:20:17 +00:00
Steffen SchmitzandGitHub ec46e7d68e fix: correct default timestamp order for traces table (#5291)
* fix: correct default timestamp order for traces table

* chore: correct order

* chore: typo
2025-01-30 14:18:58 +00:00
Hassieb PakzadandGitHub b302e8eb96 chore(evals): handle invalid JSON error if maxTokens too low (#5289) 2025-01-30 14:50:10 +01:00
marliessophieandGitHub e04e21bf13 fix(rbac): load trace data in shared sessions (#5283)
* fix(rbac): load trace data in shared sessions

* chore: refactor and simplify
2025-01-30 13:12:16 +00:00
Marc KlingenandGitHub 273bcddc0f feat: switch between projects/orgs via cmd+k menu (#5285)
* filter out dynamic routes

* add project deeplinks
2025-01-30 13:10:53 +00:00
Max Deichmann e2099de653 chore: release v3.19.0 2025-01-30 11:46:17 +01:00
Max DeichmannandGitHub 435a09f7df feat: add more x-axis chart ticks (#5220)
* push

* push

* push

* chore: release v2.58.0

* push

* push

* push

* fix

* push

* push

* fix
2025-01-30 10:06:28 +00:00
Steffen SchmitzandGitHub 037dbd8c9d feat: add LANGFUSE_INIT_PROJECT_RETENTION support to init data retention (#5281)
* feat: accept LANGFUSE_INIT_PROJECT_RETENTION setting

* feat: add LANGFUSE_INIT_PROJECT_RETENTION support to init data retention
2025-01-30 09:52:30 +00:00
Marc KlingenandGitHub 02a3d91c56 feat(ui): add cmd+k menu (#5276)
* rename existing command exports

* move existing to input-command

* add comment

* wip cmd k menu for navigation

* fix types and paths of nested menu items

* add support for nested menu items

* filter correctly
2025-01-30 09:38:27 +00:00
Steffen SchmitzandGitHub 8821ad5b30 chore: remove data retention beta label and allow self-host enterprise plan (#5279)
* chore: remove data retention beta label

* chore: allow data-retention for self-host enterprise
2025-01-30 09:28:45 +00:00
Marc KlingenandGitHub ae1ba493aa chore(deps): bump cmdk 1.0.4 (#5275) 2025-01-30 00:01:04 +00:00
Max DeichmannandGitHub 5d2735ee14 security: upgrade sentry (#5269)
push
2025-01-29 17:48:29 +00:00
marliessophieandGitHub 38f3336ad5 style(prompts): add note explaining prompt commit message purpose (#5268) 2025-01-29 16:19:33 +00:00
marliessophieandGitHub 6224d7ad0f fix(dataset-analytics): latency label should denote seconds (s) (#5267) 2025-01-29 15:03:39 +00:00
marliessophieandGitHub 30c8fc2239 fix(experiments): double brace in json syntax mistaken as variable (#5264)
* fix(experiments): double brace in json syntax mistaken as variable

* push
2025-01-29 13:33:51 +00:00
marliessophieandGitHub edbf16f3a6 fix(experiments): change logger.warning to logger.error call (#5263)
fix(experiments): remove invalid `logger.warning` call from service
2025-01-29 12:41:42 +00:00
marliessophieandGitHub 8d050717a9 chore: support uploads of CSV files with just one column (#5262)
* chore: support uploads of CSV files with just one column

* chore: increase preview file byte size

* push
2025-01-29 10:45:18 +00:00
74703f62c4 ci: lock in current lint warning levels (#2648)
* ci(worker): enforce linting

* chore: lock current linting levels

* chore: lock current lint warning levels

---------

Co-authored-by: steffen911 <steffen@langfuse.com>
2025-01-29 08:53:19 +00:00
Max DeichmannandGitHub 09603a1f23 security: upgrade golang github.com/golang-jwt/jwt/v4 (#5249)
* push

* push
2025-01-28 16:53:48 +00:00
Steffen SchmitzandGitHub 34eb3e3d76 perf: reduce redundant parsing operations within ingestionservice (#5243)
* perf: reduce redundant parsing operations within ingestionservice

* chore: utils

* chore: move trace record parsing

* chore: cleanup

* chore: access input output correctly

* chore: avoid mutations

* chore: test cases

* chore: typo
2025-01-28 16:42:04 +00:00
Hassieb PakzadandGitHub b307a75a9a feat(messages-ui): allow removing system message (#5248) 2025-01-28 17:44:41 +01:00
marliessophieandGitHub 9f20b3e1cd feat(prompts): support commit_message (#5197)
* chore(prompts-ui): add nullable `commit_message` col

* chore(prompts-ui): add commit message to prompts

* chore(prompts-api): add commit message to prompts v2 api

* chore: rename migration

* chore: extract commit message length const

* fix: legacy types

* push

* chore: refactor types to not extend legancy, but create base types

* feat: add commit message to prompt diff view between versions

* chore: migration final in order

* push
2025-01-28 16:32:05 +00:00
Hassieb PakzadandGitHub 4ae24f97f5 fix(ui-model-table): collapsed view (#5246) 2025-01-28 16:40:04 +01:00
Hassieb PakzadandGitHub 58858de930 chore(llm-keys): rename vertex-ai to google-vertex-ai (#5244) 2025-01-28 16:11:16 +01:00
Max Deichmann b8a9630731 chore: release v3.18.0 2025-01-27 23:56:51 +01:00
Max DeichmannandGitHub aec58b1149 fix: use correct path for prompt versions api (#5236)
* push

* push
2025-01-27 22:54:50 +00:00
marliessophieandGitHub d3634917d4 chore(datasets): increase csv upload limit to 10MB (#5234) 2025-01-27 21:33:23 +00:00
Max DeichmannandGitHub 52fa9eb1ff fix: align naming of prompt patch docs (#5233)
push
2025-01-27 16:12:52 +00:00
Marc KlingenandGitHub e27f0bdc1d fix(cloud): fallback to clikchouse when usage meter cannot be fetched from stripe (#5232)
* fix(cloud): fallback to clikchouse when usage meter cannot be fetched from stripe

* use error
2025-01-27 15:28:51 +00:00
marliessophieandGitHub 0576f01641 fix(experiments): improve error handling (#5209)
* fixup: execute trace creation callback handler

* chore: create trace for experimentation on error

* push

* chore: adjust test to new behaviour

* push

* push
2025-01-27 15:23:15 +00:00
Hassieb PakzadandGitHub 9f6fccfbeb fix(evals): remove system message (#5231) 2025-01-27 16:07:39 +01:00
Marc KlingenandGitHub 7cb9b75897 fix(ui): tabIndex on sign in page to skip password reset and cloud region info (#5230) 2025-01-27 14:36:46 +00:00
Marc KlingenandGitHub 5857a9e61d feat(ui): scroll deeplinked observation into view in trace tree (#5228)
* refactor component to single out the node

* push
2025-01-27 14:22:14 +00:00
Hassieb Pakzad a9a9136010 chore: release v3.17.1 2025-01-27 15:32:23 +01:00
Hassieb PakzadandGitHub e5c45e381e fix(llm-api-key): extra header JSON parsing (#5229) 2025-01-27 15:19:24 +01:00
Steffen SchmitzandGitHub cb00d463c7 feat: remove data beyond retention limit from clickhouse (#5226)
* feat: remove data beyond retention limit from clickhouse

* chore: lint

* chore: log statement

* chore: typo
2025-01-27 13:37:56 +00:00
Steffen SchmitzandGitHub e18ac03b44 perf: use final for traces and observations api if no skip indexes are filtered (#5223)
* perf: use final for traces and observations api if no skip indexes are filtered

* chore: operator order
2025-01-27 13:16:10 +00:00
Marc Klingen d54cbc6c9b chore: release v3.17.0 2025-01-27 13:38:42 +01:00
Marc KlingenandGitHub 332f6658d9 ci: run codespell also on v2 branch and prs (#5224) 2025-01-27 13:20:58 +01:00
Hassieb PakzadandGitHub 25a559293b fix(media): base id gen on project ID + content hash (#5222) 2025-01-27 11:57:47 +01:00
Max DeichmannandGitHub 9ff8643489 chore: add client side logging for auth errors (#5221)
push
2025-01-27 10:03:02 +00:00
Steffen SchmitzandGitHub dd7e4f344e fix: align input/output and metadata parsing between GET /traces and /traces/:id (#5218)
* fix: align input/output and metadata parsing between GET /traces and /traces/:id

* chore: lint

* chore: lint
2025-01-27 09:53:33 +00:00
Marc KlingenandGitHub fe089e15f2 fix(openapi): upgrade openapi spec generator to correctly specify /ingestion 207 status code (#5217) 2025-01-27 10:44:33 +01:00
Marc KlingenandGitHub 9f8793e26a feat(auth): make checks and auth method configurable across SSO providers (#5203)
push
2025-01-27 09:12:58 +00:00
Hassieb PakzadandGitHub a1cb4c727b fix(media): remove transactions (#5211) 2025-01-25 23:44:34 +01:00
Hassieb PakzadandGitHub b39eb5445a fix(media): reduce tx level to RepeateableRead (#5210) 2025-01-25 21:09:14 +01:00
Hassieb PakzadandGitHub b611301658 fix(media-api): increase tx maxWait (#5208) 2025-01-25 16:12:34 +01:00
Hassieb PakzadandGitHub c3fd8a74dc fix(trace-timeline): first token label (#5202) 2025-01-24 16:38:47 +01:00
426 changed files with 37465 additions and 9355 deletions
+21 -1
View File
@@ -65,37 +65,55 @@ OTEL_SERVICE_NAME="langfuse"
# AUTH_GOOGLE_CLIENT_SECRET=
# AUTH_GOOGLE_ALLOW_ACCOUNT_LINKING=false
# AUTH_GOOGLE_ALLOWED_DOMAINS=langfuse.com,google.com # optional allowlist of workspace domains that can sign in via Google
# AUTH_GOOGLE_CLIENT_AUTH_METHOD=
# AUTH_GOOGLE_CHECKS=
# AUTH_GITHUB_CLIENT_ID=
# AUTH_GITHUB_CLIENT_SECRET=
# AUTH_GITHUB_ALLOW_ACCOUNT_LINKING=false
# AUTH_GITHUB_CLIENT_AUTH_METHOD=
# AUTH_GITHUB_CHECKS=
# AUTH_GITHUB_ENTERPRISE_CLIENT_ID=
# AUTH_GITHUB_ENTERPRISE_CLIENT_SECRET=
# AUTH_GITHUB_ENTERPRISE_BASE_URL=
# AUTH_GITHUB_ENTERPRISE_ALLOW_ACCOUNT_LINKING=false
# AUTH_GITHUB_ENTERPRISE_CLIENT_AUTH_METHOD=
# AUTH_GITHUB_ENTERPRISE_CHECKS=
# AUTH_GITLAB_CLIENT_ID=
# AUTH_GITLAB_CLIENT_SECRET=
# AUTH_GITLAB_ALLOW_ACCOUNT_LINKING=false
# AUTH_GITLAB_ISSUER=
# AUTH_GITLAB_CLIENT_AUTH_METHOD=
# AUTH_GITLAB_CHECKS=
# AUTH_AZURE_AD_CLIENT_ID=
# AUTH_AZURE_AD_CLIENT_SECRET=
# AUTH_AZURE_AD_TENANT_ID=
# AUTH_AZURE_ALLOW_ACCOUNT_LINKING=false
# AUTH_AZURE_AD_ALLOW_ACCOUNT_LINKING=false
# AUTH_AZURE_AD_CLIENT_AUTH_METHOD=
# AUTH_AZURE_AD_CHECKS=
# AUTH_OKTA_CLIENT_ID=
# AUTH_OKTA_CLIENT_SECRET=
# AUTH_OKTA_ISSUER=
# AUTH_OKTA_ALLOW_ACCOUNT_LINKING=false
# AUTH_OKTA_CLIENT_AUTH_METHOD=
# AUTH_OKTA_CHECKS=
# AUTH_AUTH0_CLIENT_ID=
# AUTH_AUTH0_CLIENT_SECRET=
# AUTH_AUTH0_ISSUER=
# AUTH_AUTH0_ALLOW_ACCOUNT_LINKING=false
# AUTH_AUTH0_CLIENT_AUTH_METHOD=
# AUTH_AUTH0_CHECKS=
# AUTH_COGNITO_CLIENT_ID=
# AUTH_COGNITO_CLIENT_SECRET=
# AUTH_COGNITO_ISSUER=
# AUTH_COGNITO_ALLOW_ACCOUNT_LINKING=false
# AUTH_COGNITO_CLIENT_AUTH_METHOD=
# AUTH_COGNITO_CHECKS=
# AUTH_KEYCLOAK_CLIENT_ID=
# AUTH_KEYCLOAK_CLIENT_SECRET=
# AUTH_KEYCLOAK_ISSUER=
# AUTH_KEYCLOAK_ALLOW_ACCOUNT_LINKING=false
# AUTH_KEYCLOAK_CLIENT_AUTH_METHOD=
# AUTH_KEYCLOAK_CHECKS=
# AUTH_CUSTOM_CLIENT_ID=
# AUTH_CUSTOM_CLIENT_SECRET=
# AUTH_CUSTOM_ISSUER=
@@ -104,6 +122,8 @@ OTEL_SERVICE_NAME="langfuse"
# AUTH_CUSTOM_CLIENT_AUTH_METHOD="client_secret_basic" # optional
# AUTH_CUSTOM_ALLOW_ACCOUNT_LINKING=false
# AUTH_CUSTOM_ID_TOKEN=false # optional, default is true
# AUTH_CUSTOM_CLIENT_AUTH_METHOD=
# AUTH_CUSTOM_CHECKS=
# Transactional email, optional
# Defines the email address to use as the from address.
+6 -2
View File
@@ -3,9 +3,13 @@ name: Codespell
on:
push:
branches: [main]
branches:
- "main"
tags:
- "v*"
pull_request:
branches: [main]
branches:
- "**"
merge_group:
permissions:
+14 -6
View File
@@ -89,7 +89,7 @@ jobs:
timeout 10 bash -c 'until curl -f http://localhost:3000/api/public/health; do sleep 2; done'
tests-web-sync:
timeout-minutes: 20
timeout-minutes: 30
runs-on: ubuntu-latest
needs:
- pre-job
@@ -107,7 +107,7 @@ jobs:
- uses: actions/checkout@v4
- name: Install golang-migrate for Clickhouse migrations
run: |
curl -L https://github.com/golang-migrate/migrate/releases/download/v4.16.2/migrate.linux-amd64.tar.gz | tar xvz
curl -L https://github.com/golang-migrate/migrate/releases/download/v4.18.2/migrate.linux-amd64.tar.gz | tar xvz
sudo mv migrate /usr/bin/migrate
which migrate
- uses: pnpm/action-setup@v3
@@ -165,7 +165,7 @@ jobs:
run: pnpm --filter=web run test-client
tests-web-async:
timeout-minutes: 20
timeout-minutes: 30
runs-on: ubuntu-latest
needs:
- pre-job
@@ -184,7 +184,7 @@ jobs:
- uses: actions/checkout@v4
- name: Install golang-migrate for Clickhouse migrations
run: |
curl -L https://github.com/golang-migrate/migrate/releases/download/v4.16.2/migrate.linux-amd64.tar.gz | tar xvz
curl -L https://github.com/golang-migrate/migrate/releases/download/v4.18.2/migrate.linux-amd64.tar.gz | tar xvz
sudo mv migrate /usr/bin/migrate
which migrate
- uses: pnpm/action-setup@v3
@@ -277,7 +277,7 @@ jobs:
pnpm install
- name: Install golang-migrate for Clickhouse migrations
run: |
curl -L https://github.com/golang-migrate/migrate/releases/download/v4.16.2/migrate.linux-amd64.tar.gz | tar xvz
curl -L https://github.com/golang-migrate/migrate/releases/download/v4.18.2/migrate.linux-amd64.tar.gz | tar xvz
sudo mv migrate /usr/bin/migrate
which migrate
- name: Load default env
@@ -378,7 +378,7 @@ jobs:
pnpm install
- name: Install golang-migrate for Clickhouse migrations
run: |
curl -L https://github.com/golang-migrate/migrate/releases/download/v4.16.2/migrate.linux-amd64.tar.gz | tar xvz
curl -L https://github.com/golang-migrate/migrate/releases/download/v4.18.2/migrate.linux-amd64.tar.gz | tar xvz
sudo mv migrate /usr/bin/migrate
which migrate
- name: Load default env
@@ -536,3 +536,11 @@ jobs:
platforms: |
linux/amd64
${{ startsWith(github.ref, 'refs/tags/') && 'linux/arm64' || '' }}
- name: Notify Slack
uses: ravsamhq/notify-slack-action@v2
if: always()
with:
status: ${{ job.status }}
notify_when: "failure"
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
+15 -1
View File
@@ -6,7 +6,7 @@ on:
push:
branches:
- main
merge_group:
# Snyk cannot upload results in merge group. Hence, we only run on PRs and when pushingon the main branch https://github.com/github/codeql-action/issues/1572
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
@@ -29,6 +29,13 @@ jobs:
image: langfuse-langfuse-web
args: --file=web/Dockerfile
# Workaround for https://github.com/github/codeql-action/issues/2187
- name: Replace security-severity undefined for license-related findings
run: "sed -i 's/\"security-severity\": \"undefined\"/\"security-severity\": \"0\"/g' snyk.sarif"
- name: Replace security-severity null for license-related findings
run: "sed -i 's/\"security-severity\": \"null\"/\"security-severity\": \"0\"/g' snyk.sarif"
- name: Upload result to GitHub Code Scanning
uses: github/codeql-action/upload-sarif@v3
with:
@@ -44,6 +51,13 @@ jobs:
image: langfuse-langfuse-worker
args: --file=worker/Dockerfile
# Workaround for https://github.com/github/codeql-action/issues/2187
- name: Replace security-severity undefined for license-related findings
run: "sed -i 's/\"security-severity\": \"undefined\"/\"security-severity\": \"0\"/g' snyk.sarif"
- name: Replace security-severity null for license-related findings
run: "sed -i 's/\"security-severity\": \"null\"/\"security-severity\": \"0\"/g' snyk.sarif"
- name: Upload result to GitHub Code Scanning
uses: github/codeql-action/upload-sarif@v3
with:
+1
View File
@@ -7,6 +7,7 @@
# testing
/coverage
/certs/
# database
/prisma/db.sqlite
+354
View File
@@ -0,0 +1,354 @@
![Langfuse GitHub Banner](https://langfuse.com/images/docs/github-readme/github-banner.png)
<div align="center">
<div>
<h3>
<a href="https://langfuse.com/cn">
<strong>🇨🇳 🤝 🪢</strong>
</a> ·
<a href="https://cloud.langfuse.com">
<strong>Langfuse Cloud</strong>
</a> ·
<a href="https://langfuse.com/docs/deployment/self-host">
<strong>自托管</strong>
</a> ·
<a href="https://langfuse.com/demo">
<strong>演示</strong>
</a>
</h3>
</div>
<div>
<a href="https://langfuse.com/docs"><strong>文档</strong></a> ·
<a href="https://langfuse.com/issues"><strong>报告问题</strong></a> ·
<a href="https://langfuse.com/ideas"><strong>功能请求</strong></a> ·
<a href="https://langfuse.com/changelog"><strong>更新日志</strong></a> ·
<a href="https://langfuse.com/roadmap"><strong>路线图</strong></a> ·
</div>
<br/>
<span>Langfuse 使用 <a href="https://github.com/orgs/langfuse/discussions"><strong>Github Discussions</strong></a> 作为支持和功能请求的平台。</span>
<br/>
<span><b>我们正在招聘。</b> <a href="https://langfuse.com/careers"><strong>加入我们</strong></a>,从事产品工程和技术市场职位。</span>
<br/>
<br/>
<div>
</div>
</div>
<p align="center">
<a href="https://github.com/langfuse/langfuse/blob/main/LICENSE">
<img src="https://img.shields.io/badge/License-MIT-E11311.svg" alt="MIT License">
</a>
<a href="https://www.ycombinator.com/companies/langfuse">
<img src="https://img.shields.io/badge/Y%20Combinator-W23-orange" alt="Y Combinator W23">
</a>
<a href="https://hub.docker.com/u/langfuse" target="_blank">
<img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/langfuse/langfuse?labelColor=%20%23FDB062&logo=Docker&labelColor=%20%23528bff">
</a>
<a href="https://pypi.python.org/pypi/langfuse">
<img src="https://img.shields.io/pypi/dm/langfuse?logo=python&logoColor=white&label=pypi%20langfuse&color=blue" alt="langfuse Python package on PyPi">
</a>
<a href="https://www.npmjs.com/package/langfuse">
<img src="https://img.shields.io/npm/dm/langfuse?logo=npm&logoColor=white&label=npm%20langfuse&color=blue" alt="langfuse npm package">
</a>
<br/>
<a href="https://discord.com/invite/7NXusRtqYU" target="_blank">
<img src="https://img.shields.io/discord/1111061815649124414?logo=discord&labelColor=%20%235462eb&logoColor=%20%23f5f5f5&color=%20%235462eb"
alt="在 Discord 上聊天">
</a>
<a href="https://twitter.com/intent/follow?screen_name=langfuse" target="_blank">
<img src="https://img.shields.io/twitter/follow/langfuse?logo=X&color=%20%23f5f5f5"
alt="在 X (Twitter) 上关注">
</a>
<a href="https://www.linkedin.com/company/langfuse/" target="_blank">
<img src="https://custom-icon-badges.demolab.com/badge/LinkedIn-0A66C2?logo=linkedin-white&logoColor=fff"
alt="在 LinkedIn 上关注">
</a>
<a href="https://github.com/langfuse/langfuse/graphs/commit-activity" target="_blank">
<img alt="过去一个月的提交" src="https://img.shields.io/github/commit-activity/m/langfuse/langfuse?labelColor=%20%2332b583&color=%20%2312b76a">
</a>
<a href="https://github.com/langfuse/langfuse/" target="_blank">
<img alt="已关闭的问题" src="https://img.shields.io/github/issues-search?query=repo%3Alangfuse%2Flangfuse%20is%3Aclosed&label=issues%20closed&labelColor=%20%237d89b0&color=%20%235d6b98">
</a>
<a href="https://github.com/langfuse/langfuse/discussions/" target="_blank">
<img alt="讨论帖数量" src="https://img.shields.io/github/discussions/langfuse/langfuse?labelColor=%20%239b8afb&color=%20%237a5af8">
</a>
</p>
<p align="center">
<a href="./README.md"><img alt="README in English" src="https://img.shields.io/badge/English-d9d9d9"></a>
<a href="./README.cn.md"><img alt="简体中文版自述文件" src="https://img.shields.io/badge/简体中文-d9d9d9"></a>
<a href="./README.ja.md"><img alt="日本語のREADME" src="https://img.shields.io/badge/日本語-d9d9d9"></a>
<a href="./README.kr.md"><img alt="README in Korean" src="https://img.shields.io/badge/한국어-d9d9d9"></a>
</p>
Langfuse 是一个 **开源 LLM 工程** 平台。它帮助团队协作 **开发、监控、评估** 以及 **调试** AI 应用。Langfuse 可在几分钟内 **自托管**,并且经过 **实战考验**
[![Langfuse 概览视频](https://github.com/user-attachments/assets/3926b288-ff61-4b95-8aa1-45d041c70866)](https://langfuse.com/watch-demo)
## ✨ 核心特性
![Langfuse 概览](https://langfuse.com/images/docs/github-readme/github-feature-overview.png)
- [LLM 应用可观察性](https://langfuse.com/docs/tracing):为你的应用插入仪表代码,并开始将追踪数据传送到 Langfuse,从而追踪 LLM 调用及应用中其他相关逻辑(如检索、嵌入或代理操作)。检查并调试复杂日志及用户会话。试试互动的 [演示](https://langfuse.com/docs/demo) 看看效果。
- [提示管理](https://langfuse.com/docs/prompts/get-started) 帮助你集中管理、版本控制并协作迭代提示。得益于服务器和客户端的高效缓存,你可以在不增加延迟的情况下反复迭代提示。
- [评估](https://langfuse.com/docs/scores/overview) 是 LLM 应用开发流程的关键组成部分,Langfuse 能够满足你的多样需求。它支持 LLM 作为“裁判”、用户反馈收集、手动标注以及通过 API/SDK 实现自定义评估流程。
- [数据集](https://langfuse.com/docs/datasets/overview) 为评估你的 LLM 应用提供测试集和基准。它们支持持续改进、部署前测试、结构化实验、灵活评估,并能与 LangChain、LlamaIndex 等框架无缝整合。
- [LLM 试玩平台](https://langfuse.com/docs/playground) 是用于测试和迭代提示及模型配置的工具,缩短反馈周期,加速开发。当你在追踪中发现异常结果时,可以直接跳转至试玩平台进行调整。
- [综合 API](https://langfuse.com/docs/api):Langfuse 常用于驱动定制化的 LLMOps 工作流程,同时利用 Langfuse 提供的构建模块和 API。我们提供 OpenAPI 规格、Postman 集合以及针对 Python 和 JS/TS 的类型化 SDK。
## 📦 部署 Langfuse
![Langfuse 部署选项](https://langfuse.com/images/docs/github-readme/github-deployment-options.png)
### Langfuse Cloud
由 Langfuse 团队管理的部署,提供慷慨的免费额度(爱好者计划),无需信用卡。
<div align="center">
<a href="https://cloud.langfuse.com" target="_blank">
<img alt="注册 Langfuse Cloud" src="https://img.shields.io/badge/»%20Sign%20up%20for%20Langfuse%20Cloud-8A2BE2?&color=orange">
</a>
</div>
### 自托管 Langfuse
在你自己的基础设施上运行 Langfuse:
- [本地(docker compose](https://langfuse.com/self-hosting/local):使用 Docker Compose 在你的机器上于 5 分钟内运行 Langfuse。
````bash:README.md/docker-compose
# 获取最新的 Langfuse 仓库副本
git clone https://github.com/langfuse/langfuse.git
cd langfuse
# 运行 Langfuse 的 docker compose
docker compose up
`````
- [KubernetesHelm](https://langfuse.com/self-hosting/kubernetes-helm):使用 Helm 在 Kubernetes 集群上部署 Langfuse。这是推荐的生产环境部署方式。
- [虚拟机](https://langfuse.com/self-hosting/docker-compose):使用 Docker Compose 在单台虚拟机上部署 Langfuse。
- 【计划中】:针对各云平台的部署指南,欢迎在以下讨论中投票和评论:[AWS](https://github.com/orgs/langfuse/discussions/4645)、[Google Cloud](https://github.com/langfuse/discussions/4646)、[Azure](https://github.com/orgs/langfuse/discussions/4647)。
请参阅 [自托管文档](https://langfuse.com/self-hosting) 了解更多关于架构和配置选项的信息。
## 🔌 集成
![Langfuse 集成](https://langfuse.com/images/docs/github-readme/github-integrations.png)
### 主要集成:
| 集成 | 支持语言/平台 | 描述 |
| ---------------------------------------------------------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
| [SDK](https://langfuse.com/docs/sdk) | Python, JS/TS | 使用 SDK 进行手动仪表化,实现全面灵活性。 |
| [OpenAI](https://langfuse.com/docs/integrations/openai) | Python, JS/TS | 通过直接替换 OpenAI SDK 实现自动仪表化。 |
| [Langchain](https://langfuse.com/docs/integrations/langchain) | Python, JS/TS | 通过传入回调处理器至 Langchain 应用实现自动仪表化。 |
| [LlamaIndex](https://langfuse.com/docs/integrations/llama-index/get-started) | Python | 通过 LlamaIndex 回调系统实现自动仪表化。 |
| [Haystack](https://langfuse.com/docs/integrations/haystack) | Python | 通过 Haystack 内容追踪系统实现自动仪表化。 |
| [LiteLLM](https://langfuse.com/docs/integrations/litellm) | Python, JS/TS (仅代理) | 允许使用任何 LLM 替代 GPT。支持 Azure、OpenAI、Cohere、Anthropic、Ollama、VLLM、Sagemaker、HuggingFace、Replicate100+ LLMs)。 |
| [Vercel AI SDK](https://langfuse.com/docs/integrations/vercel-ai-sdk) | JS/TS | 基于 TypeScript 的工具包,帮助开发者使用 React、Next.js、Vue、Svelte 和 Node.js 构建 AI 驱动的应用。 |
| [API](https://langfuse.com/docs/api) | | 直接调用公共 API。提供 OpenAPI 规格。 |
### 与 Langfuse 集成的软件包:
| 名称 | 类型 | 描述 |
| ---------------------------------------------------------------------- | ------------------- | -------------------------------------------------------------------------------------------------------- |
| [Instructor](https://langfuse.com/docs/integrations/instructor) | 库 | 用于获取结构化 LLM 输出(JSON、Pydantic)的库。 |
| [DSPy](https://langfuse.com/docs/integrations/dspy) | 库 | 一个系统性优化语言模型提示和权重的框架。 |
| [Mirascope](https://langfuse.com/docs/integrations/mirascope) | 库 | 构建 LLM 应用的 Python 工具包。 |
| [Ollama](https://langfuse.com/docs/integrations/ollama) | 模型(本地) | 在你的机器上轻松运行开源 LLM。 |
| [Amazon Bedrock](https://langfuse.com/docs/integrations/amazon-bedrock) | 模型 | 在 AWS 上运行基础模型和微调模型。 |
| [AutoGen](https://langfuse.com/docs/integrations/autogen) | 代理框架 | 用于构建分布式代理的开源 LLM 平台。 |
| [Flowise](https://langfuse.com/docs/integrations/flowise) | 聊天/代理界面 | 基于 JS/TS 的无代码构建器,用于定制化 LLM 流程。 |
| [Langflow](https://langfuse.com/docs/integrations/langflow) | 聊天/代理界面 | 基于 Python 的 LangChain 用户界面,采用 react-flow 设计,提供便捷的实验与原型构建体验。 |
| [Dify](https://langfuse.com/docs/integrations/dify) | 聊天/代理界面 | 带有无代码构建器的开源 LLM 应用开发平台。 |
| [OpenWebUI](https://langfuse.com/docs/integrations/openwebui) | 聊天/代理界面 | 自托管的 LLM 聊天网页界面,支持包括自托管和本地模型在内的多种 LLM 运行器。 |
| [Promptfoo](https://langfuse.com/docs/integrations/promptfoo) | 工具 | 开源 LLM 测试平台。 |
| [LobeChat](https://langfuse.com/docs/integrations/lobechat) | 聊天/代理界面 | 开源聊天机器人平台。 |
| [Vapi](https://langfuse.com/docs/integrations/vapi) | 平台 | 开源语音 AI 平台。 |
| [Inferable](https://langfuse.com/docs/integrations/other/inferable) | 代理 | 构建分布式代理的开源 LLM 平台。 |
| [Gradio](https://langfuse.com/docs/integrations/other/gradio) | 聊天/代理界面 | 开源 Python 库,可用于构建类似聊天 UI 的网页界面。 |
| [Goose](https://langfuse.com/docs/integrations/goose) | 代理 | 构建分布式代理的开源 LLM 平台。 |
| [smolagents](https://langfuse.com/docs/integrations/smolagents) | 代理 | 开源 AI 代理框架。 |
| [CrewAI](https://langfuse.com/docs/integrations/crewai) | 代理 | 多代理框架,用于实现代理之间的协作与工具调用。 |
## 🚀 快速入门
为你的应用增加仪表代码,并开始将追踪数据上传到 Langfuse,从而记录 LLM 调用及应用中其他相关逻辑(如检索、嵌入或代理操作)。
### 1️⃣ 创建新项目
1. [创建 Langfuse 账户](https://cloud.langfuse.com/auth/sign-up) 或 [自托管](https://langfuse.com/self-hosting)
2. 创建一个新项目
3. 在项目设置中创建新的 API 凭证
### 2️⃣ 记录你的第一个 LLM 调用
使用 [<code>@observe()</code> 装饰器](https://langfuse.com/docs/sdk/python/decorators) 可轻松跟踪任何 Python LLM 应用。在本快速入门中,我们还使用了 Langfuse 的 [OpenAI 集成](https://langfuse.com/docs/integrations/openai) 来自动捕获所有模型参数。
> [!提示]
> 不使用 OpenAI?请访问 [我们的文档](https://langfuse.com/docs/get-started#log-your-first-llm-call-to-langfuse) 了解如何记录其他模型和框架。
安装依赖:
````bash
pip install langfuse openai
````
配置环境变量(创建名为 **.env** 的文件):
````bash:.env
LANGFUSE_SECRET_KEY="sk-lf-..."
LANGFUSE_PUBLIC_KEY="pk-lf-..."
LANGFUSE_HOST="https://cloud.langfuse.com" # 🇪🇺 欧盟区域
# LANGFUSE_HOST="https://us.cloud.langfuse.com" # 🇺🇸 美洲区域
````
创建示例代码(文件名:**main.py**):
````python:main.py
from langfuse.decorators import observe
from langfuse.openai import openai # OpenAI 集成
@observe()
def story():
return openai.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "What is Langfuse?"}],
).choices[0].message.content
@observe()
def main():
return story()
main()
````
### 3️⃣ 在 Langfuse 中查看追踪记录
在 Langfuse 中查看你的语言模型调用及其他应用逻辑。
![示例追踪记录](https://langfuse.com/images/docs/github-readme/github-example-trace.png)
_[Langfuse 中的公共示例追踪](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/2cec01e3-3dc2-472f-afcf-3b968cf0c1f4?timestamp=2025-02-10T14%3A27%3A30.275Z&observation=cb5ff844-07ef-41e6-b8e2-6c64344bc13b)_
> [!提示]
>
> [了解更多](https://langfuse.com/docs/tracing) 关于 Langfuse 中的追踪,或试试 [互动演示](https://langfuse.com/docs/demo)。
## ⭐️ 给我们加星
![为 Langfuse 加星](https://langfuse.com/images/docs/github-readme/github-star-howto.gif)
## 💭 支持
查找问题答案:
- 我们的 [文档](https://langfuse.com/docs) 是查找答案的最佳起点。内容全面,我们投入大量时间进行维护。你也可以通过 GitHub 提出文档修改建议。
- [Langfuse 常见问题](https://langfuse.com/faq) 解答了最常见的问题。
- 使用 “[Ask AI](https://langfuse.com/docs/ask-ai)” 立即获取问题答案。
支持渠道:
- **在 GitHub Discussions 的 [公共问答](https://github.com/orgs/langfuse/discussions/categories/support) 中提出任何问题。** 请尽量提供详细信息(如代码片段、截图、背景信息)以帮助我们理解你的问题。
- 在 GitHub Discussions 中 [提出功能请求](https://github.com/orgs/langfuse/discussions/categories/ideas)。
- 在 GitHub Issues 中 [报告 Bug](https://github.com/langfuse/langfuse/issues)。
- 对于时效性较强的问题,请通过应用内聊天小部件联系我们。
## 🤝 贡献
欢迎你的贡献!
- 在 GitHub Discussions 中为 [想法](https://github.com/orgs/langfuse/discussions/categories/ideas)投票。
- 提出并评论 [问题](https://github.com/langfuse/langfuse/issues)。
- 提交 PR —— 详情请参见 [CONTRIBUTING.md](CONTRIBUTING.md),了解如何搭建开发环境。
## 🥇 许可证
除 `ee` 文件夹外,本仓库采用 MIT 许可证。详情请参见 [LICENSE](LICENSE) 以及 [文档](https://langfuse.com/docs/open-source)。
## ⭐️ 星标历史
<a href="https://star-history.com/#langfuse/langfuse&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=langfuse/langfuse&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=langfuse/langfuse&type=Date" />
<img alt="星标历史图表" src="https://api.star-history.com/svg?repos=langfuse/langfuse&type=Date" style="border-radius: 15px;" />
</picture>
</a>
## ❤️ 使用 Langfuse 的开源项目
以下是使用 Langfuse 的顶级开源 Python 项目,按星标数排名([来源](https://github.com/langfuse/langfuse-docs/blob/main/components-mdx/dependents)):
| 仓库 | 星数 |
| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----: |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/127165244?s=40&v=4" width="20" height="20" alt=""> &nbsp; [langgenius](https://github.com/langgenius) / [dify](https://github.com/langgenius/dify) | 54865 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/158137808?s=40&v=4" width="20" height="20" alt=""> &nbsp; [open-webui](https://github.com/open-webui) / [open-webui](https://github.com/open-webui/open-webui) | 51531 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/131470832?s=40&v=4" width="20" height="20" alt=""> &nbsp; [lobehub](https://github.com/lobehub) / [lobe-chat](https://github.com/lobehub/lobe-chat) | 49003 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/85702467?s=40&v=4" width="20" height="20" alt=""> &nbsp; [langflow-ai](https://github.com/langflow-ai) / [langflow](https://github.com/langflow-ai/langflow) | 39093 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/130722866?s=40&v=4" width="20" height="20" alt=""> &nbsp; [run-llama](https://github.com/run-llama) / [llama_index](https://github.com/run-llama/llama_index) | 37368 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/139558948?s=40&v=4" width="20" height="20" alt=""> &nbsp; [chatchat-space](https://github.com/chatchat-space) / [Langchain-Chatchat](https://github.com/chatchat-space/Langchain-Chatchat) | 32486 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/128289781?s=40&v=4" width="20" height="20" alt=""> &nbsp; [FlowiseAI](https://github.com/FlowiseAI) / [Flowise](https://github.com/FlowiseAI/Flowise) | 32448 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/31035808?s=40&v=4" width="20" height="20" alt=""> &nbsp; [mindsdb](https://github.com/mindsdb) / [mindsdb](https://github.com/mindsdb/mindsdb) | 26931 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/119600397?s=40&v=4" width="20" height="20" alt=""> &nbsp; [twentyhq](https://github.com/twentyhq) / [twenty](https://github.com/twentyhq/twenty) | 24195 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/60330232?s=40&v=4" width="20" height="20" alt=""> &nbsp; [PostHog](https://github.com/PostHog) / [posthog](https://github.com/PostHog/posthog) | 22618 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/121462774?s=40&v=4" width="20" height="20" alt=""> &nbsp; [BerriAI](https://github.com/BerriAI) / [litellm](https://github.com/BerriAI/litellm) | 15151 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/179202840?s=40&v=4" width="20" height="20" alt=""> &nbsp; [mediar-ai](https://github.com/mediar-ai) / [screenpipe](https://github.com/mediar-ai/screenpipe) | 11037 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/105877416?s=40&v=4" width="20" height="20" alt=""> &nbsp; [formbricks](https://github.com/formbricks) / [formbricks](https://github.com/formbricks/formbricks) | 9386 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/76263028?s=40&v=4" width="20" height="20" alt=""> &nbsp; [anthropics](https://github.com/anthropics) / [courses](https://github.com/anthropics/courses) | 8385 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/78410652?s=40&v=4" width="20" height="20" alt=""> &nbsp; [GreyDGL](https://github.com/GreyDGL) / [PentestGPT](https://github.com/GreyDGL/PentestGPT) | 7374 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/152537519?s=40&v=4" width="20" height="20" alt=""> &nbsp; [superagent-ai](https://github.com/superagent-ai) / [superagent](https://github.com/superagent-ai/superagent) | 5391 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/137907881?s=40&v=4" width="20" height="20" alt=""> &nbsp; [promptfoo](https://github.com/promptfoo) / [promptfoo](https://github.com/promptfoo/promptfoo) | 4976 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/157326433?s=40&v=4" width="20" height="20" alt=""> &nbsp; [onlook-dev](https://github.com/onlook-dev) / [onlook](https://github.com/onlook-dev/onlook) | 4141 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/7250217?s=40&v=4" width="20" height="20" alt=""> &nbsp; [Canner](https://github.com/Canner) / [WrenAI](https://github.com/Canner/WrenAI) | 2526 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/11855343?s=40&v=4" width="20" height="20" alt=""> &nbsp; [pingcap](https://github.com/pingcap) / [autoflow](https://github.com/pingcap/autoflow) | 2061 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/85268109?s=40&v=4" width="20" height="20" alt=""> &nbsp; [MLSysOps](https://github.com/MLSysOps) / [MLE-agent](https://github.com/MLSysOps/MLE-agent) | 1161 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/158137808?s=40&v=4" width="20" height="20" alt=""> &nbsp; [open-webui](https://github.com/open-webui) / [pipelines](https://github.com/open-webui/pipelines) | 1100 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/18422723?s=40&v=4" width="20" height="20" alt=""> &nbsp; [alishobeiri](https://github.com/alishobeiri) / [thread](https://github.com/alishobeiri/thread) | 1074 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/125468716?s=40&v=4" width="20" height="20" alt=""> &nbsp; [topoteretes](https://github.com/topoteretes) / [cognee](https://github.com/topoteretes/cognee) | 971 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/188657705?s=40&v=4" width="20" height="20" alt=""> &nbsp; [bRAGAI](https://github.com/bRAGAI) / [bRAG-langchain](https://github.com/bRAGAI/bRAG-langchain) | 823 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/169500408?s=40&v=4" width="20" height="20" alt=""> &nbsp; [opslane](https://github.com/opslane) / [opslane](https://github.com/opslane/opslane) | 677 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/151867818?s=40&v=4" width="20" height="20" alt=""> &nbsp; [dynamiq-ai](https://github.com/dynamiq-ai) / [dynamiq](https://github.com/dynamiq-ai/dynamiq) | 639 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/48585267?s=40&v=4" width="20" height="20" alt=""> &nbsp; [theopenconversationkit](https://github.com/theopenconversationkit) / [tock](https://github.com/theopenconversationkit/tock) | 514 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/20493493?s=40&v=4" width="20" height="20" alt=""> &nbsp; [andysingal](https://github.com/andysingal) / [llm-course](https://github.com/andysingal/llm-course) | 394 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/132396805?s=40&v=4" width="20" height="20" alt=""> &nbsp; [phospho-app](https://github.com/phospho-app) / [phospho](https://github.com/phospho-app/phospho) | 384 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/178644984?s=40&v=4" width="20" height="20" alt=""> &nbsp; [sentient-engineering](https://github.com/sentient-engineering) / [agent-q](https://github.com/sentient-engineering/agent-q) | 370 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/168552753?s=40&v=4" width="20" height="20" alt=""> &nbsp; [sql-agi](https://github.com/sql-agi) / [DB-GPT](https://github.com/sql-agi/DB-GPT) | 324 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/60330232?s=40&v=4" width="20" height="20" alt=""> &nbsp; [PostHog](https://github.com/PostHog) / [posthog-foss](https://github.com/PostHog/posthog-foss) | 305 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/154247157?s=40&v=4" width="20" height="20" alt=""> &nbsp; [vespperhq](https://github.com/vespperhq) / [vespper](https://github.com/vespperhq/vespper) | 304 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/185116535?s=40&v=4" width="20" height="20" alt=""> &nbsp; [block](https://github.com/block) / [goose](https://github.com/block/goose) | 295 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/609489?s=40&v=4" width="20" height="20" alt=""> &nbsp; [aorwall](https://github.com/aorwall) / [moatless-tools](https://github.com/aorwall/moatless-tools) | 291 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/2357342?s=40&v=4" width="20" height="20" alt=""> &nbsp; [dmayboroda](https://github.com/dmayboroda) / [minima](https://github.com/dmayboroda/minima) | 221 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/66303003?s=40&v=4" width="20" height="20" alt=""> &nbsp; [RobotecAI](https://github.com/RobotecAI) / [rai](https://github.com/RobotecAI/rai) | 172 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/148684274?s=40&v=4" width="20" height="20" alt=""> &nbsp; [i-am-alice](https://github.com/i-am-alice) / [3rd-devs](https://github.com/i-am-alice/3rd-devs) | 148 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/171735272?s=40&v=4" width="20" height="20" alt=""> &nbsp; [8090-inc](https://github.com/8090-inc) / [xrx-sample-apps](https://github.com/8090-inc/xrx-sample-apps) | 138 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/104478511?s=40&v=4" width="20" height="20" alt=""> &nbsp; [babelcloud](https://github.com/babelcloud) / [LLM-RGB](https://github.com/babelcloud/LLM-RGB) | 135 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/15125613?s=40&v=4" width="20" height="20" alt=""> &nbsp; [souzatharsis](https://github.com/souzatharsis) / [tamingLLMs](https://github.com/souzatharsis/tamingLLMs) | 129 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/169401942?s=40&v=4" width="20" height="20" alt=""> &nbsp; [LibreChat-AI](https://github.com/LibreChat-AI) / [librechat.ai](https://github.com/LibreChat-AI/librechat.ai) | 128 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/51827949?s=40&v=4" width="20" height="20" alt=""> &nbsp; [deepset-ai](https://github.com/deepset-ai) / [haystack-core-integrations](https://github.com/deepset-ai/haystack-core-integrations) | 126 |
## 🔒 安全与隐私
我们非常重视数据安全和隐私。更多信息请参阅我们的 [安全与隐私](https://langfuse.com/security) 页面。
### 遥测
默认情况下,Langfuse 会自动将自托管实例的基础使用统计数据上传至集中服务器(PostHog)。
这有助于我们:
1. 了解 Langfuse 的使用情况,并改进最关键的功能。
2. 跟踪整体使用数据,以便内部及外部(例如筹款)报告。
所有数据均不会与第三方共享,也不包含任何敏感信息。我们对这一过程保持高度透明,你可以在 [此处](/web/src/features/telemetry/index.ts) 查看我们收集的具体数据。
你可以通过设置 `TELEMETRY_ENABLED=false` 来选择退出。
````
+361
View File
@@ -0,0 +1,361 @@
![Langfuse GitHub Banner](https://langfuse.com/images/docs/github-readme/github-banner.png)
<div align="center">
<div>
<h3>
<a href="https://langfuse.com/jp">
<strong>🇯🇵 🤝 🪢</strong>
</a> ·
<a href="https://cloud.langfuse.com">
<strong>Langfuse Cloud</strong>
</a> ·
<a href="https://langfuse.com/docs/deployment/self-host">
<strong>セルフホスティング</strong>
</a> ·
<a href="https://langfuse.com/demo">
<strong>デモ</strong>
</a>
</h3>
</div>
<div>
<a href="https://langfuse.com/docs"><strong>ドキュメント</strong></a> ·
<a href="https://langfuse.com/issues"><strong>バグ報告</strong></a> ·
<a href="https://langfuse.com/ideas"><strong>機能リクエスト</strong></a> ·
<a href="https://langfuse.com/changelog"><strong>変更履歴</strong></a> ·
<a href="https://langfuse.com/roadmap"><strong>ロードマップ</strong></a> ·
</div>
<br/>
<span>Langfuseは、サポートと機能リクエストのために <a href="https://github.com/orgs/langfuse/discussions"><strong>Github Discussions</strong></a> を利用しています。</span>
<br/>
<span><b>We're hiring.</b> <a href="https://langfuse.com/careers"><strong>チームに加わる</strong></a> (製品エンジニアリングおよびテクニカルGTMのポジション)への応募をお待ちしています。</span>
<br/>
<br/>
<div>
</div>
</div>
<p align="center">
<a href="https://github.com/langfuse/langfuse/blob/main/LICENSE">
<img src="https://img.shields.io/badge/License-MIT-E11311.svg" alt="MIT License">
</a>
<a href="https://www.ycombinator.com/companies/langfuse"><img src="https://img.shields.io/badge/Y%20Combinator-W23-orange" alt="Y Combinator W23"></a>
<a href="https://hub.docker.com/u/langfuse" target="_blank">
<img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/langfuse/langfuse?labelColor=%20%23FDB062&logo=Docker&labelColor=%20%23528bff"></a>
<a href="https://pypi.python.org/pypi/langfuse"><img src="https://img.shields.io/pypi/dm/langfuse?logo=python&logoColor=white&label=pypi%20langfuse&color=blue" alt="langfuse Python package on PyPi"></a>
<a href="https://www.npmjs.com/package/langfuse"><img src="https://img.shields.io/npm/dm/langfuse?logo=npm&logoColor=white&label=npm%20langfuse&color=blue" alt="langfuse npm package"></a>
<br/>
<a href="https://discord.com/invite/7NXusRtqYU" target="_blank">
<img src="https://img.shields.io/discord/1111061815649124414?logo=discord&labelColor=%20%235462eb&logoColor=%20%23f5f5f5&color=%20%235462eb"
alt="chat on Discord"></a>
<a href="https://twitter.com/intent/follow?screen_name=langfuse" target="_blank">
<img src="https://img.shields.io/twitter/follow/langfuse?logo=X&color=%20%23f5f5f5"
alt="follow on X(Twitter)"></a>
<a href="https://www.linkedin.com/company/langfuse/" target="_blank">
<img src="https://custom-icon-badges.demolab.com/badge/LinkedIn-0A66C2?logo=linkedin-white&logoColor=fff"
alt="follow on LinkedIn"></a>
<a href="https://github.com/langfuse/langfuse/graphs/commit-activity" target="_blank">
<img alt="Commits last month" src="https://img.shields.io/github/commit-activity/m/langfuse/langfuse?labelColor=%20%2332b583&color=%20%2312b76a"></a>
<a href="https://github.com/langfuse/langfuse/" target="_blank">
<img alt="Issues closed" src="https://img.shields.io/github/issues-search?query=repo%3Alangfuse%2Flangfuse%20is%3Aclosed&label=issues%20closed&labelColor=%20%237d89b0&color=%20%235d6b98"></a>
<a href="https://github.com/langfuse/langfuse/discussions/" target="_blank">
<img alt="Discussion posts" src="https://img.shields.io/github/discussions/langfuse/langfuse?labelColor=%20%239b8afb&color=%20%237a5af8"></a>
</p>
<p align="center">
<a href="./README.md"><img alt="README in English" src="https://img.shields.io/badge/English-d9d9d9"></a>
<a href="./README.cn.md"><img alt="简体中文版自述文件" src="https://img.shields.io/badge/简体中文-d9d9d9"></a>
<a href="./README.ja.md"><img alt="日本語のREADME" src="https://img.shields.io/badge/日本語-d9d9d9"></a>
<a href="./README.kr.md"><img alt="README in Korean" src="https://img.shields.io/badge/한국어-d9d9d9"></a>
</p>
Langfuseは**オープンソースのLLMエンジニアリング**プラットフォームです。
チームが共同でAIアプリケーションを**開発、監視、評価**、および**デバッグ**するのを支援します。
Langfuseは**数分でセルフホスト可能**で、**多くの実績を持つ**システムです。
[![Langfuse Overview Video](https://github.com/user-attachments/assets/3926b288-ff61-4b95-8aa1-45d041c70866)](https://langfuse.com/watch-demo)
## ✨ コア機能
![Langfuse Overview](https://langfuse.com/images/docs/github-readme/github-feature-overview.png)
- **[LLMアプリケーションの可観測性](https://langfuse.com/docs/tracing):**
アプリケーションにインストゥルメンテーションを導入し、Langfuseへトレースを取り込むことで、LLM呼び出しやリトリーバル、埋め込み、エージェントアクションなどの関連ロジックを追跡できます。
複雑なログやユーザーセッションを解析・デバッグできます。
インタラクティブな[デモ](https://langfuse.com/docs/demo)で動作を確認してください。
- **[プロンプト管理](https://langfuse.com/docs/prompts/get-started):**
プロンプトを一元管理し、バージョン管理しながら共同で改善を行えます。
サーバーおよびクライアント側で強力なキャッシングを行うため、アプリケーションのレイテンシを増やすことなくプロンプトの改良が可能です。
- **[評価](https://langfuse.com/docs/scores/overview):**
評価はLLMアプリケーション開発ワークフローの要であり、Langfuseは多様なニーズに対応します。
LLMを判定者として用いる方法、ユーザーフィードバックの収集、手動によるラベリング、API/SDKを通じたカスタム評価パイプラインをサポートします。
- **[データセット](https://langfuse.com/docs/datasets/overview):**
LLMアプリケーション評価用のテストセットやベンチマークを構築できます。
継続的な改善、事前デプロイテスト、構造化された実験、柔軟な評価、さらにLangChainやLlamaIndexなどとのシームレスな統合をサポートします。
- **[LLMプレイグラウンド](https://langfuse.com/docs/playground):**
プロンプトやモデル設定のテスト・反復作業を支援するツールで、フィードバックループを短縮し開発を加速します。
トレースで不具合が見つかった場合、直接プレイグラウンドへ飛び、迅速に改善できます。
- **[包括的なAPI](https://langfuse.com/docs/api):**
LangfuseはAPIを通じて提供されるビルディングブロックを用い、カスタムLLMOpsワークフローの基盤として頻繁に利用されます。
OpenAPI仕様、Postmanコレクション、PythonやJS/TS向けの型付きSDKが利用可能です。
## 📦 Langfuseのデプロイ
![Langfuse Deployment Options](https://langfuse.com/images/docs/github-readme/github-deployment-options.png)
### Langfuse Cloud
Langfuseチームによるマネージドデプロイメント。充実した無料プラン(ホビープラン)で、クレジットカード不要です。
<div align="center">
<a href="https://cloud.langfuse.com" target="_blank">
<img alt="Static Badge" src="https://img.shields.io/badge/»%20Sign%20up%20for%20Langfuse%20Cloud-8A2BE2?&color=orange">
</a>
</div>
### セルフホスティング Langfuse
自身のインフラ上でLangfuseを実行できます:
- **[Local (docker compose)](https://langfuse.com/self-hosting/local):**
Docker Composeを使用して、たった5分で自分のマシン上でLangfuseを実行できます.
```bash
# 最新のLangfuseリポジトリのコピーを取得
git clone https://github.com/langfuse/langfuse.git
cd langfuse
# Langfuseのdocker composeを起動
docker compose up
```
- **[Kubernetes (Helm)](https://langfuse.com/self-hosting/kubernetes-helm):**
Helmを使用してKubernetesクラスター上でLangfuseを実行します。
こちらが推奨される本番環境でのデプロイ方法です。
- **[VM](https://langfuse.com/self-hosting/docker-compose):**
Docker Composeを使用して、単一の仮想マシン上でLangfuseを実行します。
- **Planned:**
クラウド固有のデプロイガイドは計画中です。以下のスレッドに対して投票やコメントをお願いします:
[AWS](https://github.com/orgs/langfuse/discussions/4645), [Google Cloud](https://github.com/orgs/langfuse/discussions/4646), [Azure](https://github.com/orgs/langfuse/discussions/4647).
[セルフホスティングのドキュメント](https://langfuse.com/self-hosting)を参照し、アーキテクチャや設定オプションの詳細をご確認ください。
## 🔌 インテグレーション
![Langfuse Integrations](https://langfuse.com/images/docs/github-readme/github-integrations.png)
### 主なインテグレーション:
| インテグレーション | 対応言語・環境 | 説明 |
| ----------------------------------------------------------------------------------- | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| [SDK](https://langfuse.com/docs/sdk) | Python, JS/TS | SDKを利用して手動でインストゥルメンテーションを実装し、完全な柔軟性を提供します。 |
| [OpenAI](https://langfuse.com/docs/integrations/openai) | Python, JS/TS | OpenAI SDKのドロップイン置換による自動インストゥルメンテーションを実現します。 |
| [Langchain](https://langfuse.com/docs/integrations/langchain) | Python, JS/TS | Langchainアプリケーションにコールバックハンドラーを渡すことで自動的に計測します。 |
| [LlamaIndex](https://langfuse.com/docs/integrations/llama-index/get-started) | Python | LlamaIndexのコールバックシステムを介して自動的にインストゥルメントします。 |
| [Haystack](https://langfuse.com/docs/integrations/haystack) | Python | Haystackのコンテンツトレースシステムを利用した自動インストゥルメンテーションを実現します。 |
| [LiteLLM](https://langfuse.com/docs/integrations/litellm) | Python, JS/TS (proxy only)| GPTのドロップイン置換として任意のLLMを使用できます。Azure、OpenAI、Cohere、Anthropic、Ollama、VLLM、Sagemaker、HuggingFace、Replicate100+ LLM)に対応。 |
| [Vercel AI SDK](https://langfuse.com/docs/integrations/vercel-ai-sdk) | JS/TS | React、Next.js、Vue、Svelte、Node.jsを使用してAI搭載アプリケーションの構築を支援するTypeScriptツールキットです。 |
| [API](https://langfuse.com/docs/api) | | 公開APIを直接呼び出すことが可能です。OpenAPI仕様も利用できます。 |
### Langfuseと統合されているパッケージ:
| 名前 | タイプ | 説明 |
| ------------------------------------------------------------------------- | ------------------ | --------------------------------------------------------------------------------------------------------- |
| [Instructor](https://langfuse.com/docs/integrations/instructor) | ライブラリ | 構造化されたLLM出力(JSON、Pydantic)を取得するためのライブラリ |
| [DSPy](https://langfuse.com/docs/integrations/dspy) | ライブラリ | LLMプロンプトや重み付けを体系的に最適化するためのフレームワーク |
| [Mirascope](https://langfuse.com/docs/integrations/mirascope) | ライブラリ | LLMアプリケーション構築用のPythonツールキット |
| [Ollama](https://langfuse.com/docs/integrations/ollama) | モデル(ローカル) | オープンソースLLMを手軽にローカルで実行するためのツール |
| [Amazon Bedrock](https://langfuse.com/docs/integrations/amazon-bedrock) | モデル | AWS上でファウンデーションモデルやファインチューニング済みモデルを実行 |
| [Google VertexAI and Gemini](https://langfuse.com/docs/integrations/google-vertex-ai) | モデル | Google上でファウンデーションモデルやファインチューニング済みモデルを実行 |
| [AutoGen](https://langfuse.com/docs/integrations/autogen) | エージェントフレームワーク | 分散型エージェント構築のためのオープンソースLLMプラットフォーム |
| [Flowise](https://langfuse.com/docs/integrations/flowise) | チャット/エージェント UI | JS/TSのノーコードビルダーで、カスタマイズ可能なLLMフローを構築 |
| [Langflow](https://langfuse.com/docs/integrations/langflow) | チャット/エージェント UI | PythonベースのUIで、react-flowを用いてLangChainの実験やプロトタイピングを容易に実現 |
| [Dify](https://langfuse.com/docs/integrations/dify) | チャット/エージェント UI | ノーコードでLLMアプリ開発が可能なオープンソースプラットフォーム |
| [OpenWebUI](https://langfuse.com/docs/integrations/openwebui) | チャット/エージェント UI | 自前ホストおよびローカルモデルに対応するLLMチャットWeb UI |
| [Promptfoo](https://langfuse.com/docs/integrations/promptfoo) | ツール | オープンソースのLLMテストプラットフォーム |
| [LobeChat](https://langfuse.com/docs/integrations/lobechat) | チャット/エージェント UI | オープンソースのチャットボットプラットフォーム |
| [Vapi](https://langfuse.com/docs/integrations/vapi) | プラットフォーム | オープンソースの音声AIプラットフォーム |
| [Inferable](https://langfuse.com/docs/integrations/other/inferable) | エージェント | 分散型エージェント構築のためのオープンソースLLMプラットフォーム |
| [Gradio](https://langfuse.com/docs/integrations/other/gradio) | チャット/エージェント UI | チャットUIなどのWebインターフェース構築のためのオープンソースPythonライブラリ |
| [Goose](https://langfuse.com/docs/integrations/goose) | エージェント | 分散型エージェント構築のためのオープンソースLLMプラットフォーム |
| [smolagents](https://langfuse.com/docs/integrations/smolagents) | エージェント | オープンソースのAIエージェントフレームワーク |
| [CrewAI](https://langfuse.com/docs/integrations/crewai) | エージェント | エージェントの協調とツール利用を実現するマルチエージェントフレームワーク |
## 🚀 クイックスタート
アプリケーションにインストゥルメンテーションを導入し、LLM呼び出しやリトリーバル、埋め込み、エージェントアクションなどの動作をLangfuseに記録しましょう。
複雑なログやユーザーセッションの解析・デバッグが可能になります。
### 1️⃣ 新規プロジェクトの作成
1. [Langfuseアカウント作成](https://cloud.langfuse.com/auth/sign-up) または [セルフホスト](https://langfuse.com/self-hosting)
2. 新規プロジェクトを作成
3. プロジェクト設定で新しいAPIクレデンシャルを作成
### 2️⃣ 初めてのLLM呼び出しのログ記録
[`@observe()` デコレーター](https://langfuse.com/docs/sdk/python/decorators)を利用することで、任意のPython製LLMアプリケーションのトレースが簡単に行えます。
このクイックスタートでは、Langfuseの[OpenAI統合](https://langfuse.com/docs/integrations/openai)を使用して、全てのモデルパラメータを自動で取得します。
> [!TIP]
> OpenAIを利用していない場合は、[こちらのドキュメント](https://langfuse.com/docs/get-started#log-your-first-llm-call-to-langfuse)で、他のモデルやフレームワークのログ記録方法をご確認ください。
```bash
pip install langfuse openai
```
```bash filename=".env"
LANGFUSE_SECRET_KEY="sk-lf-..."
LANGFUSE_PUBLIC_KEY="pk-lf-..."
LANGFUSE_HOST="https://cloud.langfuse.com" # 🇪🇺 EUリージョン
# LANGFUSE_HOST="https://us.cloud.langfuse.com" # 🇺🇸 USリージョン
```
```python:/@observe()/ /from langfuse.openai import openai/ filename="main.py"
from langfuse.decorators import observe
from langfuse.openai import openai # OpenAI統合
@observe()
def story():
return openai.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "What is Langfuse?"}],
).choices[0].message.content
@observe()
def main():
return story()
main()
```
### 3️⃣ Langfuseでトレースを確認する
Langfuse上で、LLM呼び出しおよびその他のアプリケーションロジックのトレースを確認できます。
![Example trace in Langfuse](https://langfuse.com/images/docs/github-readme/github-example-trace.png)
_[Langfuseの公開トレース例](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/2cec01e3-3dc2-472f-afcf-3b968cf0c1f4?timestamp=2025-02-10T14%3A27%3A30.275Z&observation=cb5ff844-07ef-41e6-b8e2-6c64344bc13b)_
> [!TIP]
>
> Langfuseでのトレースの詳細については、[こちら](https://langfuse.com/docs/tracing)をご参照いただくか、[インタラクティブデモ](https://langfuse.com/docs/demo)でお試しください。
## ⭐️ Star Langfuse
![Star Langfuse](https://langfuse.com/images/docs/github-readme/github-star-howto.gif)
## 💭 サポート
質問の回答をお探しの場合は:
- 当社の[ドキュメント](https://langfuse.com/docs)は、回答を探すための最良の出発点です。内容が充実しており、継続的なメンテナンスに努めています。GitHubを通じてドキュメントへの修正提案も可能です。
- よくある質問は[Langfuse FAQ](https://langfuse.com/faq)にまとめられています。
- [Ask AI](https://langfuse.com/docs/ask-ai)を利用すれば、質問に対して即座に回答を得ることができます。
- 日本語のサポートや決済, 請求書払いなどをお求めの場合は、日本のリセラー (https://gao-ai.com) にご相談ください。
サポートチャネル:
- **GitHub Discussionsの[パブリックQ&A](https://github.com/orgs/langfuse/discussions/categories/support)で質問してください。**
質問には、コードスニペット、スクリーンショット、背景情報など、できるだけ詳細な情報を含めるとスムーズな対応が可能です。
- GitHub Discussionsで[機能リクエスト](https://github.com/orgs/langfuse/discussions/categories/ideas)を投稿してください。
- GitHub Issuesにて[バグ報告](https://github.com/langfuse/langfuse/issues)を行ってください。
- 緊急の問い合わせの場合は、アプリ内チャットウィジェットでご連絡ください。
## 🤝 貢献
皆様からの貢献を歓迎します!
- GitHub Discussionsの[アイデア](https://github.com/orgs/langfuse/discussions/categories/ideas)に投票してください。
- [Issues](https://github.com/langfuse/langfuse/issues)を作成・コメントしてください。
- プルリクエストを送信してください。開発環境のセットアップ方法については[CONTRIBUTING.md](CONTRIBUTING.md)をご参照ください。
## 🥇 ライセンス
このリポジトリは、`ee`フォルダを除き、MITライセンスの下で公開されています。
詳細は[LICENSE](LICENSE)および[オープンソースに関するドキュメント](https://langfuse.com/docs/open-source)をご確認ください。
## ⭐️ スターの履歴
<a href="https://star-history.com/#langfuse/langfuse&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=langfuse/langfuse&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=langfuse/langfuse&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=langfuse/langfuse&type=Date" style="border-radius: 15px;" />
</picture>
</a>
## ❤️ Langfuseを利用しているオープンソースプロジェクト
Langfuseを利用している主要なオープンソースPythonプロジェクト(スター数順): ([出典](https://github.com/langfuse/langfuse-docs/blob/main/components-mdx/dependents))
| リポジトリ | スター |
| :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----: |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/127165244?s=40&v=4" width="20" height="20" alt=""> &nbsp; [langgenius](https://github.com/langgenius) / [dify](https://github.com/langgenius/dify) | 54865 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/158137808?s=40&v=4" width="20" height="20" alt=""> &nbsp; [open-webui](https://github.com/open-webui) / [open-webui](https://github.com/open-webui/open-webui) | 51531 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/131470832?s=40&v=4" width="20" height="20" alt=""> &nbsp; [lobehub](https://github.com/lobehub) / [lobe-chat](https://github.com/lobehub/lobe-chat) | 49003 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/85702467?s=40&v=4" width="20" height="20" alt=""> &nbsp; [langflow-ai](https://github.com/langflow-ai) / [langflow](https://github.com/langflow-ai/langflow) | 39093 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/130722866?s=40&v=4" width="20" height="20" alt=""> &nbsp; [run-llama](https://github.com/run-llama) / [llama_index](https://github.com/run-llama/llama_index) | 37368 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/139558948?s=40&v=4" width="20" height="20" alt=""> &nbsp; [chatchat-space](https://github.com/chatchat-space) / [Langchain-Chatchat](https://github.com/chatchat-space/Langchain-Chatchat) | 32486 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/128289781?s=40&v=4" width="20" height="20" alt=""> &nbsp; [FlowiseAI](https://github.com/FlowiseAI) / [Flowise](https://github.com/FlowiseAI/Flowise) | 32448 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/31035808?s=40&v=4" width="20" height="20" alt=""> &nbsp; [mindsdb](https://github.com/mindsdb) / [mindsdb](https://github.com/mindsdb/mindsdb) | 26931 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/119600397?s=40&v=4" width="20" height="20" alt=""> &nbsp; [twentyhq](https://github.com/twentyhq) / [twenty](https://github.com/twentyhq/twenty) | 24195 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/60330232?s=40&v=4" width="20" height="20" alt=""> &nbsp; [PostHog](https://github.com/PostHog) / [posthog](https://github.com/PostHog/posthog) | 22618 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/121462774?s=40&v=4" width="20" height="20" alt=""> &nbsp; [BerriAI](https://github.com/BerriAI) / [litellm](https://github.com/BerriAI/litellm) | 15151 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/179202840?s=40&v=4" width="20" height="20" alt=""> &nbsp; [mediar-ai](https://github.com/mediar-ai) / [screenpipe](https://github.com/mediar-ai/screenpipe) | 11037 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/105877416?s=40&v=4" width="20" height="20" alt=""> &nbsp; [formbricks](https://github.com/formbricks) / [formbricks](https://github.com/formbricks/formbricks) | 9386 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/76263028?s=40&v=4" width="20" height="20" alt=""> &nbsp; [anthropics](https://github.com/anthropics) / [courses](https://github.com/anthropics/courses) | 8385 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/78410652?s=40&v=4" width="20" height="20" alt=""> &nbsp; [GreyDGL](https://github.com/GreyDGL) / [PentestGPT](https://github.com/GreyDGL/PentestGPT) | 7374 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/152537519?s=40&v=4" width="20" height="20" alt=""> &nbsp; [superagent-ai](https://github.com/superagent-ai) / [superagent](https://github.com/superagent-ai/superagent) | 5391 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/137907881?s=40&v=4" width="20" height="20" alt=""> &nbsp; [promptfoo](https://github.com/promptfoo) / [promptfoo](https://github.com/promptfoo/promptfoo) | 4976 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/157326433?s=40&v=4" width="20" height="20" alt=""> &nbsp; [onlook-dev](https://github.com/onlook-dev) / [onlook](https://github.com/onlook-dev/onlook) | 4141 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/7250217?s=40&v=4" width="20" height="20" alt=""> &nbsp; [Canner](https://github.com/Canner) / [WrenAI](https://github.com/Canner/WrenAI) | 2526 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/11855343?s=40&v=4" width="20" height="20" alt=""> &nbsp; [pingcap](https://github.com/pingcap) / [autoflow](https://github.com/pingcap/autoflow) | 2061 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/85268109?s=40&v=4" width="20" height="20" alt=""> &nbsp; [MLSysOps](https://github.com/MLSysOps) / [MLE-agent](https://github.com/MLSysOps/MLE-agent) | 1161 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/158137808?s=40&v=4" width="20" height="20" alt=""> &nbsp; [open-webui](https://github.com/open-webui) / [pipelines](https://github.com/open-webui/pipelines) | 1100 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/18422723?s=40&v=4" width="20" height="20" alt=""> &nbsp; [alishobeiri](https://github.com/alishobeiri) / [thread](https://github.com/alishobeiri/thread) | 1074 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/125468716?s=40&v=4" width="20" height="20" alt=""> &nbsp; [topoteretes](https://github.com/topoteretes) / [cognee](https://github.com/topoteretes/cognee) | 971 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/188657705?s=40&v=4" width="20" height="20" alt=""> &nbsp; [bRAGAI](https://github.com/bRAGAI) / [bRAG-langchain](https://github.com/bRAGAI/bRAG-langchain) | 823 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/169500408?s=40&v=4" width="20" height="20" alt=""> &nbsp; [opslane](https://github.com/opslane) / [opslane](https://github.com/opslane/opslane) | 677 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/151867818?s=40&v=4" width="20" height="20" alt=""> &nbsp; [dynamiq-ai](https://github.com/dynamiq-ai) / [dynamiq](https://github.com/dynamiq-ai/dynamiq) | 639 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/48585267?s=40&v=4" width="20" height="20" alt=""> &nbsp; [theopenconversationkit](https://github.com/theopenconversationkit) / [tock](https://github.com/theopenconversationkit/tock) | 514 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/20493493?s=40&v=4" width="20" height="20" alt=""> &nbsp; [andysingal](https://github.com/andysingal) / [llm-course](https://github.com/andysingal/llm-course) | 394 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/132396805?s=40&v=4" width="20" height="20" alt=""> &nbsp; [phospho-app](https://github.com/phospho-app) / [phospho](https://github.com/phospho-app/phospho) | 384 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/178644984?s=40&v=4" width="20" height="20" alt=""> &nbsp; [sentient-engineering](https://github.com/sentient-engineering) / [agent-q](https://github.com/sentient-engineering/agent-q) | 370 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/168552753?s=40&v=4" width="20" height="20" alt=""> &nbsp; [sql-agi](https://github.com/sql-agi) / [DB-GPT](https://github.com/sql-agi/DB-GPT) | 324 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/60330232?s=40&v=4" width="20" height="20" alt=""> &nbsp; [PostHog](https://github.com/PostHog) / [posthog-foss](https://github.com/PostHog/posthog-foss) | 305 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/154247157?s=40&v=4" width="20" height="20" alt=""> &nbsp; [vespperhq](https://github.com/vespperhq) / [vespper](https://github.com/vespperhq/vespper) | 304 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/185116535?s=40&v=4" width="20" height="20" alt=""> &nbsp; [block](https://github.com/block) / [goose](https://github.com/block/goose) | 295 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/609489?s=40&v=4" width="20" height="20" alt=""> &nbsp; [aorwall](https://github.com/aorwall) / [moatless-tools](https://github.com/aorwall/moatless-tools) | 291 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/2357342?s=40&v=4" width="20" height="20" alt=""> &nbsp; [dmayboroda](https://github.com/dmayboroda) / [minima](https://github.com/dmayboroda/minima) | 221 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/66303003?s=40&v=4" width="20" height="20" alt=""> &nbsp; [RobotecAI](https://github.com/RobotecAI) / [rai](https://github.com/RobotecAI/rai) | 172 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/148684274?s=40&v=4" width="20" height="20" alt=""> &nbsp; [i-am-alice](https://github.com/i-am-alice) / [3rd-devs](https://github.com/i-am-alice/3rd-devs) | 148 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/171735272?s=40&v=4" width="20" height="20" alt=""> &nbsp; [8090-inc](https://github.com/8090-inc) / [xrx-sample-apps](https://github.com/8090-inc/xrx-sample-apps) | 138 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/104478511?s=40&v=4" width="20" height="20" alt=""> &nbsp; [babelcloud](https://github.com/babelcloud) / [LLM-RGB](https://github.com/babelcloud/LLM-RGB) | 135 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/15125613?s=40&v=4" width="20" height="20" alt=""> &nbsp; [souzatharsis](https://github.com/souzatharsis) / [tamingLLMs](https://github.com/souzatharsis/tamingLLMs) | 129 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/169401942?s=40&v=4" width="20" height="20" alt=""> &nbsp; [LibreChat-AI](https://github.com/LibreChat-AI) / [librechat.ai](https://github.com/LibreChat-AI/librechat.ai) | 128 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/51827949?s=40&v=4" width="20" height="20" alt=""> &nbsp; [deepset-ai](https://github.com/deepset-ai) / [haystack-core-integrations](https://github.com/deepset-ai/haystack-core-integrations) | 126 |
## 🔒 セキュリティとプライバシー
データのセキュリティとプライバシーは非常に重要です。
詳細につきましては、[セキュリティとプライバシー](https://langfuse.com/security)ページをご参照ください。
### テレメトリー
デフォルトでは、Langfuseは以下の目的でセルフホストされたインスタンスの基本的な使用統計情報を中央サーバ(PostHog)へ自動的に報告します。
1. Langfuseの利用状況を把握し、最も重要な機能の改善に役立てる
2. 内部および外部(例:資金調達)のレポートのために全体の利用状況を追跡する
収集されたデータは第三者と共有されず、機微な情報は一切含まれていません。
当社はこの点について極力透明性を保っており、収集される具体的なデータの詳細は[こちら](/web/src/features/telemetry/index.ts)で確認できます。
`TELEMETRY_ENABLED=false` を設定することで、テレメトリーの報告をオプトアウトできます.
+339
View File
@@ -0,0 +1,339 @@
![Langfuse GitHub Banner](https://langfuse.com/images/docs/github-readme/github-banner.png)
<div align="center">
<div>
<h3>
<a href="https://langfuse.com/kr">
<strong>🇰🇷 🤝 🪢</strong>
</a> ·
<a href="https://cloud.langfuse.com">
<strong>Langfuse Cloud</strong>
</a> ·
<a href="https://langfuse.com/docs/deployment/self-host">
<strong>셀프 호스트</strong>
</a> ·
<a href="https://langfuse.com/demo">
<strong>데모</strong>
</a>
</h3>
</div>
<div>
<a href="https://langfuse.com/docs"><strong>문서</strong></a> ·
<a href="https://langfuse.com/issues"><strong>버그 신고</strong></a> ·
<a href="https://langfuse.com/ideas"><strong>기능 요청</strong></a> ·
<a href="https://langfuse.com/changelog"><strong>변경 내역</strong></a> ·
<a href="https://langfuse.com/roadmap"><strong>로드맵</strong></a> ·
</div>
<br/>
<span>Langfuse는 지원 및 기능 요청을 위해 <a href="https://github.com/orgs/langfuse/discussions"><strong>GitHub Discussions</strong></a>를 사용합니다.</span>
<br/>
<span><b>채용 중입니다.</b> <a href="https://langfuse.com/careers"><strong>함께 하세요</strong></a> 제품 엔지니어링 및 기술 go-to-market 역할의 인재를 찾고 있습니다.</span>
<br/>
<br/>
<div>
</div>
</div>
<p align="center">
<a href="https://github.com/langfuse/langfuse/blob/main/LICENSE">
<img src="https://img.shields.io/badge/License-MIT-E11311.svg" alt="MIT License">
</a>
<a href="https://www.ycombinator.com/companies/langfuse"><img src="https://img.shields.io/badge/Y%20Combinator-W23-orange" alt="Y Combinator W23"></a>
<a href="https://hub.docker.com/u/langfuse" target="_blank">
<img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/langfuse/langfuse?labelColor=%20%23FDB062&logo=Docker&labelColor=%20%23528bff"></a>
<a href="https://pypi.python.org/pypi/langfuse"><img src="https://img.shields.io/pypi/dm/langfuse?logo=python&logoColor=white&label=pypi%20langfuse&color=blue" alt="langfuse Python package on PyPi"></a>
<a href="https://www.npmjs.com/package/langfuse"><img src="https://img.shields.io/npm/dm/langfuse?logo=npm&logoColor=white&label=npm%20langfuse&color=blue" alt="langfuse npm package"></a>
<br/>
<a href="https://discord.com/invite/7NXusRtqYU" target="_blank">
<img src="https://img.shields.io/discord/1111061815649124414?logo=discord&labelColor=%20%235462eb&logoColor=%20%23f5f5f5&color=%20%235462eb"
alt="chat on Discord"></a>
<a href="https://twitter.com/intent/follow?screen_name=langfuse" target="_blank">
<img src="https://img.shields.io/twitter/follow/langfuse?logo=X&color=%20%23f5f5f5"
alt="follow on X(Twitter)"></a>
<a href="https://www.linkedin.com/company/langfuse/" target="_blank">
<img src="https://custom-icon-badges.demolab.com/badge/LinkedIn-0A66C2?logo=linkedin-white&logoColor=fff"
alt="follow on LinkedIn"></a>
<a href="https://github.com/langfuse/langfuse/graphs/commit-activity" target="_blank">
<img alt="Commits last month" src="https://img.shields.io/github/commit-activity/m/langfuse/langfuse?labelColor=%20%2332b583&color=%20%2312b76a"></a>
<a href="https://github.com/langfuse/langfuse/" target="_blank">
<img alt="Issues closed" src="https://img.shields.io/github/issues-search?query=repo%3Alangfuse%2Flangfuse%20is%3Aclosed&label=issues%20closed&labelColor=%20%237d89b0&color=%20%235d6b98"></a>
<a href="https://github.com/langfuse/langfuse/discussions/" target="_blank">
<img alt="Discussion posts" src="https://img.shields.io/github/discussions/langfuse/langfuse?labelColor=%20%239b8afb&color=%20%237a5af8"></a>
</p>
<p align="center">
<a href="./README.md"><img alt="README in English" src="https://img.shields.io/badge/English-d9d9d9"></a>
<a href="./README.cn.md"><img alt="简体中文版自述文件" src="https://img.shields.io/badge/简体中文-d9d9d9"></a>
<a href="./README.ja.md"><img alt="日本語のREADME" src="https://img.shields.io/badge/日本語-d9d9d9"></a>
<a href="./README.kr.md"><img alt="README in Korean" src="https://img.shields.io/badge/한국어-d9d9d9"></a>
</p>
Langfuse는 **오픈 소스 LLM 엔지니어링** 플랫폼입니다.
팀이 협업하여 AI 애플리케이션을 **개발, 모니터링, 평가** 및 **디버그**할 수 있도록 도와줍니다.
Langfuse는 몇 분 안에 셀프 호스팅할 수 있으며, 검증된(battle-tested) 솔루션입니다.
[![Langfuse Overview Video](https://github.com/user-attachments/assets/3926b288-ff61-4b95-8aa1-45d041c70866)](https://langfuse.com/watch-demo)
## ✨ 주요 기능
![Langfuse Overview](https://langfuse.com/images/docs/github-readme/github-feature-overview.png)
- **LLM 애플리케이션 관측**
앱에 계측(instrumentation)을 추가하여 Langfuse로 trace 데이터를 수집함으로써, 검색, 임베딩, 또는 에이전트 동작과 같은 LLM 호출 및 기타 관련 로직을 추적할 수 있습니다. 복잡한 로그와 사용자 세션을 확인 및 디버깅 해보세요. 인터랙티브 데모를 통해 실제 작동 예를 확인할 수 있습니다.
- **프롬프트 관리**
프롬프트를 중앙에서 관리하고 버전 관리하며 협업으로 수정할 수 있도록 도와줍니다. 서버와 클라이언트 측의 강력한 캐싱 덕분에 애플리케이션에 지연(latency)을 추가하지 않고도 프롬프트를 반복 개선할 수 있습니다.
- **평가**
LLM 애플리케이션 개발 워크플로우에서 핵심적인 역할을 하며, Langfuse는 여러분의 필요에 맞게 유연하게 대응합니다. LLM을 심사자로 활용하는 기능, 사용자 피드백 수집, 수동 라벨링 및 API/SDK를 통한 맞춤 평가 파이프라인을 지원합니다.
- **데이터셋**
LLM 애플리케이션 평가를 위한 테스트 세트와 벤치마크를 제공하여, 지속적인 개선, 배포 전 테스트, 구조화된 실험, 유연한 평가 및 LangChain과 LlamaIndex와 같은 프레임워크와의 원활한 통합을 지원합니다.
- **LLM 플레이그라운드**
프롬프트와 모델 구성에 대해 테스트 및 반복 개선할 수 있는 도구로, 피드백 루프를 단축하여 개발 속도를 높여줍니다. trace에서 이상한 결과가 발생하면 플레이그라운드로 바로 이동해 개선할 수 있습니다.
- **종합 API**
Langfuse는 API를 통해 제공되는 구성 요소들을 활용하여 맞춤형 LLMOps 워크플로우를 강화하는 데 자주 사용됩니다. OpenAPI 명세, Postman 컬렉션, Python 및 JS/TS용 타입드 SDK가 제공됩니다.
## 📦 Langfuse 배포
![Langfuse Deployment Options](https://langfuse.com/images/docs/github-readme/github-deployment-options.png)
### Langfuse Cloud
Langfuse 팀이 관리하는 배포 방식으로, 후한 무료 플랜(취미 플랜)을 제공하며 신용카드가 필요하지 않습니다.
<div align="center">
<a href="https://cloud.langfuse.com" target="_blank">
<img alt="Static Badge" src="https://img.shields.io/badge/»%20Sign%20up%20for%20Langfuse%20Cloud-8A2BE2?&color=orange">
</a>
</div>
### Langfuse 셀프 호스트
자체 인프라에서 Langfuse를 실행하세요:
- [로컬 (docker compose)](https://langfuse.com/self-hosting/local): Docker Compose를 사용하여 본인의 컴퓨터에서 5분 안에 Langfuse를 실행할 수 있습니다.
```bash
# 최신 Langfuse 저장소 클론
git clone https://github.com/langfuse/langfuse.git
cd langfuse
# langfuse docker compose 실행
docker compose up
```
- [Kubernetes (Helm)](https://langfuse.com/self-hosting/kubernetes-helm): Helm을 사용해 Kubernetes 클러스터에서 Langfuse를 실행합니다. 이는 권장되는 프로덕션 배포 방식입니다.
- [VM](https://langfuse.com/self-hosting/docker-compose): Docker Compose를 사용해 단일 가상 머신에서 Langfuse를 실행합니다.
- 예정: 클라우드별 배포 가이드 – 아래 스레드에서 투표 및 댓글을 남겨주세요: [AWS](https://github.com/orgs/langfuse/discussions/4645), [Google Cloud](https://github.com/orgs/langfuse/discussions/4646), [Azure](https://github.com/orgs/langfuse/discussions/4647).
자세한 내용은 [자체 호스팅 문서](https://langfuse.com/self-hosting)를 참조하세요.
## 🔌 통합 기능
![Langfuse Integrations](https://langfuse.com/images/docs/github-readme/github-integrations.png)
### 주요 통합:
| 통합 | 지원 | 설명 |
| --------------------------------------------------------------------- | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| [SDK](https://langfuse.com/docs/sdk) | Python, JS/TS | SDK를 사용하여 완전한 유연성을 갖춘 수동 계측(manual instrumentation)을 수행합니다. |
| [OpenAI](https://langfuse.com/docs/integrations/openai) | Python, JS/TS | OpenAI SDK의 드롭인 대체(drop-in replacement)를 통해 자동 계측(automated instrumentation)을 수행합니다. |
| [Langchain](https://langfuse.com/docs/integrations/langchain) | Python, JS/TS | Langchain 애플리케이션에 callback 핸들러를 전달하여 자동 계측합니다. |
| [LlamaIndex](https://langfuse.com/docs/integrations/llama-index/get-started) | Python | LlamaIndex 콜백 시스템을 통한 자동 계측을 지원합니다. |
| [Haystack](https://langfuse.com/docs/integrations/haystack) | Python | Haystack 콘텐츠 추적 시스템을 통한 자동 계측을 지원합니다. |
| [LiteLLM](https://langfuse.com/docs/integrations/litellm) | Python, JS/TS (proxy only) | GPT의 드롭인 대체품으로 어떤 LLM도 사용할 수 있습니다. Azure, OpenAI, Cohere, Anthropic, Ollama, VLLM, Sagemaker, HuggingFace, Replicate 등 100개 이상의 LLM 지원. |
| [Vercel AI SDK](https://langfuse.com/docs/integrations/vercel-ai-sdk) | JS/TS | React, Next.js, Vue, Svelte, Node.js와 함께 AI 기반 애플리케이션 구축을 돕는 TypeScript 툴킷입니다. |
| [API](https://langfuse.com/docs/api) | | 공개 API를 직접 호출합니다. OpenAPI 명세가 제공됩니다. |
### Langfuse와 통합된 패키지:
| 이름 | 유형 | 설명 |
| ----------------------------------------------------------------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------- |
| [Instructor](https://langfuse.com/docs/integrations/instructor) | 라이브러리 | 구조화된 LLM 출력을(JSON, Pydantic) 얻기 위한 라이브러리입니다. |
| [DSPy](https://langfuse.com/docs/integrations/dspy) | 라이브러리 | 언어 모델 프롬프트와 가중치를 체계적으로 최적화하는 프레임워크입니다. |
| [Mirascope](https://langfuse.com/docs/integrations/mirascope) | 라이브러리 | LLM 애플리케이션 구축을 위한 Python 툴킷입니다. |
| [Ollama](https://langfuse.com/docs/integrations/ollama) | 모델 (로컬) | 자신의 컴퓨터에서 오픈 소스 LLM을 손쉽게 실행할 수 있습니다. |
| [Amazon Bedrock](https://langfuse.com/docs/integrations/amazon-bedrock) | 모델 | AWS에서 기본 및 파인튜닝된 모델을 실행합니다. |
| [AutoGen](https://langfuse.com/docs/integrations/autogen) | 에이전트 프레임워크 | 분산 에이전트 구축을 위한 오픈 소스 LLM 플랫폼입니다. |
| [Flowise](https://langfuse.com/docs/integrations/flowise) | 채팅/에이전트 UI | 맞춤형 LLM 플로우를 위한 JS/TS 코드 없는(no-code) 빌더입니다. |
| [Langflow](https://langfuse.com/docs/integrations/langflow) | 채팅/에이전트 UI | react-flow를 활용하여 실험 및 프로토타이핑을 손쉽게 할 수 있도록 디자인된 LangChain용 Python 기반 UI입니다. |
| [Dify](https://langfuse.com/docs/integrations/dify) | 채팅/에이전트 UI | 코드 없는 빌더와 함께 제공되는 오픈 소스 LLM 애플리케이션 개발 플랫폼입니다. |
| [OpenWebUI](https://langfuse.com/docs/integrations/openwebui) | 채팅/에이전트 UI | 셀프 호스팅 및 로컬 모델 등 다양한 LLM 실행기를 지원하는 셀프 호스팅 LLM 채팅 웹 UI입니다. |
| [Promptfoo](https://langfuse.com/docs/integrations/promptfoo) | 도구 | 오픈 소스 LLM 테스트 플랫폼입니다. |
| [LobeChat](https://langfuse.com/docs/integrations/lobechat) | 채팅/에이전트 UI | 오픈 소스 챗봇 플랫폼입니다. |
| [Vapi](https://langfuse.com/docs/integrations/vapi) | 플랫폼 | 오픈 소스 음성 AI 플랫폼입니다. |
| [Inferable](https://langfuse.com/docs/integrations/other/inferable) | 에이전트 | 분산 에이전트 구축을 위한 오픈 소스 LLM 플랫폼입니다. |
| [Gradio](https://langfuse.com/docs/integrations/other/gradio) | 채팅/에이전트 UI | 채팅 UI와 같은 웹 인터페이스 구축을 위한 오픈 소스 Python 라이브러리입니다. |
| [Goose](https://langfuse.com/docs/integrations/goose) | 에이전트 | 분산 에이전트 구축을 위한 오픈 소스 LLM 플랫폼입니다. |
| [smolagents](https://langfuse.com/docs/integrations/smolagents) | 에이전트 | 오픈 소스 AI 에이전트 프레임워크입니다. |
| [CrewAI](https://langfuse.com/docs/integrations/crewai) | 에이전트 | 에이전트 간 협업 및 도구 사용을 위한 다중 에이전트 프레임워크입니다. |
## 🚀 빠른 시작
앱에 계측을 추가하고 Langfuse에 trace 데이터를 수집하여, LLM 호출 및 검색, 임베딩, 에이전트 동작과 같은 애플리케이션 로직을 추적해보세요. 복잡한 로그와 사용자 세션을 확인하여 디버깅할 수 있습니다.
### 1️⃣ 새 프로젝트 생성
1. [Langfuse 계정 생성](https://cloud.langfuse.com/auth/sign-up) 또는 [셀프 호스트](https://langfuse.com/self-hosting)
2. 새 프로젝트를 생성합니다.
3. 프로젝트 설정에서 새로운 API 자격 증명을 생성합니다.
### 2️⃣ 첫 번째 LLM 호출 기록하기
[`@observe()` 데코레이터](https://langfuse.com/docs/sdk/python/decorators)를 사용하면 Python LLM 애플리케이션의 추적이 매우 간편해집니다. 이 빠른 시작 예제에서는 Langfuse [OpenAI 통합](https://langfuse.com/docs/integrations/openai)을 사용하여 모든 모델 파라미터를 자동으로 캡처합니다.
> [!TIP]
> OpenAI를 사용하지 않으시다면, 다른 모델 및 프레임워크의 로그 기록 방법은 [문서](https://langfuse.com/docs/get-started#log-your-first-llm-call-to-langfuse)를 참조하세요.
```bash
pip install langfuse openai
```
```bash filename=".env"
LANGFUSE_SECRET_KEY="sk-lf-..."
LANGFUSE_PUBLIC_KEY="pk-lf-..."
LANGFUSE_HOST="https://cloud.langfuse.com" # 🇪🇺 EU region
# LANGFUSE_HOST="https://us.cloud.langfuse.com" # 🇺🇸 US region
```
```python:main.py
from langfuse.decorators import observe
from langfuse.openai import openai # OpenAI integration
@observe()
def story():
return openai.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "What is Langfuse?"}],
).choices[0].message.content
@observe()
def main():
return story()
main()
```
### 3️⃣ Langfuse에서 trace 확인하기
Langfuse에서 LLM 호출 및 애플리케이션의 기타 로직에 대한 trace를 확인할 수 있습니다.
![Example trace in Langfuse](https://langfuse.com/images/docs/github-readme/github-example-trace.png)
_[Langfuse의 공개 예제 trace](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/2cec01e3-3dc2-472f-afcf-3b968cf0c1f4?timestamp=2025-02-10T14%3A27%3A30.275Z&observation=cb5ff844-07ef-41e6-b8e2-6c64344bc13b)_
> [!TIP]
>
> Langfuse의 trace에 대해 더 알아보거나 [인터랙티브 데모](https://langfuse.com/docs/demo)에서 직접 체험해보세요.
## ⭐️ 별을 눌러주세요
![Star Langfuse](https://langfuse.com/images/docs/github-readme/github-star-howto.gif)
## 💭 지원
질문에 대한 답변을 찾는 방법:
- 우리의 [문서](https://langfuse.com/docs)는 답을 찾기 위한 최적의 장소입니다. 문서가 매우 포괄적이며, 유지보수에 많은 노력을 기울이고 있습니다. GitHub를 통해 문서 수정 제안도 가능합니다.
- [Langfuse FAQ](https://langfuse.com/faq)에서는 가장 흔한 질문에 대해 답변하고 있습니다.
- 질문에 즉각적인 답변이 필요하다면 [Ask AI](https://langfuse.com/docs/ask-ai)를 사용해보세요.
지원 채널:
- **GitHub Discussions의 [공개 Q&A](https://github.com/orgs/langfuse/discussions/categories/support)** 에 질문을 남겨주세요. 가능한 한 많은 세부 사항(예: 코드 스니펫, 스크린샷, 배경 정보)을 포함해 질문해 주시기 바랍니다.
- [기능 요청](https://github.com/orgs/langfuse/discussions/categories/ideas)을 남겨주세요.
- [버그 신고](https://github.com/langfuse/langfuse/issues)는 GitHub Issues를 통해 해주세요.
- 긴급한 문의는 앱 내 채팅 위젯을 통해 연락 바랍니다.
## 🤝 기여하기
여러분의 기여를 환영합니다!
- GitHub Discussions의 [아이디어](https://github.com/orgs/langfuse/discussions/categories/ideas)에 투표해보세요.
- GitHub Issues에서 이슈를 제기하고 댓글을 남겨주세요.
- PR을 제출하세요 – 개발 환경 설정 방법 등 자세한 내용은 [CONTRIBUTING.md](CONTRIBUTING.md)를 참조하세요.
## 🥇 라이선스
이 저장소는 `ee` 폴더를 제외하고 MIT 라이선스가 적용됩니다. 자세한 내용은 [LICENSE](LICENSE)와 [문서](https://langfuse.com/docs/open-source)를 확인하세요.
## ⭐️ 별(Star) 히스토리
<a href="https://star-history.com/#langfuse/langfuse&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=langfuse/langfuse&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=langfuse/langfuse&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=langfuse/langfuse&type=Date" style="border-radius: 15px;" />
</picture>
</a>
## ❤️ Langfuse를 사용하는 오픈 소스 프로젝트
별(star) 수를 기준으로 순위가 매겨진 Langfuse를 사용하는 상위 오픈 소스 Python 프로젝트들 ([출처](https://github.com/langfuse/langfuse-docs/blob/main/components-mdx/dependents)):
| 저장소 | 별 |
| :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---: |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/127165244?s=40&v=4" width="20" height="20" alt=""> &nbsp; [langgenius](https://github.com/langgenius) / [dify](https://github.com/langgenius/dify) | 54865 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/158137808?s=40&v=4" width="20" height="20" alt=""> &nbsp; [open-webui](https://github.com/open-webui) / [open-webui](https://github.com/open-webui/open-webui) | 51531 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/131470832?s=40&v=4" width="20" height="20" alt=""> &nbsp; [lobehub](https://github.com/lobehub) / [lobe-chat](https://github.com/lobehub/lobe-chat) | 49003 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/85702467?s=40&v=4" width="20" height="20" alt=""> &nbsp; [langflow-ai](https://github.com/langflow-ai) / [langflow](https://github.com/langflow-ai/langflow) | 39093 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/130722866?s=40&v=4" width="20" height="20" alt=""> &nbsp; [run-llama](https://github.com/run-llama) / [llama_index](https://github.com/run-llama/llama_index) | 37368 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/139558948?s=40&v=4" width="20" height="20" alt=""> &nbsp; [chatchat-space](https://github.com/chatchat-space) / [Langchain-Chatchat](https://github.com/chatchat-space/Langchain-Chatchat) | 32486 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/128289781?s=40&v=4" width="20" height="20" alt=""> &nbsp; [FlowiseAI](https://github.com/FlowiseAI) / [Flowise](https://github.com/FlowiseAI/Flowise) | 32448 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/31035808?s=40&v=4" width="20" height="20" alt=""> &nbsp; [mindsdb](https://github.com/mindsdb) / [mindsdb](https://github.com/mindsdb/mindsdb) | 26931 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/119600397?s=40&v=4" width="20" height="20" alt=""> &nbsp; [twentyhq](https://github.com/twentyhq) / [twenty](https://github.com/twentyhq/twenty) | 24195 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/60330232?s=40&v=4" width="20" height="20" alt=""> &nbsp; [PostHog](https://github.com/PostHog) / [posthog](https://github.com/PostHog/posthog) | 22618 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/121462774?s=40&v=4" width="20" height="20" alt=""> &nbsp; [BerriAI](https://github.com/BerriAI) / [litellm](https://github.com/BerriAI/litellm) | 15151 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/179202840?s=40&v=4" width="20" height="20" alt=""> &nbsp; [mediar-ai](https://github.com/mediar-ai) / [screenpipe](https://github.com/mediar-ai/screenpipe) | 11037 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/105877416?s=40&v=4" width="20" height="20" alt=""> &nbsp; [formbricks](https://github.com/formbricks) / [formbricks](https://github.com/formbricks/formbricks) | 9386 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/76263028?s=40&v=4" width="20" height="20" alt=""> &nbsp; [anthropics](https://github.com/anthropics) / [courses](https://github.com/anthropics/courses) | 8385 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/78410652?s=40&v=4" width="20" height="20" alt=""> &nbsp; [GreyDGL](https://github.com/GreyDGL) / [PentestGPT](https://github.com/GreyDGL/PentestGPT) | 7374 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/152537519?s=40&v=4" width="20" height="20" alt=""> &nbsp; [superagent-ai](https://github.com/superagent-ai) / [superagent](https://github.com/superagent-ai/superagent) | 5391 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/137907881?s=40&v=4" width="20" height="20" alt=""> &nbsp; [promptfoo](https://github.com/promptfoo) / [promptfoo](https://github.com/promptfoo/promptfoo) | 4976 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/157326433?s=40&v=4" width="20" height="20" alt=""> &nbsp; [onlook-dev](https://github.com/onlook-dev) / [onlook](https://github.com/onlook-dev/onlook) | 4141 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/7250217?s=40&v=4" width="20" height="20" alt=""> &nbsp; [Canner](https://github.com/Canner) / [WrenAI](https://github.com/Canner/WrenAI) | 2526 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/11855343?s=40&v=4" width="20" height="20" alt=""> &nbsp; [pingcap](https://github.com/pingcap) / [autoflow](https://github.com/pingcap/autoflow) | 2061 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/85268109?s=40&v=4" width="20" height="20" alt=""> &nbsp; [MLSysOps](https://github.com/MLSysOps) / [MLE-agent](https://github.com/MLSysOps/MLE-agent) | 1161 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/158137808?s=40&v=4" width="20" height="20" alt=""> &nbsp; [open-webui](https://github.com/open-webui) / [pipelines](https://github.com/open-webui/pipelines) | 1100 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/18422723?s=40&v=4" width="20" height="20" alt=""> &nbsp; [alishobeiri](https://github.com/alishobeiri) / [thread](https://github.com/alishobeiri/thread) | 1074 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/125468716?s=40&v=4" width="20" height="20" alt=""> &nbsp; [topoteretes](https://github.com/topoteretes) / [cognee](https://github.com/topoteretes/cognee) | 971 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/188657705?s=40&v=4" width="20" height="20" alt=""> &nbsp; [bRAGAI](https://github.com/bRAGAI) / [bRAG-langchain](https://github.com/bRAGAI/bRAG-langchain) | 823 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/169500408?s=40&v=4" width="20" height="20" alt=""> &nbsp; [opslane](https://github.com/opslane) / [opslane](https://github.com/opslane/opslane) | 677 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/151867818?s=40&v=4" width="20" height="20" alt=""> &nbsp; [dynamiq-ai](https://github.com/dynamiq-ai) / [dynamiq](https://github.com/dynamiq-ai/dynamiq) | 639 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/48585267?s=40&v=4" width="20" height="20" alt=""> &nbsp; [theopenconversationkit](https://github.com/theopenconversationkit) / [tock](https://github.com/theopenconversationkit/tock) | 514 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/20493493?s=40&v=4" width="20" height="20" alt=""> &nbsp; [andysingal](https://github.com/andysingal) / [llm-course](https://github.com/andysingal/llm-course) | 394 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/132396805?s=40&v=4" width="20" height="20" alt=""> &nbsp; [phospho-app](https://github.com/phospho-app) / [phospho](https://github.com/phospho-app/phospho) | 384 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/178644984?s=40&v=4" width="20" height="20" alt=""> &nbsp; [sentient-engineering](https://github.com/sentient-engineering) / [agent-q](https://github.com/sentient-engineering/agent-q) | 370 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/168552753?s=40&v=4" width="20" height="20" alt=""> &nbsp; [sql-agi](https://github.com/sql-agi) / [DB-GPT](https://github.com/sql-agi/DB-GPT) | 324 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/60330232?s=40&v=4" width="20" height="20" alt=""> &nbsp; [PostHog](https://github.com/PostHog) / [posthog-foss](https://github.com/PostHog/posthog-foss) | 305 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/154247157?s=40&v=4" width="20" height="20" alt=""> &nbsp; [vespperhq](https://github.com/vespperhq) / [vespper](https://github.com/vespperhq/vespper) | 304 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/185116535?s=40&v=4" width="20" height="20" alt=""> &nbsp; [block](https://github.com/block) / [goose](https://github.com/block/goose) | 295 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/609489?s=40&v=4" width="20" height="20" alt=""> &nbsp; [aorwall](https://github.com/aorwall) / [moatless-tools](https://github.com/aorwall/moatless-tools) | 291 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/2357342?s=40&v=4" width="20" height="20" alt=""> &nbsp; [dmayboroda](https://github.com/dmayboroda) / [minima](https://github.com/dmayboroda/minima) | 221 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/66303003?s=40&v=4" width="20" height="20" alt=""> &nbsp; [RobotecAI](https://github.com/RobotecAI) / [rai](https://github.com/RobotecAI/rai) | 172 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/148684274?s=40&v=4" width="20" height="20" alt=""> &nbsp; [i-am-alice](https://github.com/i-am-alice) / [3rd-devs](https://github.com/i-am-alice/3rd-devs) | 148 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/171735272?s=40&v=4" width="20" height="20" alt=""> &nbsp; [8090-inc](https://github.com/8090-inc) / [xrx-sample-apps](https://github.com/8090-inc/xrx-sample-apps) | 138 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/104478511?s=40&v=4" width="20" height="20" alt=""> &nbsp; [babelcloud](https://github.com/babelcloud) / [LLM-RGB](https://github.com/babelcloud/LLM-RGB) | 135 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/15125613?s=40&v=4" width="20" height="20" alt=""> &nbsp; [souzatharsis](https://github.com/souzatharsis) / [tamingLLMs](https://github.com/souzatharsis/tamingLLMs) | 129 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/169401942?s=40&v=4" width="20" height="20" alt=""> &nbsp; [LibreChat-AI](https://github.com/LibreChat-AI) / [librechat.ai](https://github.com/LibreChat-AI/librechat.ai) | 128 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/51827949?s=40&v=4" width="20" height="20" alt=""> &nbsp; [deepset-ai](https://github.com/deepset-ai) / [haystack-core-integrations](https://github.com/deepset-ai/haystack-core-integrations) | 126 |
## 🔒 보안 & 개인정보 보호
우리는 데이터 보안과 개인정보 보호를 매우 중요하게 생각합니다. 자세한 내용은 [Security and Privacy](https://langfuse.com/security) 페이지를 참조하세요.
### 텔레메트리
기본적으로 Langfuse는 자체 호스팅 인스턴스의 기본 사용 통계를 중앙 서버(PostHog)로 자동 보고합니다.
이를 통해:
1. Langfuse가 어떻게 사용되는지 이해하고, 가장 관련성 높은 기능을 개선할 수 있습니다.
2. 내부 및 외부(예: 자금 조달) 보고를 위한 전체 사용량을 추적할 수 있습니다.
수집된 데이터는 제3자와 공유되지 않으며 민감한 정보를 포함하지 않습니다. 이에 대해 매우 투명하게 공개하고 있으며, 수집되는 정확한 데이터는 [여기](/web/src/features/telemetry/index.ts)에서 확인할 수 있습니다.
환경 변수 `TELEMETRY_ENABLED=false`를 설정하여 옵트아웃할 수 있습니다.
+195 -107
View File
@@ -1,113 +1,132 @@
![Langfuse GitHub Banner](https://github.com/langfuse/langfuse/assets/121163007/6035f0f3-d691-4963-b5d0-10cf506e9d42)
<div align="center"><h1>Langfuse: Open Source LLM Engineering Platform</h1></div>
<div align="center"><h4>LLM Observability, Prompt Management, LLM Evaluations,<br/>Datasets, LLM Metrics, and Prompt Playground</h4></div>
![Langfuse GitHub Banner](https://langfuse.com/images/docs/github-readme/github-banner.png)
<div align="center">
<div>
<h3>
<a href="https://cloud.langfuse.com">
<strong>Sign up</strong>
<strong>Langfuse Cloud</strong>
</a> ·
<a href="https://langfuse.com/docs/deployment/self-host">
<strong>Self Host</strong>
</a> ·
<a href="https://langfuse.com/demo">
<strong>Demo (live data)</strong>
<strong>Demo</strong>
</a>
</h3>
</div>
<div>
<a href="https://langfuse.com/docs"><strong>Docs</strong></a> ·
<a href="https://langfuse.com/issues"><strong>Report Bug</strong></a> ·
<a href="https://langfuse.com/ideas"><strong>Feature Request</strong></a> ·
<a href="https://langfuse.com/changelog"><strong>Changelog</strong></a> ·
<a href="https://langfuse.com/roadmap"><strong>Roadmap</strong></a> ·
<a href="https://langfuse.com/discord"><strong>Discord</strong></a>
</div>
<br/>
<span>Langfuse uses <a href="https://github.com/orgs/langfuse/discussions"><strong>Github Discussions</strong></a> for Support and Feature Requests.</span>
<br/>
<span>We're hiring. <a href="https://langfuse.com/careers"><strong>Join us</strong></a> in Product Engineering and Developer Relations.</span>
<span><b>We're hiring.</b> <a href="https://langfuse.com/careers"><strong>Join us</strong></a> in product engineering and technical go-to-market roles.</span>
<br/>
<br/>
<div>
<a href="https://github.com/langfuse/langfuse/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-MIT-red.svg?style=flat-square" alt="MIT License"></a>
<a href="https://www.ycombinator.com/companies/langfuse"><img src="https://img.shields.io/badge/Y%20Combinator-W23-orange?style=flat-square" alt="Y Combinator W23"></a>
<a href="https://github.com/langfuse/langfuse/pkgs/container/langfuse"><img alt="Docker Image" src="https://img.shields.io/badge/docker-langfuse-blue?logo=Docker&logoColor=white&style=flat-square"></a>
<a href="https://pypi.python.org/pypi/langfuse"><img src="https://img.shields.io/pypi/dm/langfuse?style=flat-square&logo=python&logoColor=white&label=pypi%20langfuse&color=blue" alt="langfuse Python package on PyPi"></a>
<a href="https://www.npmjs.com/package/langfuse"><img src="https://img.shields.io/npm/dm/langfuse?style=flat-square&logo=npm&logoColor=white&label=npm%20langfuse&color=blue" alt="langfuse npm package"></a>
</div>
</div>
</br>
## Langfuse Overview
<p align="center">
<a href="https://github.com/langfuse/langfuse/blob/main/LICENSE">
<img src="https://img.shields.io/badge/License-MIT-E11311.svg" alt="MIT License">
</a>
<a href="https://www.ycombinator.com/companies/langfuse"><img src="https://img.shields.io/badge/Y%20Combinator-W23-orange" alt="Y Combinator W23"></a>
<a href="https://hub.docker.com/u/langfuse" target="_blank">
<img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/langfuse/langfuse?labelColor=%20%23FDB062&logo=Docker&labelColor=%20%23528bff"></a>
<a href="https://pypi.python.org/pypi/langfuse"><img src="https://img.shields.io/pypi/dm/langfuse?logo=python&logoColor=white&label=pypi%20langfuse&color=blue" alt="langfuse Python package on PyPi"></a>
<a href="https://www.npmjs.com/package/langfuse"><img src="https://img.shields.io/npm/dm/langfuse?logo=npm&logoColor=white&label=npm%20langfuse&color=blue" alt="langfuse npm package"></a>
<br/>
<a href="https://discord.com/invite/7NXusRtqYU" target="_blank">
<img src="https://img.shields.io/discord/1111061815649124414?logo=discord&labelColor=%20%235462eb&logoColor=%20%23f5f5f5&color=%20%235462eb"
alt="chat on Discord"></a>
<a href="https://twitter.com/intent/follow?screen_name=langfuse" target="_blank">
<img src="https://img.shields.io/twitter/follow/langfuse?logo=X&color=%20%23f5f5f5"
alt="follow on X(Twitter)"></a>
<a href="https://www.linkedin.com/company/langfuse/" target="_blank">
<img src="https://custom-icon-badges.demolab.com/badge/LinkedIn-0A66C2?logo=linkedin-white&logoColor=fff"
alt="follow on LinkedIn"></a>
<a href="https://github.com/langfuse/langfuse/graphs/commit-activity" target="_blank">
<img alt="Commits last month" src="https://img.shields.io/github/commit-activity/m/langfuse/langfuse?labelColor=%20%2332b583&color=%20%2312b76a"></a>
<a href="https://github.com/langfuse/langfuse/" target="_blank">
<img alt="Issues closed" src="https://img.shields.io/github/issues-search?query=repo%3Alangfuse%2Flangfuse%20is%3Aclosed&label=issues%20closed&labelColor=%20%237d89b0&color=%20%235d6b98"></a>
<a href="https://github.com/langfuse/langfuse/discussions/" target="_blank">
<img alt="Discussion posts" src="https://img.shields.io/github/discussions/langfuse/langfuse?labelColor=%20%239b8afb&color=%20%237a5af8"></a>
</p>
<p align="center">
<a href="./README.md"><img alt="README in English" src="https://img.shields.io/badge/English-d9d9d9"></a>
<a href="./README.cn.md"><img alt="简体中文版自述文件" src="https://img.shields.io/badge/简体中文-d9d9d9"></a>
<a href="./README.ja.md"><img alt="日本語のREADME" src="https://img.shields.io/badge/日本語-d9d9d9"></a>
<a href="./README.kr.md"><img alt="README in Korean" src="https://img.shields.io/badge/한국어-d9d9d9"></a>
</p>
Langfuse is an **open source LLM engineering** platform. It helps teams collaboratively
**develop, monitor, evaluate,** and **debug** AI applications. Langfuse can be **self-hosted in minutes** and is **battle-tested**.
[![Langfuse Overview Video](https://github.com/user-attachments/assets/3926b288-ff61-4b95-8aa1-45d041c70866)](https://langfuse.com/watch-demo)
### Develop
## ✨ Core Features
- **LLM Observability:** Instrument your app and start ingesting traces to Langfuse ([Quickstart](https://langfuse.com/docs/get-started), [Integrations](https://langfuse.com/docs/integrations) [Tracing](https://langfuse.com/docs/tracing))
- **Langfuse UI:** Inspect and debug complex logs ([Demo](https://langfuse.com/docs/demo), [Tracing](https://langfuse.com/docs/tracing))
- **Prompt Management:** Manage, version and deploy prompts from within Langfuse ([Prompt Management](https://langfuse.com/docs/prompts/get-started))
- **Prompt Engineering:** Test and iterate on your prompts with the [LLM Playground](https://langfuse.com/docs/playground)
![Langfuse Overview](https://langfuse.com/images/docs/github-readme/github-feature-overview.png)
### Monitor
- [LLM Application Observability](https://langfuse.com/docs/tracing): Instrument your app and start ingesting traces to Langfuse, thereby tracking LLM calls and other relevant logic in your app such as retrieval, embedding, or agent actions. Inspect and debug complex logs and user sessions. Try the interactive [demo](https://langfuse.com/docs/demo) to see this in action.
- **LLM Analytics:** Track metrics (cost, latency, quality) and gain insights from dashboards & data exports ([Analytics](https://langfuse.com/docs/analytics))
- **LLM Evaluations:** Collect and calculate scores for your LLM completions ([Scores & Evaluations](https://langfuse.com/docs/scores))
- Run ([Model-based evaluations](https://langfuse.com/docs/scores/model-based-evals)) and LLM-as-a-Judge within Langfuse
- Collect user feedback ([User Feedback](https://langfuse.com/docs/scores/user-feedback))
- Manually score LLM outputs in Langfuse ([Manual Scores](https://langfuse.com/docs/scores/manually))
- [Prompt Management](https://langfuse.com/docs/prompts/get-started) helps you centrally manage, version control, and collaboratively iterate on your prompts. Thanks to strong caching on server and client side, you can iterate on prompts without adding latency to your application.
### Test
- [Evaluations](https://langfuse.com/docs/scores/overview) are key to the LLM application development workflow, and Langfuse adapts to your needs. It supports LLM-as-a-judge, user feedback collection, manual labeling, and custom evaluation pipelines via APIs/SDKs.
- **Experiments:** Track and test app behaviour before deploying a new version
- Datasets let you test expected in and output pairs and benchmark performance before deploying ([Datasets](https://langfuse.com/docs/datasets))
- Track versions and releases in your application ([Experimentation](https://langfuse.com/docs/experimentation), [Prompt Management](https://langfuse.com/docs/prompts))
- [Datasets](https://langfuse.com/docs/datasets/overview) enable test sets and benchmarks for evaluating your LLM application. They support continuous improvement, pre-deployment testing, structured experiments, flexible evaluation, and seamless integration with frameworks like LangChain and LlamaIndex.
## Get started
- [LLM Playground](https://langfuse.com/docs/playground) is a tool for testing and iterating on your prompts and model configurations, shortening the feedback loop and accelerating development. When you see a bad result in tracing, you can directly jump to the playground to iterate on it.
- [Comprehensive API](https://langfuse.com/docs/api): Langfuse is frequently used to power bespoke LLMOps workflows while using the building blocks provided by Langfuse via the API. OpenAPI spec, Postman collection, and typed SDKs for Python, JS/TS are available.
## 📦 Deploy Langfuse
![Langfuse Deployment Options](https://langfuse.com/images/docs/github-readme/github-deployment-options.png)
### Langfuse Cloud
Managed deployment by the Langfuse team, generous free-tier (hobby plan), no credit card required.
**[» Langfuse Cloud](https://cloud.langfuse.com)**
<div align="center">
<a href="https://cloud.langfuse.com" target="_blank">
<img alt="Static Badge" src="https://img.shields.io/badge/»%20Sign%20up%20for%20Langfuse%20Cloud-8A2BE2?&color=orange">
</a>
</div>
## Self-Hosting Open Source LLM Observability with Langfuse
### Self-Host Langfuse
### Localhost (docker)
Run Langfuse on your own infrastructure:
```bash
# Clone repository
git clone https://github.com/langfuse/langfuse.git
cd langfuse
- [Local (docker compose)](https://langfuse.com/self-hosting/local): Run Langfuse on your own machine in 5 minutes using Docker Compose.
# Run server and database
docker compose up -d
```
```bash
# Get a copy of the latest Langfuse repository
git clone https://github.com/langfuse/langfuse.git
cd langfuse
[→ Learn more about deploying locally](https://langfuse.com/docs/deployment/local)
# Run the langfuse docker compose
docker compose up
```
### Self-host (docker)
- [Kubernetes (Helm)](https://langfuse.com/self-hosting/kubernetes-helm): Run Langfuse on a Kubernetes cluster using Helm. This is the preferred production deployment.
- [VM](https://langfuse.com/self-hosting/docker-compose): Run Langfuse on a single Virtual Machine using Docker Compose.
- Planned: Cloud-specific deployment guides, please upvote and comment on the following threads: [AWS](https://github.com/orgs/langfuse/discussions/4645), [Google Cloud](https://github.com/orgs/langfuse/discussions/4646), [Azure](https://github.com/orgs/langfuse/discussions/4647).
Langfuse is simple to self-host and keep updated. It currently requires only a single docker container and a postgres database.
[→ Self Hosting Instructions](https://langfuse.com/docs/deployment/self-host)
See [self-hosting documentation](https://langfuse.com/self-hosting) to learn more about the architecture and configuration options.
Templated deployments: [Railway, GCP, AWS, Azure, Kubernetes and others](https://langfuse.com/docs/deployment/self-host#platform-specific-information)
## 🔌 Integrations
## Get Started
![Langfuse Integrations](https://langfuse.com/images/docs/github-readme/github-integrations.png)
### API Keys
You need a Langfuse public and secret key to get started. Sign up [here](https://cloud.langfuse.com) and find them in your project settings.
### Ingesting Data · Instrumenting Your Application · LLM Observability with Langfuse
Note: We recommend using our fully async, typed [SDKs](https://langfuse.com/docs/sdk) that allow you to instrument any LLM application with any underlying model. They are available in [Python (Decorators)](https://langfuse.com/docs/sdk/python) & [JS/TS](https://langfuse.com/docs/sdk/typescript). The SDKs will always be the most fully featured and stable way to ingest data into Langfuse.
See the [→ Quickstart](https://langfuse.com/docs/get-started) to integrate Langfuse.
### LLM Observability Integrations
### Main Integrations:
| Integration | Supports | Description |
| ---------------------------------------------------------------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
@@ -120,77 +139,129 @@ See the [→ Quickstart](https://langfuse.com/docs/get-started) to integrate Lan
| [Vercel AI SDK](https://langfuse.com/docs/integrations/vercel-ai-sdk) | JS/TS | TypeScript toolkit designed to help developers build AI-powered applications with React, Next.js, Vue, Svelte, Node.js. |
| [API](https://langfuse.com/docs/api) | | Directly call the public API. OpenAPI spec available. |
Packages integrated with Langfuse:
### Packages integrated with Langfuse:
| Name | Description |
| --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| [Instructor](https://langfuse.com/docs/integrations/instructor) | Library to get structured LLM outputs (JSON, Pydantic) |
| [Dify](https://langfuse.com/docs/integrations/dify) | Open source LLM app development platform with no-code builder. |
| [Ollama](https://langfuse.com/docs/integrations/ollama) | Easily run open source LLMs on your own machine. |
| [Mirascope](https://langfuse.com/docs/integrations/mirascope) | Python toolkit for building LLM applications. |
| [Flowise](https://langfuse.com/docs/integrations/flowise) | JS/TS no-code builder for customized LLM flows. |
| [Langflow](https://langfuse.com/docs/integrations/langflow) | Python-based UI for LangChain, designed with react-flow to provide an effortless way to experiment and prototype flows. |
| Name | Type | Description |
| ----------------------------------------------------------------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------- |
| [Instructor](https://langfuse.com/docs/integrations/instructor) | Library | Library to get structured LLM outputs (JSON, Pydantic) |
| [DSPy](https://langfuse.com/docs/integrations/dspy) | Library | Framework that systematically optimizes language model prompts and weights |
| [Mirascope](https://langfuse.com/docs/integrations/mirascope) | Library | Python toolkit for building LLM applications. |
| [Ollama](https://langfuse.com/docs/integrations/ollama) | Model (local) | Easily run open source LLMs on your own machine. |
| [Amazon Bedrock](https://langfuse.com/docs/integrations/amazon-bedrock) | Model | Run foundation and fine-tuned models on AWS. |
| [AutoGen](https://langfuse.com/docs/integrations/autogen) | Agent Framework | Open source LLM platform for building distributed agents. |
| [Flowise](https://langfuse.com/docs/integrations/flowise) | Chat/Agent&nbsp;UI | JS/TS no-code builder for customized LLM flows. |
| [Langflow](https://langfuse.com/docs/integrations/langflow) | Chat/Agent&nbsp;UI | Python-based UI for LangChain, designed with react-flow to provide an effortless way to experiment and prototype flows. |
| [Dify](https://langfuse.com/docs/integrations/dify) | Chat/Agent&nbsp;UI | Open source LLM app development platform with no-code builder. |
| [OpenWebUI](https://langfuse.com/docs/integrations/openwebui) | Chat/Agent&nbsp;UI | Self-hosted LLM Chat web ui supporting various LLM runners including self-hosted and local models. |
| [Promptfoo](https://langfuse.com/docs/integrations/promptfoo) | Tool | Open source LLM testing platform. |
| [LobeChat](https://langfuse.com/docs/integrations/lobechat) | Chat/Agent&nbsp;UI | Open source chatbot platform. |
| [Vapi](https://langfuse.com/docs/integrations/vapi) | Platform | Open source voice AI platform. |
| [Inferable](https://langfuse.com/docs/integrations/other/inferable) | Agents | Open source LLM platform for building distributed agents. |
| [Gradio](https://langfuse.com/docs/integrations/other/gradio) | Chat/Agent&nbsp;UI | Open source Python library to build web interfaces like Chat UI. |
| [Goose](https://langfuse.com/docs/integrations/goose) | Agents | Open source LLM platform for building distributed agents. |
| [smolagents](https://langfuse.com/docs/integrations/smolagents) | Agents | Open source AI agents framework. |
| [CrewAI](https://langfuse.com/docs/integrations/crewai) | Agents | Multi agent framework for agent collaboration and tool use. |
## Questions and feedback
## 🚀 Quickstart
### Ideas and roadmap
Instrument your app and start ingesting traces to Langfuse, thereby tracking LLM calls and other relevant logic in your app such as retrieval, embedding, or agent actions. Inspect and debug complex logs and user sessions.
- [Roadmap](https://langfuse.com/roadmap)
- [GitHub Discussions](https://github.com/orgs/langfuse/discussions)
- [Feature Requests](https://langfuse.com/ideas)
### 1️⃣ Create new project
### Support and feedback
1. [Create Langfuse account](https://cloud.langfuse.com/auth/sign-up) or [self-host](https://langfuse.com/self-hosting)
2. Create a new project
3. Create new API credentials in the project settings
In order of preference the best way to communicate with us:
### 2️⃣ Log your first LLM call
- [GitHub Discussions](https://github.com/orgs/langfuse/discussions) (preferred): Contribute [ideas](https://langfuse.com/ideas), [support requests](https://langfuse.com/gh-support) and [report bugs](https://langfuse.com/issues)
- [Discord](https://langfuse.com/discord): community support
- Privately: contact at langfuse dot com
The [`@observe()` decorator](https://langfuse.com/docs/sdk/python/decorators) makes it easy to trace any Python LLM application. In this quickstart we also use the Langfuse [OpenAI integration](https://langfuse.com/docs/integrations/openai) to automatically capture all model parameters.
## Contributing to Langfuse
> [!TIP]
> Not using OpenAI? Visit [our documentation](https://langfuse.com/docs/get-started#log-your-first-llm-call-to-langfuse) to learn how to log other models and frameworks.
- Vote on [Ideas](https://github.com/orgs/langfuse/discussions/categories/ideas)
- Raise and comment on [Issues](https://github.com/langfuse/langfuse/issues)
```bash
pip install langfuse openai
```
```bash filename=".env"
LANGFUSE_SECRET_KEY="sk-lf-..."
LANGFUSE_PUBLIC_KEY="pk-lf-..."
LANGFUSE_HOST="https://cloud.langfuse.com" # 🇪🇺 EU region
# LANGFUSE_HOST="https://us.cloud.langfuse.com" # 🇺🇸 US region
```
```python /@observe()/ /from langfuse.openai import openai/ filename="main.py"
from langfuse.decorators import observe
from langfuse.openai import openai # OpenAI integration
@observe()
def story():
return openai.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "What is Langfuse?"}],
).choices[0].message.content
@observe()
def main():
return story()
main()
```
### 3️⃣ See traces in Langfuse
See your language model calls and other application logic in Langfuse.
![Example trace in Langfuse](https://langfuse.com/images/docs/github-readme/github-example-trace.png)
_[Public example trace in Langfuse](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/2cec01e3-3dc2-472f-afcf-3b968cf0c1f4?timestamp=2025-02-10T14%3A27%3A30.275Z&observation=cb5ff844-07ef-41e6-b8e2-6c64344bc13b)_
> [!TIP]
>
> [Learn more](https://langfuse.com/docs/tracing) about tracing in Langfuse or play with the [interactive demo](https://langfuse.com/docs/demo).
## ⭐️ Star Us
![star-langfuse-on-github](https://github.com/user-attachments/assets/79a1d816-d229-4526-aecc-097d4a19f1ad)
## 💭 Support
Finding an answer to your question:
- Our [documentation](https://langfuse.com/docs) is the best place to start looking for answers. It is comprehensive, and we invest significant time into maintaining it. You can also suggest edits to the docs via GitHub.
- [Langfuse FAQs](https://langfuse.com/faq) where the most common questions are answered.
- Use "[Ask AI](https://langfuse.com/docs/ask-ai)" to get instant answers to your questions.
Support Channels:
- **Ask any question in our [public Q&A](https://github.com/orgs/langfuse/discussions/categories/support) on GitHub Discussions.** Please include as much detail as possible (e.g. code snippets, screenshots, background information) to help us understand your question.
- [Request a feature](https://github.com/orgs/langfuse/discussions/categories/ideas) on GitHub Discussions.
- [Report a Bug](https://github.com/langfuse/langfuse/issues) on GitHub Issues.
- For time-sensitive queries, ping us via the in-app chat widget.
## 🤝 Contributing
Your contributions are welcome!
- Vote on [Ideas](https://github.com/orgs/langfuse/discussions/categories/ideas) in GitHub Discussions.
- Raise and comment on [Issues](https://github.com/langfuse/langfuse/issues).
- Open a PR - see [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to setup a development environment.
## License
## 🥇 License
This repository is MIT licensed, except for the `ee` folders. See [LICENSE](LICENSE) and [docs](https://langfuse.com/docs/open-source) for more details.
## Misc
### GET API to export your data
[**GET routes**](https://langfuse.com/docs/integrations/api) to use data in downstream applications (e.g. embedded analytics). You can also access them conveniently via the SDKs ([docs](https://langfuse.com/docs/query-traces)).
### Security & Privacy
We take data security and privacy seriously. Please refer to our [Security and Privacy](https://langfuse.com/security) page for more information.
### Telemetry
By default, Langfuse automatically reports basic usage statistics of self-hosted instances to a centralized server (PostHog).
This helps us to:
1. Understand how Langfuse is used and improve the most relevant features.
2. Track overall usage for internal and external (e.g. fundraising) reporting.
None of the data is shared with third parties and does not include any sensitive information. We want to be super transparent about this and you can find the exact data we collect [here](/web/src/features/telemetry/index.ts).
You can opt-out by setting `TELEMETRY_ENABLED=false`.
### Star History
## ⭐️ Star History
<a href="https://star-history.com/#langfuse/langfuse&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=langfuse/langfuse&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=langfuse/langfuse&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=langfuse/langfuse&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=langfuse/langfuse&type=Date" style="border-radius: 15px;" />
</picture>
</a>
### Open Source Projects Using Langfuse
## ❤️ Open Source Projects Using Langfuse
Top open-source Python projects that use Langfuse, ranked by stars ([Source](https://github.com/langfuse/langfuse-docs/blob/main/components-mdx/dependents)):
@@ -240,3 +311,20 @@ Top open-source Python projects that use Langfuse, ranked by stars ([Source](htt
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/15125613?s=40&v=4" width="20" height="20" alt=""> &nbsp; [souzatharsis](https://github.com/souzatharsis) / [tamingLLMs](https://github.com/souzatharsis/tamingLLMs) | 129 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/169401942?s=40&v=4" width="20" height="20" alt=""> &nbsp; [LibreChat-AI](https://github.com/LibreChat-AI) / [librechat.ai](https://github.com/LibreChat-AI/librechat.ai) | 128 |
| <img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/51827949?s=40&v=4" width="20" height="20" alt=""> &nbsp; [deepset-ai](https://github.com/deepset-ai) / [haystack-core-integrations](https://github.com/deepset-ai/haystack-core-integrations) | 126 |
## 🔒 Security & Privacy
We take data security and privacy seriously. Please refer to our [Security and Privacy](https://langfuse.com/security) page for more information.
### Telemetry
By default, Langfuse automatically reports basic usage statistics of self-hosted instances to a centralized server (PostHog).
This helps us to:
1. Understand how Langfuse is used and improve the most relevant features.
2. Track overall usage for internal and external (e.g. fundraising) reporting.
None of the data is shared with third parties and does not include any sensitive information. We want to be super transparent about this and you can find the exact data we collect [here](/web/src/features/telemetry/index.ts).
You can opt-out by setting `TELEMETRY_ENABLED=false`.
-19
View File
@@ -1,19 +0,0 @@
_We are Hiring_
Join us in building out Langfuse in Berlin, Germany. Langfuse is the open source LLM engineering platform: we build tooling to help developers [build & improve LLM applications](https://langfuse.com/docs).
We are an open source company, we hire in person (4+ days a week), we only hire excellent technical talent. Find more information on our [careers page](https://langfuse.com/careers)
_Open Roles_
- Product Engineer, 70-130k EUR, 0.1-0.35% Equity, https://www.ycombinator.com/companies/langfuse/jobs/aAvmoFB-product-engineer
- Backend Engineer, 70-130k EUR, 0.1-0.35% Equity, https://www.ycombinator.com/companies/langfuse/jobs/1bO16H6-backend-engineer
- Design Engineer, 70-130k EUR, 0.1-0.35% Equity, https://www.ycombinator.com/companies/langfuse/jobs/mDquP95-design-engineer
- Developer Advocate, 70-130k EUR, 0.1-0.35% Equity, https://www.ycombinator.com/companies/langfuse/jobs/uHysbKH-developer-advocate-devrel
_More Info_
- https://langfuse.com/careers
- https://langfuse.com/docs
- https://langfuse.com/why
- https://langfuse.com/changelog
Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

+4 -3
View File
@@ -48,6 +48,10 @@ services:
REDIS_HOST: ${REDIS_HOST:-redis}
REDIS_PORT: ${REDIS_PORT:-6379}
REDIS_AUTH: ${REDIS_AUTH:-myredissecret}
REDIS_TLS_ENABLED: ${REDIS_TLS_ENABLED:-false}
REDIS_TLS_CA: ${REDIS_TLS_CA:-/certs/ca.crt}
REDIS_TLS_CERT: ${REDIS_TLS_CERT:-/certs/redis.crt}
REDIS_TLS_KEY: ${REDIS_TLS_KEY:-/certs/redis.key}
restart: always
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/api/public/health"]
@@ -76,8 +80,6 @@ services:
clickhouse:
image: clickhouse/clickhouse-server
user: "101:101"
container_name: clickhouse
hostname: clickhouse
environment:
CLICKHOUSE_DB: default
CLICKHOUSE_USER: clickhouse
@@ -97,7 +99,6 @@ services:
minio:
image: minio/minio
container_name: minio
entrypoint: sh
# create the 'langfuse' bucket before starting the service
command: -c 'mkdir -p /data/langfuse && minio server --address ":9000" --console-address ":9001" /data'
-3
View File
@@ -2,8 +2,6 @@ services:
clickhouse:
image: clickhouse/clickhouse-server
user: "101:101"
container_name: clickhouse
hostname: clickhouse
environment:
CLICKHOUSE_DB: default
CLICKHOUSE_USER: clickhouse
@@ -19,7 +17,6 @@ services:
azurite:
image: mcr.microsoft.com/azure-storage/azurite
container_name: azurite
command: azurite-blob --blobHost 0.0.0.0
ports:
- "10000:10000"
-3
View File
@@ -2,8 +2,6 @@ services:
clickhouse:
image: clickhouse/clickhouse-server
user: "101:101"
container_name: clickhouse
hostname: clickhouse
environment:
CLICKHOUSE_DB: default
CLICKHOUSE_USER: clickhouse
@@ -19,7 +17,6 @@ services:
minio:
image: minio/minio
container_name: minio
entrypoint: sh
# create the 'langfuse' bucket before starting the service
command: -c 'mkdir -p /data/langfuse && minio server --address ":9000" --console-address ":9001" /data'
+4 -3
View File
@@ -43,6 +43,10 @@ services:
REDIS_HOST: ${REDIS_HOST:-redis}
REDIS_PORT: ${REDIS_PORT:-6379}
REDIS_AUTH: ${REDIS_AUTH:-myredissecret}
REDIS_TLS_ENABLED: ${REDIS_TLS_ENABLED:-false}
REDIS_TLS_CA: ${REDIS_TLS_CA:-/certs/ca.crt}
REDIS_TLS_CERT: ${REDIS_TLS_CERT:-/certs/redis.crt}
REDIS_TLS_KEY: ${REDIS_TLS_KEY:-/certs/redis.key}
langfuse-web:
image: langfuse/langfuse:3
@@ -68,8 +72,6 @@ services:
image: clickhouse/clickhouse-server
restart: always
user: "101:101"
container_name: clickhouse
hostname: clickhouse
environment:
CLICKHOUSE_DB: default
CLICKHOUSE_USER: clickhouse
@@ -90,7 +92,6 @@ services:
minio:
image: minio/minio
restart: always
container_name: minio
entrypoint: sh
# create the 'langfuse' bucket before starting the service
command: -c 'mkdir -p /data/langfuse && minio server --address ":9000" --console-address ":9001" /data'
+25 -11
View File
@@ -1,24 +1,36 @@
Langfuse Enterprise License (the “Enterprise License”)
Copyright (c) 2024 Langfuse GmbH ('Langfuse')
START NOTE
Langfuse is an open core project. Langfuse's core
is permissively licensed (MIT license).
Certain parts of the periphery of Langfuse are commercially
licensed and governed by this Enterprise License.
For the avoidance of doubt, this license does not apply
to the core of Langfuse as it is defined in its license in
the directory "/LICENSE" (as opposed to this file "ee/LICENSE")
which can be used and run without infringing the below license
and its licensed materials.
END NOTE
With regard to the Langfuse Software:
START OF LICENSE
Langfuse Enterprise license (the “Enterprise License” or "EE license")
Copyright (c) 2023-2025 Langfuse GmbH
With regard to the Langfuse Enterprise Software:
This software and associated documentation files (the "Software") may only be
used in production, if you (and any entity that you represent) have agreed to,
and are in compliance with, the Langfuse Terms of Service, available
used, if you (and any entity that you represent) have agreed to,
and are in compliance with, the applicable Langfuse Terms of Service, available
at https://langfuse.com/terms (the “Enterprise Terms”), or other
agreement governing the use of the Software, as agreed by you and Langfuse,
and otherwise have a valid Langfuse Enterprise license.
and otherwise have a valid Langfuse Enterprise License.
Subject to the foregoing sentence, you are free to
modify this Software and publish patches to the Software. You agree that Langfuse
and/or its licensors (as applicable) retain all right, title and interest in and
to all such modifications and/or patches, and all such modifications and/or
patches may only be used, copied, modified, displayed, distributed, or otherwise
exploited with a valid Langfuse Enterprise license.
Notwithstanding the foregoing, you may copy and modify
exploited with a valid Langfuse Enterprise License. Notwithstanding the foregoing, you may copy and modify
the Software for development and testing purposes, without requiring a
subscription. You agree that Langfuse and/or its licensors (as applicable) retain
subscription. You agree that Langfuse GmbH and/or its licensors (as applicable) retain
all right, title and interest in and to all such modifications. You are not
granted any other rights beyond what is expressly stated herein. Subject to the
foregoing, it is forbidden to copy, merge, publish, distribute, sublicense,
@@ -33,5 +45,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
For all third party components incorporated into the Langfuse Software, those
components are licensed under the original license provided by the owner of the
components are licensed under the original license provided by the owner of the
applicable component.
END OF LICENSE
-1
View File
@@ -48,7 +48,6 @@
},
"pnpm": {
"overrides": {
"jsonpath-plus": "10.0.7",
"nanoid": "^3.3.8"
}
}
+1 -1
View File
@@ -12,7 +12,7 @@ groups:
# namespaceExport: Langfuse
# allowCustomFetcher: true
- name: fernapi/fern-openapi
version: 0.0.26
version: 0.1.7
output:
location: local-file-system
path: ../../../web/public/generated/api-client
+9
View File
@@ -38,6 +38,9 @@ types:
public:
type: optional<boolean>
docs: Public traces are accessible via url without login
environment:
type: optional<string>
docs: The environment from which this trace originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.
TraceWithDetails: # GET /traces
extends: Trace
properties:
@@ -145,6 +148,9 @@ types:
costDetails:
type: optional<map<string, double>>
docs: The cost details of the observation. Key is the name of the cost metric, value is the cost in USD. The total key is the sum of all (non-total) cost metrics or the total value ingested.
environment:
type: optional<string>
docs: The environment from which this observation originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.
ObservationsView:
extends: Observation
@@ -249,6 +255,9 @@ types:
queueId:
type: optional<string>
docs: Reference an annotation queue on a score. Populated if the score was initially created in an annotation queue.
environment:
type: optional<string>
docs: The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.
NumericScore:
extends: BaseScore
properties:
+76 -3
View File
@@ -8,7 +8,15 @@ service:
endpoints:
batch:
docs: |
Batched ingestion for Langfuse Tracing. If you want to use tracing via the API, such as to build your own Langfuse client implementation, this is the only API route you need to implement.
Batched ingestion for Langfuse Tracing.
If you want to use tracing via the API, such as to build your own Langfuse client implementation, this is the only API route you need to implement.
Within each batch, there can be multiple events.
Each event has a type, an id, a timestamp, metadata and a body.
Internally, we refer to this as the "event envelope" as it tells us something about the event but not the trace.
We use the event id within this envelope to deduplicate messages to avoid processing the same event twice, i.e. the event id should be unique per request.
The event.body.id is the ID of the actual trace and will be used for updates and will be visible within the Langfuse App.
I.e. if you want to update a trace, you'd use the same body id, but separate event IDs.
Notes:
- Introduction to data model: https://langfuse.com/docs/tracing-data-model
@@ -29,6 +37,67 @@ service:
response:
type: IngestionResponse
status-code: 207
examples:
# Trace Create Request
- request:
batch:
- id: abcdef-1234-5678-90ab
timestamp: "2022-01-01T00:00:00.000Z"
type: "trace-create"
body:
id: abcdef-1234-5678-90ab
timestamp: "2022-01-01T00:00:00.000Z"
name: "My Trace"
userId: "1234-5678-90ab-cdef"
input: "My input"
output: "My output"
sessionId: "1234-5678-90ab-cdef"
release: "1.0.0"
version: "1.0.0"
metadata: "My metadata"
tags: ["tag1", "tag2"]
public: true
response:
body:
successes:
- id: abcdef-1234-5678-90ab
status: 201
errors: []
# Observation Create Request
- request:
batch:
- id: abcdef-1234-5678-90ab
timestamp: "2022-01-01T00:00:00.000Z"
type: "span-create"
body:
id: abcdef-1234-5678-90ab
traceId: "1234-5678-90ab-cdef"
startTime: "2022-01-01T00:00:00.000Z"
response:
body:
successes:
- id: abcdef-1234-5678-90ab
status: 201
errors: []
# Score Create Request
- request:
batch:
- id: abcdef-1234-5678-90ab
timestamp: "2022-01-01T00:00:00.000Z"
type: "score-create"
body:
id: abcdef-1234-5678-90ab
traceId: "1234-5678-90ab-cdef"
name: "My Score"
value: 0.9
response:
body:
successes:
- id: abcdef-1234-5678-90ab
status: 201
errors: []
types:
IngestionEvent:
@@ -99,6 +168,7 @@ types:
statusMessage: optional<string>
parentObservationId: optional<string>
version: optional<string>
environment: optional<string>
CreateEventBody:
extends: OptionalObservationBody
@@ -128,7 +198,7 @@ types:
modelParameters: optional<map<string, commons.MapValue>>
usage: optional<IngestionUsage>
usageDetails: optional<UsageDetails>
costDetails: optional<map<string, float>>
costDetails: optional<map<string, double>>
promptName: optional<string>
promptVersion: optional<integer>
@@ -141,7 +211,7 @@ types:
usage: optional<IngestionUsage>
promptName: optional<string>
usageDetails: optional<UsageDetails>
costDetails: optional<map<string, float>>
costDetails: optional<map<string, double>>
promptVersion: optional<integer>
ObservationBody:
@@ -163,6 +233,7 @@ types:
level: optional<commons.ObservationLevel>
statusMessage: optional<string>
parentObservationId: optional<string>
environment: optional<string>
TraceBody:
properties:
@@ -177,6 +248,7 @@ types:
version: optional<string>
metadata: optional<unknown>
tags: optional<list<string>>
environment: optional<string>
public:
type: optional<boolean>
docs: Make trace publicly accessible via url
@@ -190,6 +262,7 @@ types:
id: optional<string>
traceId: string
name: string
environment: optional<string>
value:
type: commons.CreateScoreValue
docs: The value of the score. Must be passed as string for categorical scores, and numeric for boolean and numeric scores. Boolean score values must equal either 1 or 0 (true or false)
@@ -9,9 +9,9 @@ service:
update:
docs: Update labels for a specific prompt version
method: PATCH
path: /prompts/{promptName}/version/{version}
path: /prompts/{name}/versions/{version}
path-parameters:
promptName:
name:
type: string
docs: The name of the prompt
version:
+10
View File
@@ -90,6 +90,9 @@ types:
tags:
type: optional<list<string>>
docs: List of tags to apply to all versions of this prompt.
commitMessage:
type: optional<string>
docs: Commit message for this prompt version.
CreateTextPromptRequest:
properties:
@@ -102,6 +105,10 @@ types:
tags:
type: optional<list<string>>
docs: List of tags to apply to all versions of this prompt.
commitMessage:
type: optional<string>
docs: Commit message for this prompt version.
Prompt:
union:
chat: ChatPrompt
@@ -118,6 +125,9 @@ types:
tags:
type: list<string>
docs: List of tags. Used to filter via UI and API. The same across versions of a prompt.
commitMessage:
type: optional<string>
docs: Commit message for this prompt version.
ChatMessage:
properties:
+1 -1
View File
@@ -59,7 +59,7 @@ service:
type: optional<commons.ScoreDataType>
docs: Retrieve only scores with a specific dataType.
traceTags:
type: optional<list<string>>
type: optional<string>
allow-multiple: true
docs: Only scores linked to traces that include all of these tags will be returned.
response: GetScoresResponse
+1 -1
View File
@@ -3,7 +3,7 @@ groups:
local:
generators:
- name: fernapi/fern-openapi
version: 0.0.31
version: 0.1.7
output:
location: local-file-system
path: ../../../web/public/generated/api
+3 -4
View File
@@ -1,6 +1,6 @@
{
"name": "langfuse",
"version": "3.16.0",
"version": "3.34.0",
"author": "engineering@langfuse.com",
"license": "MIT",
"private": true,
@@ -29,12 +29,12 @@
"prepare": "husky"
},
"devDependencies": {
"@release-it/bumper": "^6.0.1",
"@release-it/bumper": "^7.0.1",
"braces": "3.0.3",
"dotenv-cli": "^7.4.2",
"husky": "^9.0.11",
"prettier": "^3.3.3",
"release-it": "^17.3.0",
"release-it": "^18.1.2",
"turbo": "^1.13.4"
},
"release-it": {
@@ -83,7 +83,6 @@
"packageManager": "pnpm@9.5.0",
"pnpm": {
"overrides": {
"jsonpath-plus": "10.0.7",
"nanoid": "^3.3.8",
"katex": "^0.16.21"
},
@@ -0,0 +1 @@
DROP TABLE event_log ON CLUSTER default;
@@ -0,0 +1,19 @@
CREATE TABLE event_log ON CLUSTER default
(
`id` String,
`project_id` String,
`entity_type` String,
`entity_id` String,
`event_id` Nullable(String),
`bucket_name` String,
`bucket_path` String,
`created_at` DateTime64(3) DEFAULT now(),
`updated_at` DateTime64(3) DEFAULT now()
) ENGINE = MergeTree()
ORDER BY (
project_id,
entity_type,
entity_id
);
@@ -0,0 +1,3 @@
ALTER TABLE traces ON CLUSTER default DROP COLUMN IF EXISTS environment;
ALTER TABLE observations ON CLUSTER default DROP COLUMN IF EXISTS environment;
ALTER TABLE scores ON CLUSTER default DROP COLUMN IF EXISTS environment;
@@ -0,0 +1,3 @@
ALTER TABLE traces ON CLUSTER default ADD COLUMN environment LowCardinality(String) DEFAULT 'default' AFTER project_id;
ALTER TABLE observations ON CLUSTER default ADD COLUMN environment LowCardinality(String) DEFAULT 'default' AFTER project_id;
ALTER TABLE scores ON CLUSTER default ADD COLUMN environment LowCardinality(String) DEFAULT 'default' AFTER project_id;
@@ -0,0 +1 @@
DROP TABLE event_log;
@@ -0,0 +1,19 @@
CREATE TABLE event_log
(
`id` String,
`project_id` String,
`entity_type` String,
`entity_id` String,
`event_id` Nullable(String),
`bucket_name` String,
`bucket_path` String,
`created_at` DateTime64(3) DEFAULT now(),
`updated_at` DateTime64(3) DEFAULT now()
) ENGINE = MergeTree()
ORDER BY (
project_id,
entity_type,
entity_id
);
@@ -0,0 +1,3 @@
ALTER TABLE traces DROP COLUMN IF EXISTS environment;
ALTER TABLE observations DROP COLUMN IF EXISTS environment;
ALTER TABLE scores DROP COLUMN IF EXISTS environment;
@@ -0,0 +1,3 @@
ALTER TABLE traces ADD COLUMN environment LowCardinality(String) DEFAULT 'default' AFTER project_id;
ALTER TABLE observations ADD COLUMN environment LowCardinality(String) DEFAULT 'default' AFTER project_id;
ALTER TABLE scores ADD COLUMN environment LowCardinality(String) DEFAULT 'default' AFTER project_id;
+1 -5
View File
@@ -1,7 +1,4 @@
import {
clickhouseClient,
ObservationRecordReadType,
} from "@langfuse/shared/src/server";
import { ObservationRecordReadType } from "@langfuse/shared/src/server";
import { prisma } from "../../src/db";
import { redis } from "@langfuse/shared/src/server";
import { prepareClickhouse } from "../../scripts/prepareClickhouse";
@@ -65,7 +62,6 @@ async function main() {
} catch (error) {
console.error("Error during Clickhouse preparation:", error);
} finally {
await clickhouseClient().close();
await prisma.$disconnect();
redis?.disconnect();
console.log("Disconnected from Clickhouse.");
+11 -11
View File
@@ -33,7 +33,7 @@
"scripts": {
"build": "tsc",
"dev": "tsc --watch",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx --max-warnings 64",
"lint:fix": "eslint . --ext .js,.jsx,.ts,.tsx --fix",
"db:migrate": "DISABLE_ERD=false dotenv -e ../../.env -- npx prisma migrate dev",
"db:push": "DISABLE_ERD=false dotenv -e ../../.env -- npx prisma db push",
@@ -61,26 +61,27 @@
"@aws-sdk/s3-request-presigner": "^3.679.0",
"@azure/storage-blob": "^12.26.0",
"@clickhouse/client": "^1.4.0",
"@langchain/anthropic": "^0.3.8",
"@langchain/aws": "^0.1.2",
"@langchain/core": "^0.3.18",
"@langchain/google-vertexai": "^0.1.3",
"@langchain/openai": "^0.3.14",
"@langchain/anthropic": "^0.3.12",
"@langchain/aws": "^0.1.3",
"@langchain/core": "^0.3.37",
"@langchain/google-genai": "^0.1.9",
"@langchain/google-vertexai": "^0.1.8",
"@langchain/openai": "^0.3.17",
"@opentelemetry/api": ">=1.0.0 <1.10.0",
"@prisma/client": "^5.22.0",
"@prisma/client": "^6.3.0",
"@react-email/components": "^0.0.19",
"@react-email/render": "^0.0.15",
"@types/bcryptjs": "^2.4.6",
"axios": "^1.7.7",
"bcryptjs": "^2.4.3",
"bullmq": "^5.34.10",
"dd-trace": "^5.23.1",
"dd-trace": "^5.36.0",
"decimal.js": "^10.4.3",
"exponential-backoff": "^3.1.1",
"https-proxy-agent": "^7.0.6",
"ioredis": "^5.4.1",
"kysely": "^0.27.4",
"langchain": "^0.3.6",
"langchain": "^0.3.15",
"langfuse-langchain": "3.30.3",
"lodash": "^4.17.21",
"next-auth": "^4.24.11",
@@ -107,7 +108,7 @@
"kysely-codegen": "^0.16.8",
"nodemon": "^3.1.7",
"prettier": "^3.3.3",
"prisma": "^5.22.0",
"prisma": "^6.3.0",
"prisma-erd-generator": "^1.11.2",
"prisma-kysely": "^1.8.0",
"ts-node": "^10.9.2",
@@ -122,7 +123,6 @@
},
"pnpm": {
"overrides": {
"jsonpath-plus": "10.0.7",
"nanoid": "^3.3.8"
}
}
+83 -150
View File
@@ -12,25 +12,25 @@ export const Role = {
NONE: "NONE"
} as const;
export type Role = (typeof Role)[keyof typeof Role];
export const ObservationType = {
export const LegacyPrismaObservationType = {
SPAN: "SPAN",
EVENT: "EVENT",
GENERATION: "GENERATION"
} as const;
export type ObservationType = (typeof ObservationType)[keyof typeof ObservationType];
export const ObservationLevel = {
export type LegacyPrismaObservationType = (typeof LegacyPrismaObservationType)[keyof typeof LegacyPrismaObservationType];
export const LegacyPrismaObservationLevel = {
DEBUG: "DEBUG",
DEFAULT: "DEFAULT",
WARNING: "WARNING",
ERROR: "ERROR"
} as const;
export type ObservationLevel = (typeof ObservationLevel)[keyof typeof ObservationLevel];
export const ScoreSource = {
export type LegacyPrismaObservationLevel = (typeof LegacyPrismaObservationLevel)[keyof typeof LegacyPrismaObservationLevel];
export const LegacyPrismaScoreSource = {
ANNOTATION: "ANNOTATION",
API: "API",
EVAL: "EVAL"
} as const;
export type ScoreSource = (typeof ScoreSource)[keyof typeof ScoreSource];
export type LegacyPrismaScoreSource = (typeof LegacyPrismaScoreSource)[keyof typeof LegacyPrismaScoreSource];
export const ScoreDataType = {
CATEGORICAL: "CATEGORICAL",
NUMERIC: "NUMERIC",
@@ -253,16 +253,6 @@ export type EvalTemplate = {
vars: Generated<string[]>;
output_schema: unknown;
};
export type Events = {
id: string;
created_at: Generated<Timestamp>;
updated_at: Generated<Timestamp>;
project_id: string;
data: unknown;
headers: Generated<unknown>;
url: string | null;
method: string | null;
};
export type JobConfiguration = {
id: string;
created_at: Generated<Timestamp>;
@@ -277,6 +267,7 @@ export type JobConfiguration = {
variable_mapping: unknown;
sampling: string;
delay: number;
time_scope: Generated<string[]>;
};
export type JobExecution = {
id: string;
@@ -293,6 +284,77 @@ export type JobExecution = {
job_input_dataset_item_id: string | null;
job_output_score_id: string | null;
};
export type LegacyPrismaObservation = {
id: string;
trace_id: string | null;
project_id: string;
type: LegacyPrismaObservationType;
start_time: Generated<Timestamp>;
end_time: Timestamp | null;
name: string | null;
metadata: unknown | null;
parent_observation_id: string | null;
level: Generated<LegacyPrismaObservationLevel>;
status_message: string | null;
version: string | null;
created_at: Generated<Timestamp>;
updated_at: Generated<Timestamp>;
model: string | null;
internal_model: string | null;
internal_model_id: string | null;
modelParameters: unknown | null;
input: unknown | null;
output: unknown | null;
prompt_tokens: Generated<number>;
completion_tokens: Generated<number>;
total_tokens: Generated<number>;
unit: string | null;
input_cost: string | null;
output_cost: string | null;
total_cost: string | null;
calculated_input_cost: string | null;
calculated_output_cost: string | null;
calculated_total_cost: string | null;
completion_start_time: Timestamp | null;
prompt_id: string | null;
};
export type LegacyPrismaScore = {
id: string;
timestamp: Generated<Timestamp>;
project_id: string;
name: string;
value: number | null;
source: LegacyPrismaScoreSource;
author_user_id: string | null;
comment: string | null;
trace_id: string;
observation_id: string | null;
config_id: string | null;
string_value: string | null;
queue_id: string | null;
created_at: Generated<Timestamp>;
updated_at: Generated<Timestamp>;
data_type: Generated<ScoreDataType>;
};
export type LegacyPrismaTrace = {
id: string;
external_id: string | null;
timestamp: Generated<Timestamp>;
name: string | null;
user_id: string | null;
metadata: unknown | null;
release: string | null;
version: string | null;
project_id: string;
public: Generated<boolean>;
bookmarked: Generated<boolean>;
tags: Generated<string[]>;
input: unknown | null;
output: unknown | null;
session_id: string | null;
created_at: Generated<Timestamp>;
updated_at: Generated<Timestamp>;
};
export type LlmApiKeys = {
id: string;
created_at: Generated<Timestamp>;
@@ -349,40 +411,6 @@ export type Model = {
tokenizer_id: string | null;
tokenizer_config: unknown | null;
};
export type Observation = {
id: string;
trace_id: string | null;
project_id: string;
type: ObservationType;
start_time: Generated<Timestamp>;
end_time: Timestamp | null;
name: string | null;
metadata: unknown | null;
parent_observation_id: string | null;
level: Generated<ObservationLevel>;
status_message: string | null;
version: string | null;
created_at: Generated<Timestamp>;
updated_at: Generated<Timestamp>;
model: string | null;
internal_model: string | null;
internal_model_id: string | null;
modelParameters: unknown | null;
input: unknown | null;
output: unknown | null;
prompt_tokens: Generated<number>;
completion_tokens: Generated<number>;
total_tokens: Generated<number>;
unit: string | null;
input_cost: string | null;
output_cost: string | null;
total_cost: string | null;
calculated_input_cost: string | null;
calculated_output_cost: string | null;
calculated_total_cost: string | null;
completion_start_time: Timestamp | null;
prompt_id: string | null;
};
export type ObservationMedia = {
id: string;
project_id: string;
@@ -393,43 +421,6 @@ export type ObservationMedia = {
observation_id: string;
field: string;
};
export type ObservationView = {
id: string;
trace_id: string | null;
project_id: string;
type: ObservationType;
start_time: Timestamp;
end_time: Timestamp | null;
name: string | null;
metadata: unknown | null;
parent_observation_id: string | null;
level: Generated<ObservationLevel>;
status_message: string | null;
version: string | null;
created_at: Timestamp;
updated_at: Timestamp;
model: string | null;
modelParameters: unknown | null;
input: unknown | null;
output: unknown | null;
prompt_tokens: Generated<number>;
completion_tokens: Generated<number>;
total_tokens: Generated<number>;
unit: string | null;
completion_start_time: Timestamp | null;
prompt_id: string | null;
prompt_name: string | null;
prompt_version: number | null;
model_id: string | null;
input_price: string | null;
output_price: string | null;
total_price: string | null;
calculated_input_cost: string | null;
calculated_output_cost: string | null;
calculated_total_cost: string | null;
latency: number | null;
time_to_first_token: number | null;
};
export type Organization = {
id: string;
name: string;
@@ -492,6 +483,7 @@ export type Prompt = {
config: Generated<unknown>;
tags: Generated<string[]>;
labels: Generated<string[]>;
commit_message: string | null;
};
export type QueueBackUp = {
id: string;
@@ -500,24 +492,6 @@ export type QueueBackUp = {
content: unknown;
created_at: Generated<Timestamp>;
};
export type Score = {
id: string;
timestamp: Generated<Timestamp>;
project_id: string;
name: string;
value: number | null;
source: ScoreSource;
author_user_id: string | null;
comment: string | null;
trace_id: string;
observation_id: string | null;
config_id: string | null;
string_value: string | null;
queue_id: string | null;
created_at: Generated<Timestamp>;
updated_at: Generated<Timestamp>;
data_type: Generated<ScoreDataType>;
};
export type ScoreConfig = {
id: string;
created_at: Generated<Timestamp>;
@@ -544,25 +518,6 @@ export type SsoConfig = {
auth_provider: string;
auth_config: unknown | null;
};
export type Trace = {
id: string;
external_id: string | null;
timestamp: Generated<Timestamp>;
name: string | null;
user_id: string | null;
metadata: unknown | null;
release: string | null;
version: string | null;
project_id: string;
public: Generated<boolean>;
bookmarked: Generated<boolean>;
tags: Generated<string[]>;
input: unknown | null;
output: unknown | null;
session_id: string | null;
created_at: Generated<Timestamp>;
updated_at: Generated<Timestamp>;
};
export type TraceMedia = {
id: string;
project_id: string;
@@ -579,26 +534,7 @@ export type TraceSession = {
project_id: string;
bookmarked: Generated<boolean>;
public: Generated<boolean>;
};
export type TraceView = {
id: string;
external_id: string | null;
timestamp: Generated<Timestamp>;
name: string | null;
user_id: string | null;
metadata: unknown | null;
release: string | null;
version: string | null;
project_id: string;
public: Generated<boolean>;
bookmarked: Generated<boolean>;
tags: Generated<string[]>;
input: unknown | null;
output: unknown | null;
session_id: string | null;
created_at: Timestamp;
updated_at: Timestamp;
duration: number | null;
environment: Generated<string>;
};
export type User = {
id: string;
@@ -633,7 +569,6 @@ export type DB = {
dataset_runs: DatasetRuns;
datasets: Dataset;
eval_templates: EvalTemplate;
events: Events;
job_configurations: JobConfiguration;
job_executions: JobExecution;
llm_api_keys: LlmApiKeys;
@@ -641,8 +576,7 @@ export type DB = {
membership_invitations: MembershipInvitation;
models: Model;
observation_media: ObservationMedia;
observations: Observation;
observations_view: ObservationView;
observations: LegacyPrismaObservation;
organization_memberships: OrganizationMembership;
organizations: Organization;
posthog_integrations: PosthogIntegration;
@@ -652,13 +586,12 @@ export type DB = {
prompts: Prompt;
queue_backups: QueueBackUp;
score_configs: ScoreConfig;
scores: Score;
scores: LegacyPrismaScore;
Session: Session;
sso_configs: SsoConfig;
trace_media: TraceMedia;
trace_sessions: TraceSession;
traces: Trace;
traces_view: TraceView;
traces: LegacyPrismaTrace;
users: User;
verification_tokens: VerificationToken;
};
@@ -0,0 +1 @@
UPDATE "llm_api_keys" SET adapter = 'google-vertex-ai' WHERE adapter = 'vertex-ai';
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "prompts" ADD COLUMN "commit_message" TEXT;
@@ -0,0 +1,20 @@
-- CreateTable
CREATE TABLE "event_log" (
"id" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"bucket_name" TEXT NOT NULL,
"bucket_path" TEXT NOT NULL,
"project_id" TEXT NOT NULL,
"entity_type" TEXT NOT NULL,
"entity_id" TEXT NOT NULL,
"event_id" TEXT NOT NULL,
"trace_id" TEXT,
CONSTRAINT "event_log_pkey" PRIMARY KEY ("id"),
CONSTRAINT "event_log_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
-- CreateIndex
CREATE INDEX "event_log_project_id_entity_type_entity_id_idx" ON "event_log"("project_id", "entity_type", "entity_id");
@@ -0,0 +1,2 @@
-- DropTable
DROP TABLE event_log;
@@ -0,0 +1,2 @@
-- DropTable
DROP TABLE events;
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "job_configurations" ADD COLUMN "time_scope" TEXT[] DEFAULT ARRAY['NEW']::TEXT[];
@@ -0,0 +1,3 @@
-- AlterTable
ALTER TABLE "trace_sessions"
ADD COLUMN "environment" TEXT NOT NULL DEFAULT 'default';
@@ -0,0 +1,2 @@
DROP VIEW IF EXISTS "observations_view";
DROP VIEW IF EXISTS "traces_view";
@@ -1,3 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"
+95 -197
View File
@@ -3,7 +3,7 @@
generator client {
provider = "prisma-client-js"
previewFeatures = ["tracing", "views", "relationJoins", "metrics"]
previewFeatures = ["views", "relationJoins", "metrics"]
}
datasource db {
@@ -109,20 +109,17 @@ model Organization {
}
model Project {
id String @id @default(cuid())
orgId String @map("org_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
deletedAt DateTime? @map("deleted_at")
id String @id @default(cuid())
orgId String @map("org_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
deletedAt DateTime? @map("deleted_at")
name String
retentionDays Int? @map("retention_days")
retentionDays Int? @map("retention_days")
projectMembers ProjectMembership[]
organization Organization @relation(fields: [orgId], references: [id], onUpdate: Cascade, onDelete: Cascade)
traces Trace[]
observations Observation[]
organization Organization @relation(fields: [orgId], references: [id], onUpdate: Cascade, onDelete: Cascade)
apiKeys ApiKey[]
dataset Dataset[]
RawEvents Events[]
invitations MembershipInvitation[]
sessions TraceSession[]
Prompt Prompt[]
@@ -132,7 +129,6 @@ model Project {
JobExecution JobExecution[]
LlmApiKeys LlmApiKeys[]
PosthogIntegration PosthogIntegration[]
Score Score[]
scoreConfig ScoreConfig[]
BatchExport BatchExport[]
comment Comment[]
@@ -141,6 +137,9 @@ model Project {
TraceMedia TraceMedia[]
Media Media[]
ObservationMedia ObservationMedia[]
LegacyTrace LegacyPrismaTrace[]
LegacyObservation LegacyPrismaObservation[]
LegacyScore LegacyPrismaScore[]
@@index([orgId])
@@map("projects")
@@ -268,13 +267,14 @@ enum Role {
}
model TraceSession {
id String @default(cuid())
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
projectId String @map("project_id")
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
bookmarked Boolean @default(false)
public Boolean @default(false)
id String @default(cuid())
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
projectId String @map("project_id")
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
bookmarked Boolean @default(false)
public Boolean @default(false)
environment String @default("default")
@@id([id, projectId])
@@index([projectId])
@@ -283,9 +283,7 @@ model TraceSession {
@@map("trace_sessions")
}
// Update TraceView below when making changes to this model!
model Trace {
model LegacyPrismaTrace {
id String @id @default(cuid())
externalId String? @map("external_id")
timestamp DateTime @default(now())
@@ -295,7 +293,6 @@ model Trace {
release String?
version String?
projectId String @map("project_id")
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
public Boolean @default(false)
bookmarked Boolean @default(false)
tags String[] @default([])
@@ -304,6 +301,7 @@ model Trace {
sessionId String? @map("session_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
project Project @relation(fields: [projectId], references: [id])
@@index([projectId, timestamp])
@@index([sessionId])
@@ -316,80 +314,43 @@ model Trace {
@@map("traces")
}
// This view is based on the trace table. Once prisma supports
// inheritance, we should remove code duplication here.
view TraceView {
// trace fields
id String @id @default(cuid())
externalId String? @map("external_id")
timestamp DateTime @default(now())
name String?
userId String? @map("user_id")
metadata Json?
release String?
version String?
projectId String @map("project_id")
public Boolean @default(false)
bookmarked Boolean @default(false)
tags String[] @default([])
input Json?
output Json?
sessionId String? @map("session_id")
createdAt DateTime @map("created_at")
updatedAt DateTime @map("updated_at")
// calculated fields
duration Float? @map("duration") // can be null if no observations in trace
@@map("traces_view")
}
// Update ObservationView below when making changes to this model!
// traceId is optional only due to timing during data injestion
// (traceId is not necessarily known at the time of observation creation)
model Observation {
id String @id @default(cuid())
traceId String? @map("trace_id")
projectId String @map("project_id")
type ObservationType
startTime DateTime @default(now()) @map("start_time")
endTime DateTime? @map("end_time")
name String?
metadata Json?
parentObservationId String? @map("parent_observation_id")
level ObservationLevel @default(DEFAULT)
statusMessage String? @map("status_message")
version String?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
model LegacyPrismaObservation {
id String @id @default(cuid())
traceId String? @map("trace_id")
projectId String @map("project_id")
type LegacyPrismaObservationType
startTime DateTime @default(now()) @map("start_time")
endTime DateTime? @map("end_time")
name String?
metadata Json?
parentObservationId String? @map("parent_observation_id")
level LegacyPrismaObservationLevel @default(DEFAULT)
statusMessage String? @map("status_message")
version String?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
// GENERATION ONLY
model String? // user-provided model attribute
internalModel String? @map("internal_model") // matched model.name that is matched at ingestion time, to be deprecated
internalModelId String? @map("internal_model_id") // matched model.id that is matched at ingestion time
modelParameters Json?
input Json?
output Json?
promptTokens Int @default(0) @map("prompt_tokens")
completionTokens Int @default(0) @map("completion_tokens")
totalTokens Int @default(0) @map("total_tokens")
unit String?
model String? // user-provided model attribute
internalModel String? @map("internal_model") // matched model.name that is matched at ingestion time, to be deprecated
internalModelId String? @map("internal_model_id") // matched model.id that is matched at ingestion time
modelParameters Json?
input Json?
output Json?
promptTokens Int @default(0) @map("prompt_tokens")
completionTokens Int @default(0) @map("completion_tokens")
totalTokens Int @default(0) @map("total_tokens")
unit String?
// User provided cost at ingestion
inputCost Decimal? @map("input_cost")
outputCost Decimal? @map("output_cost")
totalCost Decimal? @map("total_cost")
inputCost Decimal? @map("input_cost")
outputCost Decimal? @map("output_cost")
totalCost Decimal? @map("total_cost")
// Calculated cost
calculatedInputCost Decimal? @map("calculated_input_cost")
calculatedOutputCost Decimal? @map("calculated_output_cost")
calculatedTotalCost Decimal? @map("calculated_total_cost")
completionStartTime DateTime? @map("completion_start_time")
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
promptId String? @map("prompt_id") // no fk constraint, prompt can be deleted
calculatedInputCost Decimal? @map("calculated_input_cost")
calculatedOutputCost Decimal? @map("calculated_output_cost")
calculatedTotalCost Decimal? @map("calculated_total_cost")
completionStartTime DateTime? @map("completion_start_time")
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
promptId String? @map("prompt_id") // no fk constraint, prompt can be deleted
@@unique([id, projectId])
@@index([projectId, internalModel, startTime, unit])
@@ -406,88 +367,38 @@ model Observation {
@@map("observations")
}
// This view is a mix of the observation and model. Once prisma supports
// inheritance, we should remove code duplication here.
view ObservationView {
id String @id @default(cuid())
traceId String? @map("trace_id")
projectId String @map("project_id")
type ObservationType
startTime DateTime @map("start_time")
endTime DateTime? @map("end_time")
name String?
metadata Json?
parentObservationId String? @map("parent_observation_id")
level ObservationLevel @default(DEFAULT)
statusMessage String? @map("status_message")
version String?
createdAt DateTime @map("created_at")
updatedAt DateTime @map("updated_at")
// GENERATION ONLY
model String?
modelParameters Json?
input Json?
output Json?
promptTokens Int @default(0) @map("prompt_tokens")
completionTokens Int @default(0) @map("completion_tokens")
totalTokens Int @default(0) @map("total_tokens")
unit String?
completionStartTime DateTime? @map("completion_start_time")
// prompts
promptId String? @map("prompt_id")
promptName String? @map("prompt_name")
promptVersion Int? @map("prompt_version")
// model fields
modelId String? @map("model_id")
inputPrice Decimal? @map("input_price")
outputPrice Decimal? @map("output_price")
totalPrice Decimal? @map("total_price")
// calculated fields
calculatedInputCost Decimal? @map("calculated_input_cost")
calculatedOutputCost Decimal? @map("calculated_output_cost")
calculatedTotalCost Decimal? @map("calculated_total_cost")
latency Float? @map("latency")
timeToFirstToken Float? @map("time_to_first_token")
@@map("observations_view")
}
enum ObservationType {
enum LegacyPrismaObservationType {
SPAN
EVENT
GENERATION
}
enum ObservationLevel {
enum LegacyPrismaObservationLevel {
DEBUG
DEFAULT
WARNING
ERROR
}
model Score {
id String @id @default(cuid())
timestamp DateTime @default(now())
projectId String @map("project_id")
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
model LegacyPrismaScore {
id String @id @default(cuid())
timestamp DateTime @default(now())
projectId String @map("project_id")
name String
value Float? // always defined if data type is NUMERIC or BOOLEAN, optional for CATEGORICAL
source ScoreSource
authorUserId String? @map("author_user_id")
source LegacyPrismaScoreSource
authorUserId String? @map("author_user_id")
comment String?
traceId String @map("trace_id")
observationId String? @map("observation_id")
configId String? @map("config_id")
stringValue String? @map("string_value") // always defined if data type is CATEGORICAL or BOOLEAN, null for NUMERIC
queueId String? @map("queue_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
dataType ScoreDataType @default(NUMERIC) @map("data_type")
scoreConfig ScoreConfig? @relation(fields: [configId], references: [id], onDelete: SetNull)
traceId String @map("trace_id")
observationId String? @map("observation_id")
configId String? @map("config_id")
stringValue String? @map("string_value") // always defined if data type is CATEGORICAL or BOOLEAN, null for NUMERIC
queueId String? @map("queue_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
dataType ScoreDataType @default(NUMERIC) @map("data_type")
scoreConfig ScoreConfig? @relation(fields: [configId], references: [id], onDelete: SetNull)
project Project @relation(fields: [projectId], references: [id])
@@unique([id, projectId]) // used for upserts via prisma
@@index(timestamp)
@@ -502,26 +413,26 @@ model Score {
@@map("scores")
}
enum ScoreSource {
enum LegacyPrismaScoreSource {
ANNOTATION
API
EVAL
}
model ScoreConfig {
id String @id @default(cuid())
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
projectId String @map("project_id")
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
id String @id @default(cuid())
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
projectId String @map("project_id")
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
name String
dataType ScoreDataType @map("data_type")
isArchived Boolean @default(false) @map("is_archived")
minValue Float? @map("min_value")
maxValue Float? @map("max_value")
categories Json? @map("categories")
dataType ScoreDataType @map("data_type")
isArchived Boolean @default(false) @map("is_archived")
minValue Float? @map("min_value")
maxValue Float? @map("max_value")
categories Json? @map("categories")
description String?
score Score[]
legacyScore LegacyPrismaScore[]
@@unique([id, projectId]) // used for upserts via prisma
@@index([dataType])
@@ -691,21 +602,6 @@ model DatasetRunItems {
@@map("dataset_run_items")
}
model Events {
id String @id @default(cuid())
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
projectId String @map("project_id")
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
data Json
headers Json @default("{}")
url String?
method String?
@@index(projectId)
@@map("events")
}
model Comment {
id String @id @default(cuid())
projectId String @map("project_id")
@@ -738,14 +634,15 @@ model Prompt {
createdBy String @map("created_by")
prompt Json
name String
version Int
type String @default("text")
isActive Boolean? @map("is_active") // Deprecated. To be removed once 'production' labels work as expected.
config Json @default("{}") @db.Json
tags String[] @default([])
labels String[] @default([])
prompt Json
name String
version Int
type String @default("text")
isActive Boolean? @map("is_active") // Deprecated. To be removed once 'production' labels work as expected.
config Json @default("{}") @db.Json
tags String[] @default([])
labels String[] @default([])
commitMessage String? @map("commit_message")
@@unique([projectId, name, version])
@@index([projectId, id])
@@ -868,6 +765,7 @@ model JobConfiguration {
variableMapping Json @map("variable_mapping")
sampling Decimal // ratio of jobs that are executed for sampling (0..1)
delay Int // delay in milliseconds
timeScope String[] @default(["NEW"]) @map("time_scope")
JobExecution JobExecution[]
@@index([projectId, id])
+27 -115
View File
@@ -2,8 +2,6 @@ import {
PrismaClient,
type Project,
type Prisma,
ObservationType,
ScoreSource,
ScoreDataType,
AnnotationQueueObjectType,
} from "../src/index";
@@ -97,7 +95,7 @@ async function main() {
},
});
const orgMembership = await prisma.organizationMembership.upsert({
await prisma.organizationMembership.upsert({
where: {
orgId_userId: {
userId: user.id,
@@ -127,7 +125,7 @@ async function main() {
update: {},
});
const projectMembership = await prisma.projectMembership.upsert({
await prisma.projectMembership.upsert({
where: {
projectId_userId: {
projectId: project1.id,
@@ -266,38 +264,23 @@ async function main() {
const traceVolume = environment === "load" ? LOAD_TRACE_VOLUME : 100;
const {
traces,
observations,
scores,
sessions,
events,
comments,
queueItems,
} = createObjects(
traceVolume,
envTags,
colorTags,
project1,
project2,
promptIds,
queueIds,
configIdsAndNames,
);
const { traces, observations, scores, sessions, comments, queueItems } =
createObjects(
traceVolume,
envTags,
colorTags,
project1,
project2,
promptIds,
queueIds,
configIdsAndNames,
);
logger.info(
`Seeding ${traces.length} traces, ${observations.length} observations, and ${scores.length} scores`,
);
await uploadObjects(
traces,
observations,
scores,
sessions,
events,
comments,
queueItems,
);
await uploadObjects(sessions, comments, queueItems);
// If openai key is in environment, add it to the projects LLM API keys
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
@@ -420,7 +403,7 @@ export async function createDatasets(
updatedAt: Date;
name: string;
},
observations: Prisma.ObservationCreateManyInput[],
observations: { id?: string; projectId?: string; traceId?: string | null }[],
) {
for (let datasetNumber = 0; datasetNumber < 2; datasetNumber++) {
for (const projectId of [project1.id, project2.id]) {
@@ -532,11 +515,7 @@ export async function createDatasets(
}
async function uploadObjects(
traces: Prisma.TraceCreateManyInput[],
observations: Prisma.ObservationCreateManyInput[],
scores: Prisma.ScoreCreateManyInput[],
sessions: Prisma.TraceSessionCreateManyInput[],
events: Prisma.ObservationCreateManyInput[],
comments: Prisma.CommentCreateManyInput[],
queueItems: Prisma.AnnotationQueueItemCreateManyInput[],
) {
@@ -564,73 +543,6 @@ async function uploadObjects(
await promises[i];
}
promises = [];
chunk(traces, chunkSize).forEach((chunk) => {
promises.push(
prisma.trace.createMany({
data: chunk,
}),
);
});
for (let i = 0; i < promises.length; i++) {
if (i + 1 >= promises.length || i % Math.ceil(promises.length / 10) === 0)
logger.info(
`Seeding of Traces ${((i + 1) / promises.length) * 100}% complete`,
);
await promises[i];
}
promises = [];
chunk(observations, chunkSize).forEach((chunk) => {
promises.push(
prisma.observation.createMany({
data: chunk,
}),
);
});
for (let i = 0; i < promises.length; i++) {
if (i + 1 >= promises.length || i % Math.ceil(promises.length / 10) === 0)
logger.info(
`Seeding of Observations ${((i + 1) / promises.length) * 100}% complete`,
);
await promises[i];
}
promises = [];
chunk(events, chunkSize).forEach((chunk) => {
promises.push(
prisma.observation.createMany({
data: chunk,
}),
);
});
for (let i = 0; i < promises.length; i++) {
if (i + 1 >= promises.length || i % Math.ceil(promises.length / 10) === 0)
logger.info(
`Seeding of Events ${((i + 1) / promises.length) * 100}% complete`,
);
await promises[i];
}
promises = [];
chunk(scores, chunkSize).forEach((chunk) => {
promises.push(
prisma.score.createMany({
data: chunk,
}),
);
});
for (let i = 0; i < promises.length; i++) {
if (i + 1 >= promises.length || i % Math.ceil(promises.length / 10) === 0)
logger.info(
`Seeding of Scores ${((i + 1) / promises.length) * 100}% complete`,
);
await promises[i];
}
promises = [];
chunk(comments, chunkSize).forEach((chunk) => {
promises.push(
@@ -682,11 +594,11 @@ function createObjects(
}[]
>,
) {
const traces: Prisma.TraceCreateManyInput[] = [];
const observations: Prisma.ObservationCreateManyInput[] = [];
const scores: Prisma.ScoreCreateManyInput[] = [];
const traces: any[] = [];
const observations: any[] = [];
const scores: any[] = [];
const sessions: Prisma.TraceSessionCreateManyInput[] = [];
const events: Prisma.ObservationCreateManyInput[] = [];
const events: any[] = [];
const configs: Prisma.ScoreConfigCreateManyInput[] = [];
const comments: Prisma.CommentCreateManyInput[] = [];
const queueItems: Prisma.AnnotationQueueItemCreateManyInput[] = [];
@@ -795,7 +707,7 @@ function createObjects(
name: annotationScoreName,
timestamp: traceTs,
createdAt: traceTs,
source: ScoreSource.ANNOTATION,
source: "ANNOTATION",
projectId,
authorUserId: `user-${i}`,
dataType,
@@ -812,7 +724,7 @@ function createObjects(
value: Math.floor(Math.random() * 10) - 5,
timestamp: traceTs,
createdAt: traceTs,
source: ScoreSource.API,
source: "API",
projectId,
dataType: ScoreDataType.NUMERIC,
},
@@ -825,7 +737,7 @@ function createObjects(
name: "Completeness",
timestamp: traceTs,
createdAt: traceTs,
source: ScoreSource.API,
source: "API",
projectId,
dataType: ScoreDataType.CATEGORICAL,
stringValue:
@@ -859,7 +771,7 @@ function createObjects(
);
const span = {
type: ObservationType.SPAN,
type: "SPAN",
id: `span-${v4()}`,
startTime: spanTsStart,
createdAt: spanTsStart,
@@ -933,7 +845,7 @@ function createObjects(
const { input, output } = getGenerationInputOutput();
const generation = {
type: ObservationType.GENERATION,
type: "GENERATION",
id: `generation-${v4()}`,
startTime: generationTsStart,
createdAt: generationTsStart,
@@ -978,7 +890,7 @@ function createObjects(
value: Math.random() * 2 - 1,
observationId: generation.id,
traceId: trace.id,
source: ScoreSource.API,
source: "API",
projectId: trace.projectId,
timestamp: generationTsEnd,
createdAt: traceTs,
@@ -989,7 +901,7 @@ function createObjects(
value: Math.random() * 2 - 1,
observationId: generation.id,
traceId: trace.id,
source: ScoreSource.API,
source: "API",
projectId: trace.projectId,
timestamp: generationTsEnd,
createdAt: traceTs,
@@ -1013,7 +925,7 @@ function createObjects(
);
events.push({
type: ObservationType.EVENT,
type: "EVENT",
id: `event-${v4()}`,
startTime: eventTs,
createdAt: eventTs,
+1 -7
View File
@@ -1,11 +1,6 @@
import { randomUUID } from "crypto";
import { prisma } from "../src/db";
import {
clickhouseClient,
getDisplaySecretKey,
hashSecretKey,
logger,
} from "../src/server";
import { getDisplaySecretKey, hashSecretKey, logger } from "../src/server";
import { prepareClickhouse } from "./prepareClickhouse";
import { redis } from "../src/server";
@@ -124,7 +119,6 @@ async function main() {
} catch (error) {
logger.error("Error during Clickhouse preparation:", error);
} finally {
await clickhouseClient().close();
await prisma.$disconnect();
redis?.disconnect();
logger.info("Disconnected from Clickhouse.");
+11 -12
View File
@@ -67,6 +67,7 @@ export const prepareClickhouse = async (
concat('release_', toString(randUniform(0, 100))) AS release,
concat('version_', toString(randUniform(0, 100))) AS version,
'${projectId}' AS project_id,
'default' AS environment,
if(rand() < 0.8, true, false) as public,
if(rand() < 0.8, true, false) as bookmarked,
array('tag1', 'tag2') as tags,
@@ -85,6 +86,7 @@ export const prepareClickhouse = async (
SELECT toString(number) AS id,
toString(floor(randUniform(0, ${tracesPerProject}))) AS trace_id,
'${projectId}' AS project_id,
'default' AS environment,
if(randUniform(0, 1) < 0.47, 'GENERATION', if(randUniform(0, 1) < 0.94, 'SPAN', 'EVENT')) AS type,
toString(rand()) AS parent_observation_id,
toDateTime(now() - randUniform(0, ${opts.numberOfDays} * 24 * 60 * 60)) AS start_time,
@@ -96,18 +98,14 @@ export const prepareClickhouse = async (
'version' AS version,
repeat('input', toInt64(randExponential(1 / 100))) AS input,
repeat('output', toInt64(randExponential(1 / 100))) AS output,
if("type" = 'GENERATION',
case
when number % 2 = 0 then 'claude-3-haiku-20240307'
else 'gpt-4'
end,
NULL) as provided_model_name,
if("type" = 'GENERATION',
case
when number % 2 = 0 then 'cltr0w45b000008k1407o9qv1'
else 'clrntkjgy000f08jx79v9g1xj'
end,
NULL) as internal_model_id,
case
when number % 2 = 0 then 'clause-3-haiku-20230407'
else 'gpt-4'
end as provided_model_name,
case
when number % 2 = 0 then 'cltra4wbs0000k1407g0ya3'
else '1cmtk9y0000y3y79x9jgxj'
end as internal_model_id,
if("type" = 'GENERATION',
'{"temperature": 0.7, "max_tokens": 150}',
'{}') AS model_parameters,
@@ -150,6 +148,7 @@ export const prepareClickhouse = async (
SELECT toString(floor(randUniform(0, 100))) AS id,
toDateTime(now() - randUniform(0, ${opts.numberOfDays} * 24 * 60 * 60)) AS timestamp,
'${projectId}' AS project_id,
'default' AS environment,
toString(floor(randUniform(0, ${tracesPerProject}))) AS trace_id,
if(
rand() > 0.9,
+4
View File
@@ -18,6 +18,10 @@ const EnvSchema = z.object({
.nullable(),
REDIS_AUTH: z.string().nullish(),
REDIS_CONNECTION_STRING: z.string().nullish(),
REDIS_TLS_ENABLED: z.enum(["true", "false"]).default("false"),
REDIS_TLS_CA_PATH: z.string().optional(),
REDIS_TLS_CERT_PATH: z.string().optional(),
REDIS_TLS_KEY_PATH: z.string().optional(),
REDIS_ENABLE_AUTO_PIPELINING: z.enum(["true", "false"]).default("true"),
ENCRYPTION_KEY: z
.string()
@@ -28,6 +28,7 @@ const BooleanData = z.object({
const CreateAnnotationScoreBase = z.object({
name: z.string(),
projectId: z.string(),
environment: z.string().default("default"),
traceId: z.string(),
configId: z.string().optional(),
observationId: z.string().optional(),
@@ -0,0 +1,38 @@
import z from "zod";
import { singleFilter } from "../../interfaces/filters";
import { orderBy } from "../../interfaces/orderBy";
import { BatchExportTableName } from "../batchExport/types";
/* eslint-disable no-unused-vars */
export enum BatchActionType {
Create = "create",
Delete = "delete",
}
const ActionIdSchema = z.enum([
"trace-delete",
"trace-add-to-annotation-queue",
]);
export type ActionId = z.infer<typeof ActionIdSchema>;
export const BatchActionQuerySchema = z.object({
filter: z.array(singleFilter).nullable(),
orderBy,
});
export type BatchActionQuery = z.infer<typeof BatchActionQuerySchema>;
export const CreateBatchActionSchema = z.object({
projectId: z.string(),
actionId: ActionIdSchema,
targetId: z.string().optional(),
query: BatchActionQuerySchema,
tableName: z.nativeEnum(BatchExportTableName),
});
export const GetIsBatchActionInProgressSchema = z.object({
projectId: z.string(),
actionId: ActionIdSchema,
tableName: z.nativeEnum(BatchExportTableName),
});
@@ -21,6 +21,7 @@ export enum BatchExportTableName {
Sessions = "sessions",
Traces = "traces",
Generations = "generations",
DatasetRunItems = "dataset_run_items",
}
export const exportOptions: Record<
+7 -5
View File
@@ -17,6 +17,7 @@ export const variableMapping = z
objectName: z.string().nullish(),
langfuseObject: z.enum(langfuseObjects),
selectedColumnId: z.string(),
jsonSelector: z.string().nullish(),
})
.refine(
(value) => value.langfuseObject === "trace" || value.objectName !== null,
@@ -32,6 +33,7 @@ export const wipVariableMapping = z.object({
objectName: z.string().nullish(),
langfuseObject: z.enum(langfuseObjects),
selectedColumnId: z.string().nullish(),
jsonSelector: z.string().nullish(),
});
const observationCols = [
@@ -104,9 +106,9 @@ export const OutputSchema = z.object({
score: z.string(),
});
export enum EvalTargetObject {
Trace = "trace",
Dataset = "dataset",
}
export const DEFAULT_TRACE_JOB_DELAY = 10_000;
export const JobTimeScopeZod = z.enum(["NEW", "EXISTING"]);
export type JobTimeScope = z.infer<typeof JobTimeScopeZod>;
export const TimeScopeSchema = z.array(JobTimeScopeZod).default(["NEW"]);
@@ -1,8 +1,7 @@
import { z } from "zod";
import { Score } from "@prisma/client";
import { isPresent, stringDateTime } from "../../utils/typeChecks";
import { Score } from "../../server";
import {
NonEmptyString,
paginationMetaResponseZod,
@@ -46,6 +45,7 @@ const ScoreBase = z.object({
id: z.string(),
timestamp: z.coerce.date(),
projectId: z.string(),
environment: z.string().default("default"),
name: z.string(),
source: z.enum(ScoreSource),
authorUserId: z.string().nullish(),
+3 -2
View File
@@ -1,4 +1,5 @@
import { ScoreDataType, ScoreSource } from "@prisma/client";
import { ScoreDataType } from "@prisma/client";
import { ScoreSourceType } from "../../server";
export type CategoricalAggregate = {
type: "CATEGORICAL";
@@ -22,7 +23,7 @@ export type ScoreAggregate = Record<
export type ScoreSimplified = {
name: string;
dataType: ScoreDataType;
source: ScoreSource;
source: ScoreSourceType;
value?: number | null;
comment?: string | null;
stringValue?: string | null;
+4
View File
@@ -21,7 +21,10 @@ export * from "./server/llm/types";
// evals
export * from "./features/evals/types";
// table actions
export * from "./features/batchExport/types";
export * from "./features/batchAction/types";
// annotation
export * from "./features/annotation/types";
@@ -38,6 +41,7 @@ export * from "./features/experiments/utils";
// export db types only
export * from "@prisma/client";
export { type DB } from "../prisma/generated/types";
export * from "./server/repositories/types";
// errors
export * from "./errors/index";
+8 -3
View File
@@ -1,8 +1,8 @@
import { ObservationLevel } from "@prisma/client";
import {
type OptionsDefinition,
type ColumnDefinition,
} from "./tableDefinitions/types";
} from "./tableDefinitions";
import { ObservationLevelType } from "./server";
// to be used server side
export const observationsTableCols: ColumnDefinition[] = [
@@ -102,7 +102,12 @@ export const observationsTableCols: ColumnDefinition[] = [
id: "level",
type: "stringOptions",
internal: 'o."level"::text',
options: Object.values(ObservationLevel).map((value) => ({ value })),
options: [
{ value: "DEBUG" },
{ value: "DEFAULT" },
{ value: "WARNING" },
{ value: "ERROR" },
] as { value: ObservationLevelType }[],
},
{
name: "Status Message",
@@ -1,27 +1,41 @@
import { createClient } from "@clickhouse/client";
import { env } from "../../env";
import { NodeClickHouseClientConfigOptions } from "@clickhouse/client/dist/config";
import { getCurrentSpan } from "../instrumentation";
import { propagation, context } from "@opentelemetry/api";
export type ClickhouseClientType = ReturnType<typeof createClient>;
export const clickhouseClient = (opts?: NodeClickHouseClientConfigOptions) =>
createClient({
...opts,
export const clickhouseClient = (
params: {
tags?: Record<string, string>;
opts?: NodeClickHouseClientConfigOptions;
} = {},
) => {
const headers = params.opts?.http_headers ?? {};
const activeSpan = getCurrentSpan();
if (activeSpan) {
propagation.inject(context.active(), headers);
}
return createClient({
...params.opts,
url: env.CLICKHOUSE_URL,
username: env.CLICKHOUSE_USER,
password: env.CLICKHOUSE_PASSWORD,
database: env.CLICKHOUSE_DB,
http_headers: headers,
clickhouse_settings: {
log_comment: JSON.stringify(params.tags ?? {}),
async_insert: 1,
wait_for_async_insert: 1, // if disabled, we won't get errors from clickhouse
},
});
};
export const defaultClickhouseClient = clickhouseClient();
/**
* Accepts a JavaScript date and returns the DateTime in format YYYY-MM-DD HH:MM:SS
*/
export const convertDateToClickhouseDateTime = (date: Date): string => {
// 2024-11-06T20:37:00.123Z -> 2024-11-06 21:37:00.123
return date.toISOString().replace("T", " ").replace("Z", "");
+2
View File
@@ -23,12 +23,14 @@ export * from "../server/ingestion/types";
export * from "../server/ingestion/validateAndInflateScore";
export * from "./redis/redis";
export * from "./redis/traceUpsert";
export * from "./redis/createEvalQueue";
export * from "./redis/cloudUsageMeteringQueue";
export * from "./redis/getQueue";
export * from "./redis/traceDelete";
export * from "./redis/projectDelete";
export * from "./redis/datasetRunItemUpsert";
export * from "./redis/batchExport";
export * from "./redis/batchActionQueue";
export * from "./redis/ingestionQueue";
export * from "./redis/postHogIntegrationQueue";
export * from "./redis/postHogIntegrationProcessingQueue";
@@ -1,5 +1,6 @@
import { Model, Observation, Prisma } from "@prisma/client";
import { Model, Prisma } from "@prisma/client";
import { prisma } from "../../db";
import { Observation } from "../repositories";
export async function findModel(p: {
event: {
@@ -4,7 +4,6 @@ import { z } from "zod";
import { type Model } from "../../db";
import { env } from "../../env";
import {
ForbiddenError,
InvalidRequestError,
LangfuseNotFoundError,
UnauthorizedError,
@@ -15,6 +14,7 @@ import {
getCurrentSpan,
instrumentAsync,
instrumentSync,
recordDistribution,
recordIncrement,
traceException,
} from "../instrumentation";
@@ -22,16 +22,11 @@ import { logger } from "../logger";
import { QueueJobs } from "../queues";
import { IngestionQueue } from "../redis/ingestionQueue";
import { redis } from "../redis/redis";
import { eventTypes, ingestionEvent, IngestionEventType } from "./types";
import {
StorageService,
StorageServiceFactory,
} from "../services/StorageService";
import { eventTypes, ingestionEvent, IngestionEventType } from "./types";
export type TokenCountDelegate = (p: {
model: Model;
text: unknown;
}) => number | undefined;
let s3StorageServiceClient: StorageService;
@@ -49,9 +44,45 @@ const getS3StorageServiceClient = (bucketName: string): StorageService => {
return s3StorageServiceClient;
};
export type TokenCountDelegate = (p: {
model: Model;
text: unknown;
}) => number | undefined;
/**
* Get the delay for the event based on the event type. Uses delay if set, 0 if current UTC timestamp is not between
* 23:45 and 00:15, and env.LANGFUSE_INGESTION_QUEUE_DELAY_MS otherwise.
* We need the delay around date boundaries to avoid duplicates for out-of-order processing of events.
* @param delay - Delay overwrite. Used if non-null.
*/
const getDelay = (delay: number | null) => {
if (delay !== null) {
return delay;
}
const now = new Date();
const hours = now.getUTCHours();
const minutes = now.getUTCMinutes();
if ((hours === 23 && minutes >= 45) || (hours === 0 && minutes <= 15)) {
return env.LANGFUSE_INGESTION_QUEUE_DELAY_MS;
}
// Use 5s here to avoid duplicate processing on the worker. If the ingestion delay is set to a lower value,
// we use this instead.
// Values should be revisited based on a cost/performance trade-off.
return Math.min(5000, env.LANGFUSE_INGESTION_QUEUE_DELAY_MS);
};
/**
* Processes a batch of events.
* @param input - Batch of IngestionEventType. Will validate the types first thing and return errors if they are invalid.
* @param authCheck - AuthHeaderValidVerificationResult
* @param delay - (Optional) Delay in ms to wait before processing events in the batch.
*/
export const processEventBatch = async (
input: unknown[],
authCheck: AuthHeaderValidVerificationResult,
delay: number | null = null,
): Promise<{
successes: { id: string; status: number }[];
errors: {
@@ -64,7 +95,12 @@ export const processEventBatch = async (
// add context of api call to the span
const currentSpan = getCurrentSpan();
recordIncrement("langfuse.ingestion.event", input.length);
currentSpan?.setAttribute("event_count", input.length);
recordDistribution("langfuse.ingestion.event_distribution", input.length);
currentSpan?.setAttribute("langfuse.ingestion.batch_size", input.length);
currentSpan?.setAttribute("langfuse.project.id", authCheck.scope.projectId);
currentSpan?.setAttribute("langfuse.org.id", authCheck.scope.orgId);
currentSpan?.setAttribute("langfuse.org.plan", authCheck.scope.plan);
/**************
* VALIDATION *
@@ -79,7 +115,10 @@ export const processEventBatch = async (
(span) => {
const parsedBody = ingestionEvent.safeParse(event);
if (parsedBody.data?.id !== undefined) {
span.setAttribute("object.id", parsedBody.data.id);
span.setAttribute(
"langfuse.ingestion.entity.id",
parsedBody.data.id,
);
}
return parsedBody;
},
@@ -154,9 +193,6 @@ export const processEventBatch = async (
********************/
let s3UploadErrored = false;
await instrumentAsync({ name: "s3-upload-events" }, async () => {
const s3Client = getS3StorageServiceClient(
env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
);
// S3 Event Upload is blocking, but non-failing.
// If a promise rejects, we log it below, but do not throw an error.
// In this case, we upload the full batch into the Redis queue.
@@ -166,10 +202,10 @@ export const processEventBatch = async (
// That way we batch updates from the same invocation into a single file and reduce
// write operations on S3.
const { data, key, type, eventBodyId } = sortedBatchByEventBodyId[id];
return s3Client.uploadJson(
`${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${authCheck.scope.projectId}/${getClickhouseEntityType(type)}/${eventBodyId}/${key}.json`,
data,
);
const bucketPath = `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${authCheck.scope.projectId}/${getClickhouseEntityType(type)}/${eventBodyId}/${key}.json`;
return getS3StorageServiceClient(
env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
).uploadJson(bucketPath, data);
}),
);
results.forEach((result) => {
@@ -207,13 +243,12 @@ export const processEventBatch = async (
data: {
type: sortedBatchByEventBodyId[id].type,
eventBodyId: sortedBatchByEventBodyId[id].eventBodyId,
fileKey: sortedBatchByEventBodyId[id].key,
},
authCheck,
},
},
{
delay: env.LANGFUSE_INGESTION_QUEUE_DELAY_MS,
},
{ delay: getDelay(delay) },
)
: Promise.reject("Failed to instantiate queue"),
),
+24 -35
View File
@@ -3,7 +3,9 @@ import { z } from "zod";
import { NonEmptyString, jsonSchema } from "../../utils/zod";
import { ModelUsageUnit } from "../../constants";
import { ObservationLevel, ScoreSource } from "@prisma/client";
import { type ScoreSourceType } from "../repositories";
const ObservationLevel = z.enum(["DEBUG", "DEFAULT", "WARNING", "ERROR"]);
export const Usage = z.object({
input: z.number().int().nullish(),
@@ -116,6 +118,15 @@ export const UsageOrCostDetails = z
.union([OpenAIUsageSchema, RawUsageOrCostDetails])
.nullish();
export const EnvironmentName = z
.string()
.max(40, "Maximum length is 40 characters")
.regex(
/^(?!langfuse)[a-z0-9-_]+$/,
"Only alphanumeric lower case characters, hyphens, and underscores are allowed, and it must not start with 'langfuse'",
)
.default("default");
// Using z.any instead of jsonSchema for input/output as we saw huge CPU overhead for large numeric arrays.
// With this setup parsing should be more lightweight and doesn't block other requests.
// As we allow plain values, arrays, and objects the JSON parse via bodyParser should suffice.
@@ -128,6 +139,7 @@ export const TraceBody = z.object({
output: z.any().nullish(),
sessionId: z.string().nullish(),
userId: z.string().nullish(),
environment: EnvironmentName,
metadata: jsonSchema.nullish(),
release: z.string().nullish(),
version: z.string().nullish(),
@@ -137,12 +149,13 @@ export const TraceBody = z.object({
export const OptionalObservationBody = z.object({
traceId: z.string().nullish(),
environment: EnvironmentName,
name: z.string().nullish(),
startTime: stringDateTime,
metadata: jsonSchema.nullish(),
input: z.any().nullish(),
output: z.any().nullish(),
level: z.nativeEnum(ObservationLevel).nullish(),
level: ObservationLevel.nullish(),
statusMessage: z.string().nullish(),
parentObservationId: z.string().nullish(),
version: z.string().nullish(),
@@ -228,9 +241,12 @@ const BaseScoreBody = z.object({
id: z.string().nullish(),
name: NonEmptyString,
traceId: z.string(),
environment: EnvironmentName,
observationId: z.string().nullish(),
comment: z.string().nullish(),
source: z.nativeEnum(ScoreSource).default(ScoreSource.API),
source: z
.enum(["API", "EVAL", "ANNOTATION"])
.default("API" as ScoreSourceType),
});
/**
@@ -281,7 +297,7 @@ export const LegacySpanPostSchema = z.object({
input: jsonSchema.nullish(),
output: jsonSchema.nullish(),
parentObservationId: z.string().nullish(),
level: z.nativeEnum(ObservationLevel).nullish(),
level: ObservationLevel.nullish(),
statusMessage: z.string().nullish(),
version: z.string().nullish(),
});
@@ -295,7 +311,7 @@ export const LegacySpanPatchSchema = z.object({
metadata: jsonSchema.nullish(),
input: jsonSchema.nullish(),
output: jsonSchema.nullish(),
level: z.nativeEnum(ObservationLevel).nullish(),
level: ObservationLevel.nullish(),
statusMessage: z.string().nullish(),
version: z.string().nullish(),
});
@@ -319,7 +335,7 @@ export const LegacyGenerationsCreateSchema = z.object({
usage: usage,
metadata: jsonSchema.nullish(),
parentObservationId: z.string().nullish(),
level: z.nativeEnum(ObservationLevel).nullish(),
level: ObservationLevel.nullish(),
statusMessage: z.string().nullish(),
version: z.string().nullish(),
});
@@ -342,7 +358,7 @@ export const LegacyGenerationPatchSchema = z.object({
completion: jsonSchema.nullish(),
usage: usage,
metadata: jsonSchema.nullish(),
level: z.nativeEnum(ObservationLevel).nullish(),
level: ObservationLevel.nullish(),
statusMessage: z.string().nullish(),
version: z.string().nullish(),
});
@@ -369,7 +385,7 @@ export const LegacyObservationBody = z.object({
costDetails: UsageOrCostDetails,
metadata: jsonSchema.nullish(),
parentObservationId: z.string().nullish(),
level: z.nativeEnum(ObservationLevel).nullish(),
level: ObservationLevel.nullish(),
statusMessage: z.string().nullish(),
version: z.string().nullish(),
});
@@ -379,18 +395,6 @@ export const SdkLogEvent = z.object({
id: z.string().nullish(), // Not used, but makes downstream processing easier.
});
// definitions for the ingestion API
export const observationTypes = [
"observation-create",
"observation-update",
"generation-create",
"generation-update",
"span-create",
"span-update",
"event-create",
];
export const eventTypes = {
TRACE_CREATE: "trace-create",
SCORE_CREATE: "score-create",
@@ -470,27 +474,12 @@ export const ingestionEvent = z.discriminatedUnion("type", [
export type IngestionEventType = z.infer<typeof ingestionEvent>;
export const ingestionBatchEvent = z.array(ingestionEvent);
export type IngestionBatchEventType = z.infer<typeof ingestionBatchEvent>;
export const ingestionEventWithProjectId = ingestionEvent.and(
z.object({ projectId: z.string() }),
);
export type IngestionEventWithProjectIdType = z.infer<
typeof ingestionEventWithProjectId
>;
export const ingestionApiSchema = z.object({
batch: ingestionBatchEvent,
metadata: jsonSchema.nullish(),
});
export const ingestionApiSchemaWithProjectId = ingestionApiSchema.extend({
projectId: z.string(),
});
export type IngestionApiSchemaWithProjectId = z.infer<
typeof ingestionApiSchemaWithProjectId
>;
export type ObservationEvent =
| z.infer<typeof legacyObservationCreateEvent>
| z.infer<typeof legacyObservationUpdateEvent>
@@ -4,7 +4,8 @@ import {
validateDbScoreConfigSafe,
ValidatedScoreConfig,
} from "../../../src";
import { prisma, Score, ScoreDataType } from "../../db";
import { prisma, ScoreDataType } from "../../db";
import { Score } from "../repositories";
import { InvalidRequestError, LangfuseNotFoundError } from "../../errors";
@@ -1,10 +1,9 @@
import type { ZodSchema } from "zod";
import { CallbackHandler } from "langfuse-langchain";
import { ChatAnthropic } from "@langchain/anthropic";
import { ChatVertexAI } from "@langchain/google-vertexai";
import { ChatBedrockConverse } from "@langchain/aws";
import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
import {
AIMessage,
BaseMessage,
@@ -21,27 +20,20 @@ import GCPServiceAccountKeySchema, {
BedrockConfigSchema,
BedrockCredentialSchema,
} from "../../interfaces/customLLMProviderConfigSchemas";
import { AuthHeaderValidVerificationResult } from "../auth/types";
import {
processEventBatch,
type TokenCountDelegate,
} from "../ingestion/processEventBatch";
import { processEventBatch } from "../ingestion/processEventBatch";
import { logger } from "../logger";
import { ChatMessage, ChatMessageRole, LLMAdapter, ModelParams } from "./types";
import {
ChatMessage,
ChatMessageRole,
LLMAdapter,
ModelParams,
TraceParams,
} from "./types";
import { CallbackHandler } from "langfuse-langchain";
import type { BaseCallbackHandler } from "@langchain/core/callbacks/base";
type ProcessTracedEvents = () => Promise<void>;
export type TraceParams = {
traceName: string;
traceId: string;
projectId: string;
tags: string[];
tokenCountDelegate: TokenCountDelegate;
authCheck: AuthHeaderValidVerificationResult;
};
type LLMCompletionParams = {
messages: ChatMessage[];
modelParams: ModelParams;
@@ -53,6 +45,7 @@ type LLMCompletionParams = {
maxRetries?: number;
config?: Record<string, string> | null;
traceParams?: TraceParams;
throwOnError?: boolean; // default is true
};
type FetchLLMCompletionParams = LLMCompletionParams & {
@@ -102,6 +95,7 @@ export async function fetchLLMCompletion(
config,
traceParams,
extraHeaders,
throwOnError = true,
} = params;
let finalCallbacks: BaseCallbackHandler[] | undefined = callbacks ?? [];
@@ -113,7 +107,6 @@ export async function fetchLLMCompletion(
_isLocalEventExportEnabled: true,
tags: traceParams.tags,
});
finalCallbacks.push(handler);
processTracedEvents = async () => {
@@ -141,7 +134,10 @@ export async function fetchLLMCompletion(
finalMessages = messages.map((message) => {
if (message.role === ChatMessageRole.User)
return new HumanMessage(message.content);
if (message.role === ChatMessageRole.System)
if (
message.role === ChatMessageRole.System ||
message.role === ChatMessageRole.Developer
)
return new SystemMessage(message.content);
return new AIMessage(message.content);
@@ -154,7 +150,8 @@ export async function fetchLLMCompletion(
| ChatOpenAI
| ChatAnthropic
| ChatBedrockConverse
| ChatVertexAI;
| ChatVertexAI
| ChatGoogleGenerativeAI;
if (modelParams.adapter === LLMAdapter.Anthropic) {
chatModel = new ChatAnthropic({
anthropicApiKey: apiKey,
@@ -227,6 +224,16 @@ export async function fetchLLMCompletion(
credentials,
},
});
} else if (modelParams.adapter === LLMAdapter.GoogleAIStudio) {
chatModel = new ChatGoogleGenerativeAI({
model: modelParams.model,
temperature: modelParams.temperature,
maxOutputTokens: modelParams.max_tokens,
topP: modelParams.top_p,
callbacks: finalCallbacks,
maxRetries,
apiKey,
});
} else {
// eslint-disable-next-line no-unused-vars
const _exhaustiveCheck: never = modelParams.adapter;
@@ -239,20 +246,21 @@ export async function fetchLLMCompletion(
runName: traceParams?.traceName,
};
if (params.structuredOutputSchema) {
return {
completion: await (chatModel as ChatOpenAI) // Typecast necessary due to https://github.com/langchain-ai/langchainjs/issues/6795
.withStructuredOutput(params.structuredOutputSchema)
.invoke(finalMessages, runConfig),
processTracedEvents,
};
}
try {
if (params.structuredOutputSchema) {
return {
completion: await (chatModel as ChatOpenAI) // Typecast necessary due to https://github.com/langchain-ai/langchainjs/issues/6795
.withStructuredOutput(params.structuredOutputSchema)
.invoke(finalMessages, runConfig),
processTracedEvents,
};
}
/*
Workaround OpenAI o1 while in beta:
/*
Workaround OpenAI reasoning models:
This is a temporary workaround to avoid sending system messages to OpenAI's O1 models.
O1 models do not support in beta:
This is a temporary workaround to avoid sending unsupported parameters to OpenAI's O1 models.
O1 models do not support:
- system messages
- top_p
- max_tokens at all, one has to use max_completion_tokens instead
@@ -260,43 +268,58 @@ export async function fetchLLMCompletion(
Reference: https://platform.openai.com/docs/guides/reasoning/beta-limitations
*/
if (modelParams.model.startsWith("o1-")) {
return {
completion: await new ChatOpenAI({
openAIApiKey: apiKey,
modelName: modelParams.model,
temperature: 1,
maxTokens: undefined,
topP: undefined,
callbacks,
maxRetries,
configuration: {
baseURL,
},
timeout: 1000 * 60 * 2, // 2 minutes timeout
})
.pipe(new StringOutputParser())
.invoke(
finalMessages.filter((message) => message._getType() !== "system"),
runConfig,
),
processTracedEvents,
};
}
if (
modelParams.model.startsWith("o1-") ||
modelParams.model.startsWith("o3-")
) {
const filteredMessages = finalMessages.filter((message) => {
return (
modelParams.model.startsWith("o3-") || message._getType() !== "system"
);
});
return {
completion: await new ChatOpenAI({
openAIApiKey: apiKey,
modelName: modelParams.model,
temperature: 1,
maxTokens: undefined,
topP: undefined,
callbacks,
maxRetries,
modelKwargs: {
max_completion_tokens: modelParams.max_tokens,
},
configuration: {
baseURL,
},
timeout: 1000 * 60 * 2, // 2 minutes timeout
})
.pipe(new StringOutputParser())
.invoke(filteredMessages, runConfig),
processTracedEvents,
};
}
if (streaming) {
return {
completion: await chatModel
.pipe(new BytesOutputParser())
.stream(finalMessages, runConfig),
processTracedEvents,
};
}
if (streaming) {
return {
completion: await chatModel
.pipe(new BytesOutputParser())
.stream(finalMessages, runConfig),
.pipe(new StringOutputParser())
.invoke(finalMessages, runConfig),
processTracedEvents,
};
} catch (error) {
if (throwOnError) {
throw error;
}
return { completion: null, processTracedEvents };
}
return {
completion: await chatModel
.pipe(new StringOutputParser())
.invoke(finalMessages, runConfig),
processTracedEvents,
};
}
+41 -1
View File
@@ -1,6 +1,11 @@
import { LlmApiKeys } from "@prisma/client";
import z from "zod";
import { BedrockConfigSchema } from "../../interfaces/customLLMProviderConfigSchemas";
import { TokenCountDelegate } from "../ingestion/processEventBatch";
import { AuthHeaderValidVerificationResult } from "../auth/types";
/* eslint-disable no-unused-vars */
// disable lint as this is exported and used in web/worker
export type PromptVariable = { name: string; value: string; isUsed: boolean };
@@ -16,15 +21,22 @@ export enum LLMAdapter {
OpenAI = "openai",
Azure = "azure",
Bedrock = "bedrock",
VertexAI = "vertex-ai",
VertexAI = "google-vertex-ai",
GoogleAIStudio = "google-ai-studio",
}
export enum ChatMessageRole {
System = "system",
User = "user",
Assistant = "assistant",
Developer = "developer",
}
export const SYSTEM_ROLES: string[] = [
ChatMessageRole.System,
ChatMessageRole.Developer,
];
export const ChatMessageDefaultRoleSchema = z.nativeEnum(ChatMessageRole);
const ChatMessageSchema = z.object({
@@ -71,6 +83,7 @@ export const ExperimentMetadataSchema = z
provider: z.string(),
model: z.string(),
model_params: ZodModelConfig,
error: z.string().optional(),
})
.strict();
export type ExperimentMetadata = z.infer<typeof ExperimentMetadataSchema>;
@@ -82,10 +95,14 @@ export const openAIModels = [
"gpt-4o-2024-05-13",
"gpt-4o-mini",
"gpt-4o-mini-2024-07-18",
"o3-mini",
"o3-mini-2025-01-31",
"o1-preview",
"o1-preview-2024-09-12",
"o1-mini",
"o1-mini-2024-09-12",
"gpt-4.5-preview",
"gpt-4.5-preview-2025-02-27",
"gpt-4-turbo-preview",
"gpt-4-1106-preview",
"gpt-4-0613",
@@ -104,6 +121,7 @@ export type OpenAIModel = (typeof openAIModels)[number];
// NOTE: Update docs page when changing this! https://langfuse.com/docs/playground#openai-playground--anthropic-playground
export const anthropicModels = [
"claude-3-7-sonnet-20250219",
"claude-3-5-sonnet-20241022",
"claude-3-5-sonnet-20240620",
"claude-3-opus-20240229",
@@ -116,18 +134,31 @@ export const anthropicModels = [
] as const;
export const vertexAIModels = [
"gemini-2.0-pro-exp-02-05",
"gemini-2.0-flash-001",
"gemini-2.0-flash-lite-preview-02-05",
"gemini-2.0-flash-exp",
"gemini-1.5-pro",
"gemini-1.5-flash",
"gemini-1.0-pro",
] as const;
export const googleAIStudioModels = [
"gemini-2.0-flash",
"gemini-2.0-flash-lite-preview-02-05",
"gemini-2.0-flash-thinking-exp-01-21",
"gemini-1.5-pro",
"gemini-1.5-flash",
"gemini-1.5-flash-8b",
] as const;
export type AnthropicModel = (typeof anthropicModels)[number];
export type VertexAIModel = (typeof vertexAIModels)[number];
export const supportedModels = {
[LLMAdapter.Anthropic]: anthropicModels,
[LLMAdapter.OpenAI]: openAIModels,
[LLMAdapter.VertexAI]: vertexAIModels,
[LLMAdapter.GoogleAIStudio]: googleAIStudioModels,
[LLMAdapter.Azure]: [],
[LLMAdapter.Bedrock]: [],
} as const;
@@ -163,3 +194,12 @@ export type LLMApiKey =
z.infer<typeof LLMApiKeySchema> extends LlmApiKeys
? z.infer<typeof LLMApiKeySchema>
: never;
export type TraceParams = {
traceName: string;
traceId: string;
projectId: string;
tags: string[];
tokenCountDelegate: TokenCountDelegate;
authCheck: AuthHeaderValidVerificationResult;
};
+1 -1
View File
@@ -9,5 +9,5 @@ export function decryptAndParseExtraHeaders(
) {
if (!extraHeaders) return;
return ExtraHeaderSchema.parse(decrypt(extraHeaders));
return ExtraHeaderSchema.parse(JSON.parse(decrypt(extraHeaders)));
}
@@ -383,6 +383,10 @@ export class FilterList {
return this.filters.find(predicate);
}
some(predicate: (filter: Filter) => boolean) {
return this.filters.some(predicate);
}
length() {
return this.filters.length;
}
@@ -1,4 +1,4 @@
import { ObservationView } from "@prisma/client";
import { ObservationView } from "../repositories";
type AdditionalObservationFields = {
traceName: string | null;
+75 -1
View File
@@ -1,10 +1,17 @@
/* eslint-disable no-unused-vars */
import { z } from "zod";
import { eventTypes, ingestionBatchEvent } from ".";
import { eventTypes } from ".";
import {
BatchActionQuerySchema,
BatchActionType,
} from "../features/batchAction/types";
import { BatchExportTableName } from "../features/batchExport/types";
export const IngestionEvent = z.object({
data: z.object({
type: z.nativeEnum(eventTypes),
eventBodyId: z.string(),
fileKey: z.string().optional(),
}),
authCheck: z.object({
validKey: z.literal(true),
@@ -55,7 +62,55 @@ export const DataRetentionProcessingEventSchema = z.object({
projectId: z.string(),
retention: z.number(),
});
export const BatchActionProcessingEventSchema = z.discriminatedUnion(
"actionId",
[
z.object({
actionId: z.literal("trace-delete"),
projectId: z.string(),
query: BatchActionQuerySchema,
tableName: z.nativeEnum(BatchExportTableName),
cutoffCreatedAt: z.date(),
targetId: z.string().optional(),
type: z.nativeEnum(BatchActionType),
}),
z.object({
actionId: z.literal("trace-add-to-annotation-queue"),
projectId: z.string(),
query: BatchActionQuerySchema,
tableName: z.nativeEnum(BatchExportTableName),
cutoffCreatedAt: z.date(),
targetId: z.string().optional(),
type: z.nativeEnum(BatchActionType),
}),
z.object({
actionId: z.literal("eval-create"),
targetObject: z.enum(["trace", "dataset"]),
configId: z.string(),
projectId: z.string(),
cutoffCreatedAt: z.date(),
query: BatchActionQuerySchema,
}),
],
);
export const CreateEvalQueueEventSchema = DatasetRunItemUpsertEventSchema.and(
z.object({
configId: z.string(),
timestamp: z.date(),
}),
).or(
TraceQueueEventSchema.and(
z.object({
timestamp: z.date(),
configId: z.string(),
}),
),
);
export type CreateEvalQueueEventType = z.infer<
typeof CreateEvalQueueEventSchema
>;
export type BatchExportJobType = z.infer<typeof BatchExportJobSchema>;
export type TraceQueueEventType = z.infer<typeof TraceQueueEventSchema>;
export type TracesQueueEventType = z.infer<typeof TracesQueueEventSchema>;
@@ -74,6 +129,9 @@ export type PostHogIntegrationProcessingEventType = z.infer<
export type DataRetentionProcessingEventType = z.infer<
typeof DataRetentionProcessingEventSchema
>;
export type BatchActionProcessingEventType = z.infer<
typeof BatchActionProcessingEventSchema
>;
export enum QueueName {
TraceUpsert = "trace-upsert", // Ingestion pipeline adds events on each Trace upsert
@@ -92,6 +150,8 @@ export enum QueueName {
MeteringDataPostgresExportQueue = "metering-data-postgres-export-queue",
DataRetentionQueue = "data-retention-queue",
DataRetentionProcessingQueue = "data-retention-processing-queue",
BatchActionQueue = "batch-action-queue",
CreateEvalQueue = "create-eval-queue",
}
export enum QueueJobs {
@@ -111,6 +171,8 @@ export enum QueueJobs {
MeteringDataPostgresExportJob = "metering-data-postgres-export-job",
DataRetentionJob = "data-retention-job",
DataRetentionProcessingJob = "data-retention-processing-job",
BatchActionProcessingJob = "batch-action-processing-job",
CreateEvalJob = "create-eval-job",
}
export type TQueueJobTypes = {
@@ -180,4 +242,16 @@ export type TQueueJobTypes = {
payload: DataRetentionProcessingEventType;
name: QueueJobs.DataRetentionProcessingJob;
};
[QueueName.BatchActionQueue]: {
timestamp: Date;
id: string;
payload: BatchActionProcessingEventType;
name: QueueJobs.BatchActionProcessingJob;
};
[QueueName.CreateEvalQueue]: {
timestamp: Date;
id: string;
payload: CreateEvalQueueEventType;
name: QueueJobs.CreateEvalJob;
};
};
@@ -0,0 +1,45 @@
import { Queue } from "bullmq";
import { QueueName, TQueueJobTypes } from "../queues";
import { createNewRedisInstance, redisQueueRetryOptions } from "./redis";
import { logger } from "../logger";
export class BatchActionQueue {
private static instance: Queue<
TQueueJobTypes[QueueName.BatchActionQueue]
> | null = null;
public static getInstance(): Queue<
TQueueJobTypes[QueueName.BatchActionQueue]
> | null {
if (BatchActionQueue.instance) return BatchActionQueue.instance;
const newRedis = createNewRedisInstance({
enableOfflineQueue: false,
...redisQueueRetryOptions,
});
BatchActionQueue.instance = newRedis
? new Queue<TQueueJobTypes[QueueName.BatchActionQueue]>(
QueueName.BatchActionQueue,
{
connection: newRedis,
defaultJobOptions: {
removeOnComplete: true,
removeOnFail: 10_000,
attempts: 2,
backoff: {
type: "exponential",
delay: 5000,
},
},
},
)
: null;
BatchActionQueue.instance?.on("error", (err) => {
logger.error("BatchActionQueue error", err);
});
return BatchActionQueue.instance;
}
}
@@ -0,0 +1,45 @@
import { QueueName, TQueueJobTypes } from "../queues";
import { Queue } from "bullmq";
import { createNewRedisInstance, redisQueueRetryOptions } from "./redis";
import { logger } from "../logger";
export class CreateEvalQueue {
private static instance: Queue<
TQueueJobTypes[QueueName.CreateEvalQueue]
> | null = null;
public static getInstance(): Queue<
TQueueJobTypes[QueueName.CreateEvalQueue]
> | null {
if (CreateEvalQueue.instance) return CreateEvalQueue.instance;
const newRedis = createNewRedisInstance({
enableOfflineQueue: false,
...redisQueueRetryOptions,
});
CreateEvalQueue.instance = newRedis
? new Queue<TQueueJobTypes[QueueName.CreateEvalQueue]>(
QueueName.CreateEvalQueue,
{
connection: newRedis,
defaultJobOptions: {
removeOnComplete: 100, // Important: If not true, new jobs for that ID would be ignored as jobs in the complete set are still considered as part of the queue
removeOnFail: 100_000,
attempts: 5,
backoff: {
type: "exponential",
delay: 5000,
},
},
},
)
: null;
CreateEvalQueue.instance?.on("error", (err) => {
logger.error("CreateEvalQueue error", err);
});
return CreateEvalQueue.instance;
}
}
@@ -15,6 +15,8 @@ import { CoreDataS3ExportQueue } from "./coreDataS3ExportQueue";
import { MeteringDataPostgresExportQueue } from "./meteringDataPostgresExportQueue";
import { DataRetentionQueue } from "./dataRetentionQueue";
import { DataRetentionProcessingQueue } from "./dataRetentionProcessingQueue";
import { BatchActionQueue } from "./batchActionQueue";
import { CreateEvalQueue } from "./createEvalQueue";
export function getQueue(queueName: QueueName): Queue | null {
switch (queueName) {
@@ -50,6 +52,10 @@ export function getQueue(queueName: QueueName): Queue | null {
return DataRetentionQueue.getInstance();
case QueueName.DataRetentionProcessingQueue:
return DataRetentionProcessingQueue.getInstance();
case QueueName.BatchActionQueue:
return BatchActionQueue.getInstance();
case QueueName.CreateEvalQueue:
return CreateEvalQueue.getInstance();
default:
const exhaustiveCheckDefault: never = queueName;
throw new Error(`Queue ${queueName} not found`);
@@ -27,6 +27,7 @@ export class ProjectDeleteQueue {
removeOnComplete: true,
removeOnFail: 100_000,
attempts: 5,
delay: 60_000, // 1 minute
backoff: {
type: "exponential",
delay: 5000,
+15
View File
@@ -1,4 +1,5 @@
import Redis, { RedisOptions } from "ioredis";
import fs from 'fs';
import { env } from "../../env";
import { logger } from "../logger";
@@ -23,10 +24,23 @@ export const redisQueueRetryOptions: Partial<RedisOptions> = {
export const createNewRedisInstance = (
additionalOptions: Partial<RedisOptions> = {},
) => {
const tlsEnabled = env.REDIS_TLS_ENABLED === "true";
const tlsOptions = tlsEnabled
? {
tls: {
ca: env.REDIS_TLS_CA_PATH ? fs.readFileSync(env.REDIS_TLS_CA_PATH) : undefined,
cert: env.REDIS_TLS_CERT_PATH ? fs.readFileSync(env.REDIS_TLS_CERT_PATH) : undefined,
key: env.REDIS_TLS_KEY_PATH ? fs.readFileSync(env.REDIS_TLS_KEY_PATH) : undefined,
},
}
: {};
const instance = env.REDIS_CONNECTION_STRING
? new Redis(env.REDIS_CONNECTION_STRING, {
...defaultRedisOptions,
...additionalOptions,
...tlsOptions,
})
: env.REDIS_HOST
? new Redis({
@@ -35,6 +49,7 @@ export const createNewRedisInstance = (
password: String(env.REDIS_AUTH),
...defaultRedisOptions,
...additionalOptions,
...tlsOptions,
})
: null;
@@ -25,10 +25,10 @@ export class TraceDeleteQueue {
defaultJobOptions: {
removeOnComplete: true,
removeOnFail: 100_000,
attempts: 5,
attempts: 2,
backoff: {
type: "exponential",
delay: 5000,
delay: 30_000,
},
},
},
@@ -5,14 +5,14 @@ import {
} from "../clickhouse/client";
import { logger } from "../logger";
import { getTracer, instrumentAsync } from "../instrumentation";
import {
StorageService,
StorageServiceFactory,
} from "../services/StorageService";
import { randomUUID } from "crypto";
import { getClickhouseEntityType } from "../clickhouse/schemaUtils";
import { NodeClickHouseClientConfigOptions } from "@clickhouse/client/dist/config";
import { context, trace } from "@opentelemetry/api";
import {
StorageService,
StorageServiceFactory,
} from "../services/StorageService";
let s3StorageServiceClient: StorageService;
@@ -36,16 +36,14 @@ export async function upsertClickhouse<
table: "scores" | "traces" | "observations";
records: T[];
eventBodyMapper: (body: T) => Record<string, unknown>;
tags?: Record<string, string>;
}): Promise<void> {
return await instrumentAsync({ name: "clickhouse-upsert" }, async (span) => {
// https://opentelemetry.io/docs/specs/semconv/database/database-spans/
span.setAttribute("ch.query.table", opts.table);
const s3Client = getS3StorageServiceClient(
env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
);
await Promise.all(
opts.records.map((record) => {
opts.records.map(async (record) => {
// drop trailing s and pretend it's always a create.
// Only applicable to scores and traces.
let eventType = `${opts.table.slice(0, -1)}-create`;
@@ -53,21 +51,44 @@ export async function upsertClickhouse<
// @ts-ignore - If it's an observation we now that `type` is a string
eventType = `${record["type"].toLowerCase()}-create`;
}
s3Client.uploadJson(
`${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${record.project_id}/${getClickhouseEntityType(eventType)}/${record.id}/${randomUUID()}.json`,
[
const eventId = randomUUID();
const bucketPath = `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${record.project_id}/${getClickhouseEntityType(eventType)}/${record.id}/${eventId}.json`;
// Write new file directly to ClickHouse. We don't use the ClickHouse writer here as we expect more limited traffic
// and are not worried that much about latency.
await clickhouseClient({
tags: opts.tags,
}).insert({
table: "event_log",
values: [
{
id: randomUUID(),
timestamp: new Date().toISOString(),
type: eventType,
body: opts.eventBodyMapper(record),
project_id: record.project_id,
entity_type: getClickhouseEntityType(eventType),
entity_id: record.id,
event_id: eventId,
bucket_name: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
bucket_path: bucketPath,
},
],
);
format: "JSONEachRow",
});
return getS3StorageServiceClient(
env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
).uploadJson(bucketPath, [
{
id: eventId,
timestamp: new Date().toISOString(),
type: eventType,
body: opts.eventBodyMapper(record),
},
]);
}),
);
const res = await clickhouseClient().insert({
const res = await clickhouseClient({ tags: opts.tags }).insert({
table: opts.table,
values: opts.records.map((record) => ({
...record,
@@ -106,6 +127,7 @@ export async function* queryClickhouseStream<T>(opts: {
query: string;
params?: Record<string, unknown> | undefined;
clickhouseConfigs?: NodeClickHouseClientConfigOptions;
tags?: Record<string, string>;
}): AsyncGenerator<T> {
const tracer = getTracer("clickhouse-query-stream");
const span = tracer.startSpan("clickhouse-query-stream");
@@ -117,7 +139,10 @@ export async function* queryClickhouseStream<T>(opts: {
// https://opentelemetry.io/docs/specs/semconv/database/database-spans/
span.setAttribute("ch.query.text", opts.query);
const res = await clickhouseClient(opts.clickhouseConfigs).query({
const res = await clickhouseClient({
tags: opts.tags,
opts: opts.clickhouseConfigs,
}).query({
query: opts.query,
format: "JSONEachRow",
query_params: opts.params,
@@ -164,12 +189,16 @@ export async function queryClickhouse<T>(opts: {
query: string;
params?: Record<string, unknown> | undefined;
clickhouseConfigs?: NodeClickHouseClientConfigOptions;
tags?: Record<string, string>;
}): Promise<T[]> {
return await instrumentAsync({ name: "clickhouse-query" }, async (span) => {
// https://opentelemetry.io/docs/specs/semconv/database/database-spans/
span.setAttribute("ch.query.text", opts.query);
const res = await clickhouseClient(opts.clickhouseConfigs).query({
const res = await clickhouseClient({
tags: opts.tags,
opts: opts.clickhouseConfigs,
}).query({
query: opts.query,
format: "JSONEachRow",
query_params: opts.params,
@@ -203,15 +232,19 @@ export async function queryClickhouse<T>(opts: {
});
}
export async function commandClickhouse<T>(opts: {
export async function commandClickhouse(opts: {
query: string;
params?: Record<string, unknown> | undefined;
clickhouseConfigs?: NodeClickHouseClientConfigOptions;
tags?: Record<string, string>;
}): Promise<void> {
return await instrumentAsync({ name: "clickhouse-command" }, async (span) => {
// https://opentelemetry.io/docs/specs/semconv/database/database-spans/
span.setAttribute("ch.query.text", opts.query);
const res = await clickhouseClient(opts.clickhouseConfigs).command({
const res = await clickhouseClient({
tags: opts.tags,
opts: opts.clickhouseConfigs,
}).command({
query: opts.query,
query_params: opts.params,
});
@@ -39,6 +39,12 @@ export const getTotalTraces = async (
projectId,
...chFilter.params,
},
tags: {
feature: "dashboard",
type: "totalTraces",
kind: "analytic",
projectId,
},
});
if (result.length === 0) {
@@ -59,7 +65,6 @@ export const getObservationsCostGroupedByName = async (
const appliedFilter = chFilter.apply();
const hasTraceFilter = chFilter.find((f) => f.clickhouseTable === "traces");
// TODO: Validate whether we can filter traces on timestamp here.
const query = `
SELECT
@@ -68,9 +73,10 @@ export const getObservationsCostGroupedByName = async (
sumMap(usage_details)['total'] as sum_usage_details
FROM observations o FINAL ${hasTraceFilter ? "LEFT JOIN traces t ON o.trace_id = t.id AND o.project_id = t.project_id" : ""}
WHERE project_id = {projectId: String}
AND ${appliedFilter.query}
${appliedFilter.query ? `AND ${appliedFilter.query}` : ""}
GROUP BY provided_model_name
ORDER BY sumMap(cost_details)['total'] DESC
LIMIT 50
`;
const result = await queryClickhouse<{
@@ -83,6 +89,12 @@ export const getObservationsCostGroupedByName = async (
projectId,
...appliedFilter.params,
},
tags: {
feature: "dashboard",
type: "observationCostGroupedByName",
kind: "analytic",
projectId,
},
});
return result;
@@ -137,6 +149,12 @@ export const getScoreAggregate = async (
? { tracesTimestamp: convertDateToClickhouseDateTime(timeFilter.value) }
: {}),
},
tags: {
feature: "dashboard",
type: "scoreAggregate",
kind: "analytic",
projectId,
},
});
return result;
@@ -145,23 +163,26 @@ export const getScoreAggregate = async (
export const groupTracesByTime = async (
projectId: string,
filter: FilterState,
groupBy: DateTrunc,
) => {
const chFilter = new FilterList(
createFilterFromFilterState(filter, dashboardColumnDefinitions),
).apply();
const [orderByQuery, orderByParams, bucketSizeInSeconds] = orderByTimeSeries(
filter,
"timestamp",
);
const query = `
SELECT
${selectTimeseriesColumn(groupBy, "timestamp", "timestamp")},
${selectTimeseriesColumn(bucketSizeInSeconds, "timestamp", "timestamp")},
count(*) as count
FROM traces t FINAL
WHERE project_id = {projectId: String}
AND ${chFilter.query}
GROUP BY timestamp
${orderByTimeSeries(groupBy, "timestamp")}
${orderByQuery}
`;
const result = await queryClickhouse<{
timestamp: string;
count: string;
@@ -170,11 +191,18 @@ export const groupTracesByTime = async (
params: {
projectId,
...chFilter.params,
...orderByParams,
},
tags: {
feature: "dashboard",
type: "tracesByTime",
kind: "analytic",
projectId,
},
});
return result.map((row) => ({
timestamp: new Date(row.timestamp),
timestamp: parseClickhouseUTCDateTimeFormat(row.timestamp),
countTraceId: Number(row.count),
}));
};
@@ -182,7 +210,6 @@ export const groupTracesByTime = async (
export const getObservationUsageByTime = async (
projectId: string,
filter: FilterState,
groupBy: DateTrunc,
) => {
const chFilter = new FilterList(
createFilterFromFilterState(filter, dashboardColumnDefinitions),
@@ -200,9 +227,14 @@ export const getObservationUsageByTime = async (
) as DateTimeFilter | undefined)
: undefined;
const [orderByQuery, orderByParams, bucketSizeInSeconds] = orderByTimeSeries(
filter,
"start_time",
);
const query = `
SELECT
${selectTimeseriesColumn(groupBy, "start_time", "start_time")},
${selectTimeseriesColumn(bucketSizeInSeconds, "start_time", "start_time")},
sumMap(usage_details) as units,
sumMap(cost_details) as cost,
provided_model_name
@@ -212,7 +244,7 @@ export const getObservationUsageByTime = async (
AND ${appliedFilter.query}
${timeFilter ? `AND t.timestamp >= {traceTimestamp: DateTime64(3)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}` : ""}
GROUP BY start_time, provided_model_name
${orderByTimeSeries(groupBy, "start_time")}
${orderByQuery}
`;
const result = await queryClickhouse<{
@@ -225,14 +257,21 @@ export const getObservationUsageByTime = async (
params: {
projectId,
...appliedFilter.params,
...orderByParams,
...(timeFilter
? { traceTimestamp: convertDateToClickhouseDateTime(timeFilter.value) }
: {}),
},
tags: {
feature: "dashboard",
type: "observationUsageByTime",
kind: "analytic",
projectId,
},
});
return result.map((row) => ({
start_time: new Date(row.start_time),
start_time: parseClickhouseUTCDateTimeFormat(row.start_time),
units: Object.fromEntries(
Object.entries(row.units ?? {}).map(([key, value]) => [
key,
@@ -271,12 +310,15 @@ export const getDistinctModels = async (
// No need for final as duplicates are caught by distinct anyway.
const query = `
SELECT distinct(provided_model_name) as model
SELECT distinct(provided_model_name) as model, count(*) as count
FROM observations o
${tracesFilter ? "LEFT JOIN traces t ON o.trace_id = t.id AND o.project_id = t.project_id" : ""}
WHERE project_id = {projectId: String}
AND ${appliedFilter.query}
${timeFilter ? `AND t.timestamp >= {traceTimestamp: DateTime64(3)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}` : ""}
GROUP BY provided_model_name
ORDER BY count(*) DESC
LIMIT 1000
`;
const result = await queryClickhouse<{ model: string }>({
@@ -288,6 +330,12 @@ export const getDistinctModels = async (
? { traceTimestamp: convertDateToClickhouseDateTime(timeFilter.value) }
: {}),
},
tags: {
feature: "dashboard",
type: "distinctModels",
kind: "analytic",
projectId,
},
});
return result;
@@ -296,7 +344,6 @@ export const getDistinctModels = async (
export const getScoresAggregateOverTime = async (
projectId: string,
filter: FilterState,
groupBy: DateTrunc,
) => {
const chFilter = new FilterList(
createFilterFromFilterState(filter, dashboardColumnDefinitions),
@@ -307,9 +354,14 @@ export const getScoresAggregateOverTime = async (
const traceFilter = chFilter.find((f) => f.clickhouseTable === "traces");
// TODO: Validate whether we can filter traces on timestamp here.
const [orderByQuery, orderByParams, bucketSizeInSeconds] = orderByTimeSeries(
filter,
"timestamp",
);
const query = `
SELECT
${selectTimeseriesColumn(groupBy, "timestamp", "timestamp")},
${selectTimeseriesColumn(bucketSizeInSeconds, "timestamp", "timestamp")},
name,
data_type,
source,
@@ -324,7 +376,7 @@ export const getScoresAggregateOverTime = async (
name,
data_type,
source
${orderByTimeSeries(groupBy, "timestamp")};
${orderByQuery};
`;
const result = await queryClickhouse<{
@@ -338,11 +390,18 @@ export const getScoresAggregateOverTime = async (
params: {
projectId,
...appliedFilter.params,
...orderByParams,
},
tags: {
feature: "dashboard",
type: "scoresAggregateOverTime",
kind: "analytic",
projectId,
},
});
return result.map((row) => ({
scoreTimestamp: new Date(row.timestamp),
scoreTimestamp: parseClickhouseUTCDateTimeFormat(row.timestamp),
scoreName: row.name,
scoreDataType: row.data_type,
scoreSource: row.source,
@@ -396,6 +455,12 @@ export const getModelUsageByUser = async (
? { traceTimestamp: convertDateToClickhouseDateTime(timeFilter.value) }
: {}),
},
tags: {
feature: "dashboard",
type: "modelUsageByUser",
kind: "analytic",
projectId,
},
});
return result.map((row) => ({
@@ -431,6 +496,12 @@ export const getObservationLatencies = async (
const result = await queryClickhouse<{ quantiles: string[]; name: string }>({
query,
params: { projectId, ...appliedFilter.params },
tags: {
feature: "dashboard",
type: "observationLatencies",
kind: "analytic",
projectId,
},
});
return result.map((row) => ({
@@ -492,6 +563,12 @@ export const getTracesLatencies = async (
? { dateTimeFilterObservations: timestampFilter.value }
: {}),
},
tags: {
feature: "dashboard",
type: "tracesLatencies",
kind: "analytic",
projectId,
},
});
return result.map((row) => ({
@@ -506,7 +583,6 @@ export const getTracesLatencies = async (
export const getModelLatenciesOverTime = async (
projectId: string,
filter: FilterState,
groupBy: DateTrunc,
) => {
const chFilter = new FilterList(
createFilterFromFilterState(filter, dashboardColumnDefinitions),
@@ -516,10 +592,15 @@ export const getModelLatenciesOverTime = async (
const traceFilter = chFilter.find((f) => f.clickhouseTable === "traces");
const [orderByQuery, orderByParams, bucketSizeInSeconds] = orderByTimeSeries(
filter,
"start_time_bucket",
);
// Skipping FINAL here, as the quantiles are approximate to begin with.
const query = `
SELECT
${selectTimeseriesColumn(groupBy, "o.start_time", "start_time_bucket")},
${selectTimeseriesColumn(bucketSizeInSeconds, "o.start_time", "start_time_bucket")},
provided_model_name,
quantiles(0.5, 0.75, 0.9, 0.95, 0.99)(date_diff('millisecond', o.start_time, o.end_time)) as quantiles
FROM observations o
@@ -527,14 +608,23 @@ export const getModelLatenciesOverTime = async (
WHERE project_id = {projectId: String}
AND ${appliedFilter.query}
GROUP BY provided_model_name, start_time_bucket
${orderByTimeSeries(groupBy, "start_time_bucket")};
${orderByQuery};
`;
const result = await queryClickhouse<{
start_time_bucket: string;
provided_model_name: string;
quantiles: string[];
}>({ query, params: { projectId, ...appliedFilter.params } });
}>({
query,
params: { projectId, ...appliedFilter.params, ...orderByParams },
tags: {
feature: "dashboard",
type: "modelLatenciesOverTime",
kind: "analytic",
projectId,
},
});
return result.map((row) => ({
p50: Number(row.quantiles[0]) / 1000,
@@ -543,14 +633,13 @@ export const getModelLatenciesOverTime = async (
p95: Number(row.quantiles[3]) / 1000,
p99: Number(row.quantiles[4]) / 1000,
model: row.provided_model_name,
start_time: new Date(row.start_time_bucket),
start_time: parseClickhouseUTCDateTimeFormat(row.start_time_bucket),
}));
};
export const getNumericScoreTimeSeries = async (
projectId: string,
filter: FilterState,
groupBy: DateTrunc,
) => {
const chFilter = new FilterList(
createFilterFromFilterState(filter, dashboardColumnDefinitions),
@@ -559,9 +648,14 @@ export const getNumericScoreTimeSeries = async (
const traceFilter = chFilter.find((f) => f.clickhouseTable === "traces");
const [orderByQuery, orderByParams, bucketSizeInSeconds] = orderByTimeSeries(
filter,
"score_timestamp",
);
const query = `
SELECT
${selectTimeseriesColumn(groupBy, "s.timestamp", "score_timestamp")},
${selectTimeseriesColumn(bucketSizeInSeconds, "s.timestamp", "score_timestamp")},
s.name as score_name,
AVG(s.value) as avg_value
FROM scores s final
@@ -569,11 +663,11 @@ export const getNumericScoreTimeSeries = async (
WHERE s.project_id = {projectId: String}
${chFilterRes?.query ? `AND ${chFilterRes.query}` : ""}
GROUP BY score_name, score_timestamp
${orderByTimeSeries(groupBy, "score_timestamp")}
${orderByQuery}
`;
return queryClickhouse<{
score_timestamp: Date;
const result = await queryClickhouse<{
score_timestamp: string;
score_name: string;
avg_value: number;
}>({
@@ -581,14 +675,26 @@ export const getNumericScoreTimeSeries = async (
params: {
projectId,
...(chFilterRes ? chFilterRes.params : {}),
...orderByParams,
},
tags: {
feature: "dashboard",
type: "numericScoreTimeSeries",
kind: "analytic",
projectId,
},
});
return result.map((row) => ({
scoreTimestamp: parseClickhouseUTCDateTimeFormat(row.score_timestamp),
scoreName: row.score_name,
avgValue: Number(row.avg_value),
}));
};
export const getCategoricalScoreTimeSeries = async (
projectId: string,
filter: FilterState,
groupBy: DateTrunc | undefined,
) => {
const chFilter = new FilterList(
createFilterFromFilterState(filter, dashboardColumnDefinitions),
@@ -597,9 +703,14 @@ export const getCategoricalScoreTimeSeries = async (
const traceFilter = chFilter.find((f) => f.clickhouseTable === "traces");
const [orderByQuery, orderByParams, bucketSizeInSeconds] = orderByTimeSeries(
filter,
"score_timestamp",
);
const query = `
SELECT
${groupBy ? selectTimeseriesColumn(groupBy, "s.timestamp", "score_timestamp") + ", " : ""}
${bucketSizeInSeconds ? selectTimeseriesColumn(bucketSizeInSeconds, "s.timestamp", "score_timestamp") + ", " : ""}
s.name as score_name,
s.data_type as score_data_type,
s.source as score_source,
@@ -609,12 +720,12 @@ export const getCategoricalScoreTimeSeries = async (
${traceFilter ? "JOIN traces t ON s.trace_id = t.id AND s.project_id = t.project_id" : ""}
WHERE s.project_id = {projectId: String}
${chFilterRes?.query ? `AND ${chFilterRes.query}` : ""}
GROUP BY score_name, score_data_type, score_source, score_value ${groupBy ? ", score_timestamp" : ""}
${groupBy ? orderByTimeSeries(groupBy, "score_timestamp") : ""}
GROUP BY score_name, score_data_type, score_source, score_value ${bucketSizeInSeconds ? ", score_timestamp" : ""}
${orderByQuery}
`;
return queryClickhouse<{
score_timestamp?: Date;
const result = await queryClickhouse<{
score_timestamp?: string;
score_name: string;
score_data_type: string;
score_source: string;
@@ -625,14 +736,31 @@ export const getCategoricalScoreTimeSeries = async (
params: {
projectId,
...(chFilterRes ? chFilterRes.params : {}),
...orderByParams,
},
tags: {
feature: "dashboard",
type: "categoricalScoreTimeSeries",
kind: "analytic",
projectId,
},
});
return result.map((row) => ({
scoreTimestamp: row.score_timestamp
? parseClickhouseUTCDateTimeFormat(row.score_timestamp)
: undefined,
scoreName: row.score_name,
scoreDataType: row.score_data_type,
scoreSource: row.score_source,
scoreValue: row.score_value,
count: Number(row.count),
}));
};
export const getObservationsStatusTimeSeries = async (
projectId: string,
filter: FilterState,
groupBy: DateTrunc | undefined,
) => {
const chFilter = new FilterList(
createFilterFromFilterState(filter, dashboardColumnDefinitions),
@@ -641,9 +769,14 @@ export const getObservationsStatusTimeSeries = async (
const traceFilter = chFilter.find((f) => f.clickhouseTable === "traces");
const [orderByQuery, orderByParams, bucketSizeInSeconds] = orderByTimeSeries(
filter,
"start_time_bucket",
);
const query = `
SELECT
${groupBy ? selectTimeseriesColumn(groupBy, "o.start_time", "start_time_bucket") + ", " : ""}
${bucketSizeInSeconds ? selectTimeseriesColumn(bucketSizeInSeconds, "o.start_time", "start_time_bucket") + ", " : ""}
count(*) as observation_count,
level as level
FROM observations o
@@ -651,8 +784,8 @@ export const getObservationsStatusTimeSeries = async (
WHERE project_id = {projectId: String}
AND o.level IS NOT NULL
AND ${chFilterRes?.query}
GROUP BY level ${groupBy ? ", start_time_bucket" : ""}
${groupBy ? orderByTimeSeries(groupBy, "start_time_bucket") : ""}
GROUP BY level ${bucketSizeInSeconds ? ", start_time_bucket" : ""}
${orderByQuery}
`;
const result = await queryClickhouse<{
@@ -661,7 +794,17 @@ export const getObservationsStatusTimeSeries = async (
level: string;
}>({
query,
params: { projectId, ...(chFilterRes ? chFilterRes.params : {}) },
params: {
projectId,
...(chFilterRes ? chFilterRes.params : {}),
...orderByParams,
},
tags: {
feature: "dashboard",
type: "observationStatusTimeSeries",
kind: "analytic",
projectId,
},
});
return result.map((row) => ({
@@ -673,61 +816,70 @@ export const getObservationsStatusTimeSeries = async (
}));
};
const orderByTimeSeries = (dateTrunc: DateTrunc, col: string) => {
let interval;
switch (dateTrunc) {
case "year":
interval = "toIntervalYear(1)";
break;
case "month":
interval = "toIntervalMonth(1)";
break;
case "week":
interval = "toIntervalWeek(1)";
break;
case "day":
interval = "toIntervalDay(1)";
break;
case "hour":
interval = "toIntervalHour(1)";
break;
case "minute":
interval = "toIntervalMinute(1)";
break;
default:
return undefined;
export const orderByTimeSeries = (
filter: FilterState,
col: string,
): [string, { fromTime: number; toTime: number }, number] => {
const potentialBucketSizesSeconds = [
5, 10, 30, 60, 300, 600, 1800, 3600, 18000, 36000, 86400, 604800, 2592000,
];
// Calculate time difference in seconds
const [from, to] = extractFromAndToTimestampsFromFilter(filter);
if (!from || !to) {
throw new Error("Time Filter is required for time series queries");
}
return `ORDER BY ${col} ASC WITH FILL STEP ${interval}`;
const fromDate = new Date(from.value as Date);
const toDate = new Date(to.value as Date);
const diffInSeconds = Math.abs(toDate.getTime() - fromDate.getTime()) / 1000;
// choose the bucket size that is the closest to the desired number of buckets
const bucketSizeInSeconds = potentialBucketSizesSeconds.reduce(
(closest, size) => {
const diffFromDesiredBuckets = Math.abs(diffInSeconds / size - 50);
return diffFromDesiredBuckets < closest.diffFromDesiredBuckets
? { size, diffFromDesiredBuckets }
: closest;
},
{ size: 0, diffFromDesiredBuckets: Infinity },
).size;
// Convert to interval string
const interval = `toIntervalSecond(${bucketSizeInSeconds})`;
return [
`ORDER BY ${col} ASC
WITH FILL
FROM toStartOfInterval(toDateTime({fromTime: DateTime64(3)}), INTERVAL ${bucketSizeInSeconds} SECOND)
TO toDateTime({toTime: DateTime64(3)}) + INTERVAL ${bucketSizeInSeconds} SECOND
STEP ${interval}`,
{ fromTime: fromDate.getTime(), toTime: toDate.getTime() },
bucketSizeInSeconds,
];
};
const selectTimeseriesColumn = (
dateTrunc: DateTrunc,
export const selectTimeseriesColumn = (
bucketSizeInSeconds: number,
col: string,
as: String,
) => {
let interval;
switch (dateTrunc) {
case "year":
interval = "toStartOfYear";
break;
case "month":
interval = "toStartOfMonth";
break;
case "week":
interval = "toStartOfWeek";
break;
case "day":
interval = "toStartOfDay";
break;
case "hour":
interval = "toStartOfHour";
break;
case "minute":
interval = "toStartOfMinute";
break;
default:
return undefined;
}
return `${interval}(${col}) as ${as}`;
return `toStartOfInterval(${col}, INTERVAL ${bucketSizeInSeconds} SECOND) as ${as}`;
};
export const extractFromAndToTimestampsFromFilter = (filter?: FilterState) => {
if (!filter)
throw new Error("Time Filter is required for time series queries");
const fromTimestamp = filter.filter(
(f) => f.type === "datetime" && (f.operator === ">" || f.operator === ">="),
);
const toTimestamp = filter.filter(
(f) => f.type === "datetime" && (f.operator === "<" || f.operator === "<="),
);
return [fromTimestamp[0], toTimestamp[0]];
};
@@ -36,6 +36,7 @@ export const observationRecordBaseSchema = z.object({
project_id: z.string(),
type: z.string(),
parent_observation_id: z.string().nullish(),
environment: z.string().default("default"),
name: z.string().nullish(),
metadata: z.record(z.string()),
level: z.string().nullish(),
@@ -52,9 +53,6 @@ export const observationRecordBaseSchema = z.object({
prompt_version: z.number().nullish(),
is_deleted: z.number(),
});
export type ObservationRecordBaseType = z.infer<
typeof observationRecordBaseSchema
>;
export const observationRecordReadSchema = observationRecordBaseSchema.extend({
created_at: clickhouseStringDateSchema,
@@ -98,6 +96,7 @@ export const traceRecordBaseSchema = z.object({
release: z.string().nullish(),
version: z.string().nullish(),
project_id: z.string(),
environment: z.string().default("default"),
public: z.boolean(),
bookmarked: z.boolean(),
tags: z.array(z.string()),
@@ -106,7 +105,6 @@ export const traceRecordBaseSchema = z.object({
session_id: z.string().nullish(),
is_deleted: z.number(),
});
export type TraceRecordBaseType = z.infer<typeof traceRecordBaseSchema>;
export const traceRecordReadSchema = traceRecordBaseSchema.extend({
timestamp: clickhouseStringDateSchema,
@@ -129,6 +127,7 @@ export const scoreRecordBaseSchema = z.object({
project_id: z.string(),
trace_id: z.string(),
observation_id: z.string().nullish(),
environment: z.string().default("default"),
name: z.string(),
value: z.number().nullish(),
source: z.string(),
@@ -140,7 +139,6 @@ export const scoreRecordBaseSchema = z.object({
queue_id: z.string().nullish(),
is_deleted: z.number(),
});
export type ScoreRecordBaseType = z.infer<typeof scoreRecordBaseSchema>;
export const scoreRecordReadSchema = scoreRecordBaseSchema.extend({
created_at: clickhouseStringDateSchema,
@@ -158,6 +156,30 @@ export const scoreRecordInsertSchema = scoreRecordBaseSchema.extend({
});
export type ScoreRecordInsertType = z.infer<typeof scoreRecordInsertSchema>;
export const eventLogRecordBaseSchema = z.object({
id: z.string(),
project_id: z.string(),
entity_type: z.string(),
entity_id: z.string(),
// event_id is nullable to be compatible with legacy queue events.
// It still allows us to delete things by prefix, but requires an additional list call.
event_id: z.string().nullable(),
bucket_name: z.string(),
bucket_path: z.string(),
});
export const eventLogRecordReadSchema = eventLogRecordBaseSchema.extend({
created_at: clickhouseStringDateSchema,
updated_at: clickhouseStringDateSchema,
});
export type EventLogRecordReadType = z.infer<typeof eventLogRecordReadSchema>;
export const eventLogRecordInsertSchema = eventLogRecordBaseSchema.extend({
created_at: z.number(),
updated_at: z.number(),
});
export type EventLogRecordInsertType = z.infer<
typeof eventLogRecordInsertSchema
>;
export const convertTraceReadToInsert = (
record: TraceRecordReadType,
): TraceRecordInsertType => {
@@ -222,6 +244,7 @@ export const convertPostgresTraceToInsert = (
: Array.isArray(trace.metadata)
? { metadata: trace.metadata }
: trace.metadata,
environment: trace.environment,
release: trace.release,
version: trace.version,
project_id: trace.project_id,
@@ -258,6 +281,7 @@ export const convertPostgresObservationToInsert = (
project_id: observation.project_id,
type: observation.type,
parent_observation_id: observation.parent_observation_id,
environment: observation.environment,
start_time: observation.start_time?.getTime(),
end_time: observation.end_time?.getTime(),
name: observation.name,
@@ -321,6 +345,7 @@ export const convertPostgresScoreToInsert = (
project_id: score.project_id,
trace_id: score.trace_id,
observation_id: score.observation_id,
environment: score.environment,
name: score.name,
value: score.value,
source: score.source,
@@ -0,0 +1,229 @@
import {
commandClickhouse,
queryClickhouse,
queryClickhouseStream,
} from "./clickhouse";
import { EventLogRecordReadType } from "./definitions";
import { convertDateToClickhouseDateTime } from "../clickhouse/client";
export const getEventLogByProjectAndEntityId = async (
projectId: string,
entityType: string,
entityId: string,
): Promise<EventLogRecordReadType[]> => {
const query = `
select *
from event_log
where project_id = {projectId: String}
and entity_type = {entityType: String}
and entity_id = {entityId: String}
`;
return queryClickhouse<EventLogRecordReadType>({
query,
params: {
projectId,
entityType,
entityId,
},
tags: {
feature: "eventLog",
kind: "byID",
projectId,
},
});
};
export const getEventLogByProjectId = (
projectId: string,
): AsyncGenerator<EventLogRecordReadType> => {
const query = `
select *
from event_log
where project_id = {projectId: String}
`;
return queryClickhouseStream<EventLogRecordReadType>({
query,
params: {
projectId,
},
tags: {
feature: "eventLog",
kind: "list",
projectId,
},
});
};
export const getEventLogByProjectIdBeforeDate = (
projectId: string,
beforeDate: Date,
): AsyncGenerator<EventLogRecordReadType> => {
const query = `
select *
from event_log
where project_id = {projectId: String}
and created_at <= {beforeDate: DateTime64(3)}
`;
return queryClickhouseStream<EventLogRecordReadType>({
query,
params: {
projectId,
beforeDate: convertDateToClickhouseDateTime(beforeDate),
},
tags: {
feature: "eventLog",
kind: "list",
projectId,
},
});
};
export const getEventLogByProjectIdAndTraceIds = (
projectId: string,
traceIds: string[],
): AsyncGenerator<EventLogRecordReadType> => {
const query = `
with filtered_traces as (
select distinct
id as entity_id,
project_id as project_id,
'trace' as entity_type
from traces
where project_id = {projectId: String}
and id in ({traceIds: Array(String)})
), filtered_observations as (
select distinct
id as entity_id,
project_id as project_id,
'observation' as entity_type
from observations
where project_id = {projectId: String}
and trace_id in ({traceIds: Array(String)})
), filtered_scores as (
select distinct
id as entity_id,
project_id as project_id,
'score' as entity_type
from scores
where project_id = {projectId: String}
and trace_id in ({traceIds: Array(String)})
), filtered_events as (
select *
from filtered_traces
union all
select *
from filtered_observations
union all
select *
from filtered_scores
)
-- We use a semi join because we only use the 'filtered_events' as a filter.
-- There is no need to build the cartesian product (i.e. the combination) between the event log and the events.
select el.*
from event_log el
left semi join filtered_events fe
on el.project_id = fe.project_id and el.entity_id = fe.entity_id and el.entity_type = fe.entity_type
where el.project_id = {projectId: String}
`;
return queryClickhouseStream<EventLogRecordReadType>({
query,
params: {
projectId,
traceIds,
},
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
tags: {
feature: "eventLog",
kind: "list",
projectId,
},
});
};
/**
* Deletes event log records by projectId and the _eventLog_.id
* @param projectId - Project ID
* @param ids - ID record of the event log table to be deleted
*/
export const deleteEventLogByProjectIdAndIds = async (
projectId: string,
ids: string[],
): Promise<void> => {
const query = `
delete from event_log
where project_id = {projectId: String}
and id in ({ids: Array(String)});
`;
await commandClickhouse({
query,
params: {
projectId,
ids,
},
clickhouseConfigs: {
request_timeout: 300_000, // 5 minutes
},
tags: {
feature: "eventLog",
kind: "delete",
projectId,
},
});
};
export const deleteEventLogByProjectId = async (
projectId: string,
): Promise<void> => {
const query = `
DELETE FROM event_log
WHERE project_id = {projectId: String};
`;
await commandClickhouse({
query: query,
params: {
projectId,
},
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
tags: {
feature: "eventLog",
kind: "delete",
projectId,
},
});
};
export const deleteEventLogByProjectIdBeforeDate = async (
projectId: string,
beforeDate: Date,
): Promise<void> => {
const query = `
DELETE FROM event_log
WHERE project_id = {projectId: String}
AND created_at <= {beforeDate: DateTime64(3)};
`;
await commandClickhouse({
query: query,
params: {
projectId,
beforeDate: convertDateToClickhouseDateTime(beforeDate),
},
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
tags: {
feature: "eventLog",
kind: "delete",
projectId,
},
});
};
@@ -9,3 +9,4 @@ export * from "./observations_converters";
export * from "./clickhouse";
export * from "./constants";
export * from "./trace-sessions";
export * from "./eventLog";
@@ -5,7 +5,6 @@ import {
queryClickhouseStream,
upsertClickhouse,
} from "./clickhouse";
import { ObservationLevel } from "@prisma/client";
import { logger } from "../logger";
import { InternalServerError, LangfuseNotFoundError } from "../../errors";
import { prisma } from "../../db";
@@ -15,18 +14,15 @@ import {
DateTimeFilter,
FilterList,
StringFilter,
} from "../queries/clickhouse-sql/clickhouse-filter";
import {
FullObservation,
FullObservations,
} from "../queries/createGenerationsQuery";
orderByToClickhouseSql,
} from "../queries";
import { createFilterFromFilterState } from "../queries/clickhouse-sql/factory";
import {
observationsTableTraceUiColumnDefinitions,
observationsTableUiColumnDefinitions,
} from "../../tableDefinitions";
import { TableCount } from "./types";
import { orderByToClickhouseSql } from "../queries/clickhouse-sql/orderby-factory";
import { OrderByState } from "../../interfaces/orderBy";
import { getTracesByIds } from "./traces";
import { convertDateToClickhouseDateTime } from "../clickhouse/client";
@@ -65,6 +61,12 @@ export const checkObservationExists = async (
? { startTime: convertDateToClickhouseDateTime(startTime) }
: {}),
},
tags: {
feature: "tracing",
type: "observation",
kind: "exists",
projectId,
},
});
return rows.length > 0;
@@ -90,6 +92,12 @@ export const upsertObservation = async (
table: "observations",
records: [observation as ObservationRecordReadType],
eventBodyMapper: convertObservation,
tags: {
feature: "tracing",
type: "observation",
kind: "upsert",
projectId: observation.project_id ?? "",
},
});
};
@@ -106,6 +114,7 @@ export const getObservationsViewForTrace = async (
project_id,
type,
parent_observation_id,
environment,
start_time,
end_time,
name,
@@ -144,6 +153,12 @@ export const getObservationsViewForTrace = async (
? { traceTimestamp: convertDateToClickhouseDateTime(timestamp) }
: {}),
},
tags: {
feature: "tracing",
type: "observation",
kind: "list",
projectId,
},
});
return records.map(convertObservationToView);
@@ -163,6 +178,7 @@ export const getObservationForTraceIdByName = async (
project_id,
type,
parent_observation_id,
environment,
start_time,
end_time,
name,
@@ -203,6 +219,12 @@ export const getObservationForTraceIdByName = async (
? { traceTimestamp: convertDateToClickhouseDateTime(timestamp) }
: {}),
},
tags: {
feature: "tracing",
type: "observation",
kind: "list",
projectId,
},
});
return records.map(convertObservationToView);
@@ -322,6 +344,7 @@ const getObservationByIdInternal = async (
id,
trace_id,
project_id,
environment,
type,
parent_observation_id,
start_time,
@@ -362,6 +385,12 @@ const getObservationByIdInternal = async (
? { startTime: convertDateToClickhouseDateTime(startTime) }
: {}),
},
tags: {
feature: "tracing",
type: "observation",
kind: "byId",
projectId,
},
});
};
@@ -375,21 +404,6 @@ export type ObservationTableQuery = {
selectIOAndMetadata?: boolean;
};
export type ObservationTableRecord = {
id: string;
projectId: string;
traceId: string;
observationCount: number;
providedCostDetails: Record<string, number>;
costDetails: Record<string, number>;
usageDetails: Record<string, number>;
providedUsageDetails: Record<string, number>;
latencyMs: number;
level: ObservationLevel;
scoresAvg: Record<string, number>;
scoresValues: Record<string, number>;
};
export type ObservationsTableQueryResult = ObservationRecordReadType & {
latency?: string;
time_to_first_token?: string;
@@ -402,48 +416,9 @@ export const getObservationsTableCount = async (opts: ObservationTableQuery) =>
getObservationsTableInternal<TableCount>({
...opts,
select: "count",
tags: { kind: "count" },
});
export type ObservationsTableRow = Omit<
FullObservation,
"modelId" | "inputPrice" | "outputPrice" | "totalPrice"
>;
export const getObservationsTable = async (
opts: ObservationTableQuery,
): Promise<Array<ObservationsTableRow>> => {
const observationRecords = await getObservationsTableInternal<
Omit<
ObservationsTableQueryResult,
"trace_tags" | "trace_name" | "trace_user_id"
>
>({
...opts,
select: "rows",
});
const traces = await getTracesByIds(
observationRecords
.map((o) => o.trace_id)
.filter((o): o is string => Boolean(o)),
opts.projectId,
);
return observationRecords.map((o) => {
const trace = traces.find((t) => t.id === o.trace_id);
return {
...convertObservationToView(o),
latency: o.latency ? Number(o.latency) / 1000 : null,
timeToFirstToken: o.time_to_first_token
? Number(o.time_to_first_token) / 1000
: null,
traceName: trace?.name ?? null,
traceTags: trace?.tags ?? [],
userId: trace?.userId ?? null,
};
});
};
export const getObservationsTableWithModelData = async (
opts: ObservationTableQuery,
): Promise<FullObservations> => {
@@ -455,6 +430,7 @@ export const getObservationsTableWithModelData = async (
>({
...opts,
select: "rows",
tags: { kind: "list" },
});
const uniqueModels: string[] = Array.from(
@@ -511,7 +487,10 @@ export const getObservationsTableWithModelData = async (
};
const getObservationsTableInternal = async <T>(
opts: ObservationTableQuery & { select: "count" | "rows" },
opts: ObservationTableQuery & {
select: "count" | "rows";
tags: Record<string, string>;
},
): Promise<Array<T>> => {
const select =
opts.select === "count"
@@ -703,6 +682,12 @@ const getObservationsTableInternal = async <T>(
: {}),
...search.params,
},
tags: {
...(opts.tags ?? {}),
feature: "tracing",
type: "observation",
projectId,
},
});
return res;
@@ -748,6 +733,12 @@ export const getObservationsGroupedByModel = async (
params: {
...appliedObservationsFilter.params,
},
tags: {
feature: "tracing",
type: "observation",
kind: "analytic",
projectId,
},
});
return res.map((r) => ({ model: r.name }));
};
@@ -792,6 +783,12 @@ export const getObservationsGroupedByModelId = async (
params: {
...appliedObservationsFilter.params,
},
tags: {
feature: "tracing",
type: "observation",
kind: "analytic",
projectId,
},
});
return res.map((r) => ({ modelId: r.modelId }));
};
@@ -836,6 +833,12 @@ export const getObservationsGroupedByName = async (
params: {
...appliedObservationsFilter.params,
},
tags: {
feature: "tracing",
type: "observation",
kind: "analytic",
projectId,
},
});
return res;
};
@@ -881,6 +884,12 @@ export const getObservationsGroupedByPromptName = async (
params: {
...appliedObservationsFilter.params,
},
tags: {
feature: "tracing",
type: "observation",
kind: "analytic",
projectId,
},
});
const prompts = res.map((r) => r.id).filter((r): r is string => Boolean(r));
@@ -908,6 +917,7 @@ export const getObservationsGroupedByPromptName = async (
export const getCostForTraces = async (
projectId: string,
timestamp: Date,
traceIds: string[],
) => {
// Wrapping the query in a CTE allows us to skip FINAL which allows Clickhouse to use skip indexes.
@@ -917,6 +927,7 @@ export const getCostForTraces = async (
FROM observations o
WHERE o.project_id = {projectId: String}
AND o.trace_id IN ({traceIds: Array(String)})
AND o.start_time >= {timestamp: DateTime64(3)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}
ORDER BY o.event_ts DESC
LIMIT 1 BY o.id, o.project_id
)
@@ -930,6 +941,13 @@ export const getCostForTraces = async (
params: {
projectId,
traceIds,
timestamp: convertDateToClickhouseDateTime(timestamp),
},
tags: {
feature: "tracing",
type: "observation",
kind: "analytic",
projectId,
},
});
return res.length > 0 ? Number(res[0].total_cost) : undefined;
@@ -953,6 +971,12 @@ export const deleteObservationsByTraceIds = async (
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
tags: {
feature: "tracing",
type: "observation",
kind: "delete",
projectId,
},
});
};
@@ -969,6 +993,39 @@ export const deleteObservationsByProjectId = async (projectId: string) => {
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
tags: {
feature: "tracing",
type: "observation",
kind: "delete",
projectId,
},
});
};
export const deleteObservationsOlderThanDays = async (
projectId: string,
days: number,
) => {
const query = `
DELETE FROM observations
WHERE project_id = {projectId: String}
AND start_time < now() - INTERVAL {numDays: Int} DAYS;
`;
await commandClickhouse({
query: query,
params: {
projectId,
numDays: days,
},
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
tags: {
feature: "tracing",
type: "observation",
kind: "delete",
projectId,
},
});
};
@@ -990,6 +1047,12 @@ export const getObservationsWithPromptName = async (
projectId,
promptNames,
},
tags: {
feature: "tracing",
type: "observation",
kind: "list",
projectId,
},
});
return rows.map((r) => ({
@@ -1052,6 +1115,12 @@ export const getObservationMetricsForPrompts = async (
projectId,
promptIds,
},
tags: {
feature: "tracing",
type: "observation",
kind: "analytic",
projectId,
},
});
return rows.map((r) => ({
@@ -1070,6 +1139,7 @@ export const getObservationMetricsForPrompts = async (
export const getLatencyAndTotalCostForObservations = async (
projectId: string,
observationIds: string[],
timestamp?: Date,
) => {
const query = `
SELECT
@@ -1078,7 +1148,8 @@ export const getLatencyAndTotalCostForObservations = async (
dateDiff('millisecond', start_time, end_time) AS latency_ms
FROM observations FINAL
WHERE project_id = {projectId: String}
AND id IN ({observationIds: Array(String)})
AND id IN ({observationIds: Array(String)})
${timestamp ? `AND start_time >= {timestamp: DateTime64(3)}` : ""}
`;
const rows = await queryClickhouse<{
id: string;
@@ -1089,6 +1160,15 @@ export const getLatencyAndTotalCostForObservations = async (
params: {
projectId,
observationIds,
...(timestamp
? { timestamp: convertDateToClickhouseDateTime(timestamp) }
: {}),
},
tags: {
feature: "tracing",
type: "observation",
kind: "analytic",
projectId,
},
});
@@ -1102,6 +1182,7 @@ export const getLatencyAndTotalCostForObservations = async (
export const getLatencyAndTotalCostForObservationsByTraces = async (
projectId: string,
traceIds: string[],
timestamp?: Date,
) => {
const query = `
SELECT
@@ -1111,6 +1192,7 @@ export const getLatencyAndTotalCostForObservationsByTraces = async (
FROM observations FINAL
WHERE project_id = {projectId: String}
AND trace_id IN ({traceIds: Array(String)})
${timestamp ? `AND start_time >= {timestamp: DateTime64(3)}` : ""}
GROUP BY trace_id
`;
const rows = await queryClickhouse<{
@@ -1122,6 +1204,15 @@ export const getLatencyAndTotalCostForObservationsByTraces = async (
params: {
projectId,
traceIds,
...(timestamp
? { timestamp: convertDateToClickhouseDateTime(timestamp) }
: {}),
},
tags: {
feature: "tracing",
type: "observation",
kind: "analytic",
projectId,
},
});
@@ -1155,6 +1246,11 @@ export const getObservationCountsByProjectInCreationInterval = async ({
start: convertDateToClickhouseDateTime(start),
end: convertDateToClickhouseDateTime(end),
},
tags: {
feature: "tracing",
type: "observation",
kind: "analytic",
},
});
return rows.map((row) => ({
@@ -1184,6 +1280,11 @@ export const getObservationCountOfProjectsSinceCreationDate = async ({
projectIds,
start: convertDateToClickhouseDateTime(start),
},
tags: {
feature: "tracing",
type: "observation",
kind: "analytic",
},
});
return Number(rows[0]?.count ?? 0);
@@ -1208,6 +1309,12 @@ export const getTraceIdsForObservations = async (
projectId,
observationIds,
},
tags: {
feature: "tracing",
type: "observation",
kind: "list",
projectId,
},
});
return rows.map((row) => ({
@@ -1261,6 +1368,12 @@ export const getGenerationsForPostHog = async function* (
minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
},
tags: {
feature: "posthog",
type: "observation",
kind: "analytic",
projectId,
},
});
const baseUrl = env.NEXTAUTH_URL?.replace("/api/auth", "");
@@ -1,14 +1,14 @@
import {
Observation,
ObservationView,
ObservationType,
ObservationLevel,
Prisma,
} from "@prisma/client";
import { Prisma } from "@prisma/client";
import Decimal from "decimal.js";
import { parseClickhouseUTCDateTimeFormat } from "./clickhouse";
import { ObservationRecordReadType } from "./definitions";
import { parseJsonPrioritised } from "../../utils/json";
import {
Observation,
ObservationView,
ObservationType,
ObservationLevelType,
} from "./types";
export const convertObservationToView = (
record: ObservationRecordReadType,
@@ -55,6 +55,7 @@ export const convertObservation = (
traceId: record.trace_id ?? null,
projectId: record.project_id,
type: record.type as ObservationType,
environment: record.environment,
parentObservationId: record.parent_observation_id ?? null,
startTime: parseClickhouseUTCDateTimeFormat(record.start_time),
endTime: record.end_time
@@ -69,7 +70,7 @@ export const convertObservation = (
val && parseJsonPrioritised(val),
]),
),
level: record.level as ObservationLevel,
level: record.level as ObservationLevelType,
statusMessage: record.status_message ?? null,
version: record.version ?? null,
input: (record.input
@@ -1,4 +1,5 @@
import { Score, ScoreDataType, ScoreSource } from "@prisma/client";
import { ScoreDataType } from "@prisma/client";
import { Score, ScoreSourceType } from "./types";
import {
commandClickhouse,
parseClickhouseUTCDateTimeFormat,
@@ -6,7 +7,7 @@ import {
queryClickhouseStream,
upsertClickhouse,
} from "./clickhouse";
import { FilterList } from "../queries/clickhouse-sql/clickhouse-filter";
import { FilterList, orderByToClickhouseSql } from "../queries";
import { FilterCondition, FilterState, TimeFilter } from "../../types";
import {
createFilterFromFilterState,
@@ -17,7 +18,6 @@ import {
dashboardColumnDefinitions,
scoresTableUiColumnDefinitions,
} from "../../tableDefinitions";
import { orderByToClickhouseSql } from "../queries/clickhouse-sql/orderby-factory";
import {
convertScoreAggregation,
convertToScore,
@@ -64,6 +64,12 @@ export const searchExistingAnnotationScore = async (
traceId,
observationId,
},
tags: {
feature: "tracing",
type: "score",
kind: "list",
projectId,
},
});
return rows.map(convertToScore).shift();
};
@@ -71,7 +77,7 @@ export const searchExistingAnnotationScore = async (
export const getScoreById = async (
projectId: string,
scoreId: string,
source?: ScoreSource,
source?: ScoreSourceType,
) => {
const query = `
SELECT *
@@ -91,6 +97,12 @@ export const getScoreById = async (
scoreId,
...(source !== undefined ? { source } : {}),
},
tags: {
feature: "tracing",
type: "score",
kind: "byId",
projectId,
},
});
return rows.map(convertToScore).shift();
};
@@ -98,7 +110,7 @@ export const getScoreById = async (
export const getScoresByIds = async (
projectId: string,
scoreId: string[],
source?: ScoreSource,
source?: ScoreSourceType,
) => {
const query = `
SELECT *
@@ -117,6 +129,12 @@ export const getScoresByIds = async (
scoreId,
...(source !== undefined ? { source } : {}),
},
tags: {
feature: "tracing",
type: "score",
kind: "byId",
projectId,
},
});
return rows.map(convertToScore);
};
@@ -133,6 +151,12 @@ export const upsertScore = async (score: Partial<ScoreRecordReadType>) => {
table: "scores",
records: [score as ScoreRecordReadType],
eventBodyMapper: convertToScore,
tags: {
feature: "tracing",
type: "score",
kind: "upsert",
projectId: score.project_id ?? "",
},
});
};
@@ -169,6 +193,12 @@ export const getScoresForTraces = async (props: GetScoresForTracesProps) => {
? { traceTimestamp: convertDateToClickhouseDateTime(timestamp) }
: {}),
},
tags: {
feature: "tracing",
type: "score",
kind: "list",
projectId,
},
});
return rows.map(convertToScore);
@@ -199,6 +229,12 @@ export const getScoresForObservations = async (
limit: limit,
offset: offset,
},
tags: {
feature: "tracing",
type: "score",
kind: "list",
projectId,
},
});
return rows.map(convertToScore);
@@ -235,11 +271,17 @@ export const getScoresGroupedByNameSourceType = async (
? { timestamp: convertDateToClickhouseDateTime(timestamp) }
: {}),
},
tags: {
feature: "tracing",
type: "score",
kind: "list",
projectId,
},
});
return rows.map((row) => ({
name: row.name,
source: row.source as ScoreSource,
source: row.source as ScoreSourceType,
dataType: row.data_type as ScoreDataType,
}));
};
@@ -285,6 +327,12 @@ export const getScoresGroupedByName = async (
projectId: projectId,
...(timestampFilterRes ? timestampFilterRes.params : {}),
},
tags: {
feature: "tracing",
type: "score",
kind: "list",
projectId,
},
});
return rows;
@@ -301,6 +349,7 @@ export const getScoresUiCount = async (props: {
select: `
count(*) as count
`,
tags: { kind: "count" },
...props,
});
@@ -323,6 +372,7 @@ export const getScoresUiTable = async (props: {
const rows = await getScoresUiGeneric<{
id: string;
project_id: string;
environment: string;
name: string;
value: number;
string_value: string | null;
@@ -347,6 +397,7 @@ export const getScoresUiTable = async (props: {
select: `
s.id,
s.project_id,
s.environment,
s.name,
s.value,
s.string_value,
@@ -369,11 +420,13 @@ export const getScoresUiTable = async (props: {
t.name as trace_name,
t.tags as trace_tags
`,
tags: { kind: "analytic" },
...props,
});
return rows.map((row) => ({
projectId: row.project_id,
environment: row.environment,
authorUserId: row.author_user_id,
traceId: row.trace_id,
observationId: row.observation_id,
@@ -387,7 +440,7 @@ export const getScoresUiTable = async (props: {
stringValue: row.string_value,
comment: row.comment,
dataType: row.data_type as ScoreDataType,
source: row.source as ScoreSource,
source: row.source as ScoreSourceType,
name: row.name,
value: row.value,
timestamp: parseClickhouseUTCDateTimeFormat(row.timestamp),
@@ -402,6 +455,7 @@ export const getScoresUiGeneric = async <T>(props: {
orderBy: OrderByState;
limit?: number;
offset?: number;
tags?: Record<string, string>;
}): Promise<T[]> => {
const { select, projectId, filter, orderBy, limit, offset } = props;
@@ -436,6 +490,12 @@ export const getScoresUiGeneric = async <T>(props: {
limit: limit,
offset: offset,
},
tags: {
...(props.tags ?? {}),
feature: "tracing",
type: "score",
projectId,
},
});
return rows;
@@ -476,6 +536,12 @@ export const getScoreNames = async (
projectId: projectId,
...(timestampFilterRes ? timestampFilterRes.params : {}),
},
tags: {
feature: "tracing",
type: "score",
kind: "list",
projectId,
},
});
return rows.map((row) => ({
@@ -496,6 +562,12 @@ export const deleteScore = async (projectId: string, scoreId: string) => {
projectId,
scoreId,
},
tags: {
feature: "tracing",
type: "score",
kind: "delete",
projectId,
},
});
};
@@ -517,6 +589,12 @@ export const deleteScoresByTraceIds = async (
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
tags: {
feature: "tracing",
type: "score",
kind: "delete",
projectId,
},
});
};
@@ -533,6 +611,39 @@ export const deleteScoresByProjectId = async (projectId: string) => {
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
tags: {
feature: "tracing",
type: "score",
kind: "delete",
projectId,
},
});
};
export const deleteScoresOlderThanDays = async (
projectId: string,
days: number,
) => {
const query = `
DELETE FROM scores
WHERE project_id = {projectId: String}
AND timestamp < now() - INTERVAL {numDays: Int} DAYS;
`;
await commandClickhouse({
query: query,
params: {
projectId,
numDays: days,
},
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
tags: {
feature: "tracing",
type: "score",
kind: "delete",
projectId,
},
});
};
@@ -567,6 +678,12 @@ export const getNumericScoreHistogram = async (
limit,
...(chFilterRes ? chFilterRes.params : {}),
},
tags: {
feature: "tracing",
type: "score",
kind: "analytic",
projectId,
},
});
};
@@ -603,6 +720,12 @@ export const getAggregatedScoresForPrompts = async (
projectId,
promptIds,
},
tags: {
feature: "tracing",
type: "score",
kind: "analytic",
projectId,
},
});
return rows.map((row) => ({
@@ -634,6 +757,11 @@ export const getScoreCountsByProjectInCreationInterval = async ({
start: convertDateToClickhouseDateTime(start),
end: convertDateToClickhouseDateTime(end),
},
tags: {
feature: "tracing",
type: "score",
kind: "analytic",
},
});
return rows.map((row) => ({
@@ -672,6 +800,12 @@ export const getDistinctScoreNames = async (
}
: {}),
},
tags: {
feature: "tracing",
type: "score",
kind: "list",
projectId,
},
});
return rows.map((row) => row.name);
@@ -712,6 +846,12 @@ export const getScoresForPostHog = async function* (
minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
},
tags: {
feature: "posthog",
type: "score",
kind: "analytic",
projectId,
},
});
const baseUrl = env.NEXTAUTH_URL?.replace("/api/auth", "");
@@ -738,3 +878,27 @@ export const getScoresForPostHog = async function* (
};
}
};
export const hasAnyScore = async (projectId: string) => {
const query = `
SELECT 1
FROM scores
WHERE project_id = {projectId: String}
LIMIT 1
`;
const rows = await queryClickhouse<{ 1: number }>({
query,
params: {
projectId,
},
tags: {
feature: "tracing",
type: "score",
kind: "hasAny",
projectId,
},
});
return rows.length > 0;
};
@@ -1,5 +1,6 @@
import { ScoreSource, ScoreDataType, Score } from "@prisma/client";
import { ScoreDataType } from "@prisma/client";
import { ScoreRecordReadType } from "./definitions";
import { Score, ScoreSourceType } from "./types";
export type ScoreAggregation = {
id: string;
@@ -16,11 +17,12 @@ export const convertToScore = (row: ScoreRecordReadType): Score => {
id: row.id,
timestamp: new Date(row.timestamp),
projectId: row.project_id,
environment: row.environment,
traceId: row.trace_id,
observationId: row.observation_id ?? null,
name: row.name,
value: row.value ?? null,
source: row.source as ScoreSource,
source: row.source as ScoreSourceType,
comment: row.comment ?? null,
authorUserId: row.author_user_id ?? null,
configId: row.config_id ?? null,
@@ -38,7 +40,7 @@ export const convertScoreAggregation = (row: ScoreAggregation) => {
name: row.name,
stringValue: row.string_value,
value: Number(row.value),
source: row.source as ScoreSource,
source: row.source as ScoreSourceType,
dataType: row.data_type as ScoreDataType,
comment: row.comment,
};
@@ -59,3 +59,14 @@ export const getPublicSessionsFilter = async (
? [...filter.filter((f) => f.column !== "⭐️"), ...additionalBookmarkFilter]
: [...additionalBookmarkFilter];
};
export const hasAnySession = async (projectId: string) => {
const count = await prisma.traceSession.count({
where: {
projectId,
},
take: 1,
});
return count > 0;
};
@@ -100,6 +100,12 @@ export const checkTraceExists = async (
? { timestamp: convertDateToClickhouseDateTime(timestamp) }
: {}),
},
tags: {
feature: "tracing",
type: "trace",
kind: "exists",
projectId,
},
});
return rows.length > 0;
@@ -117,6 +123,12 @@ export const upsertTrace = async (trace: Partial<TraceRecordReadType>) => {
table: "traces",
records: [trace as TraceRecordReadType],
eventBodyMapper: convertClickhouseToDomain,
tags: {
feature: "tracing",
type: "trace",
kind: "upsert",
projectId: trace.project_id ?? "",
},
});
};
@@ -140,6 +152,12 @@ export const getTracesByIds = async (
projectId,
timestamp: timestamp ? convertDateToClickhouseDateTime(timestamp) : null,
},
tags: {
feature: "tracing",
type: "trace",
kind: "byId",
projectId,
},
});
return records.map(convertClickhouseToDomain);
@@ -165,6 +183,12 @@ export const getTracesBySessionId = async (
projectId,
timestamp: timestamp ? convertDateToClickhouseDateTime(timestamp) : null,
},
tags: {
feature: "tracing",
type: "trace",
kind: "list",
projectId,
},
});
return records.map(convertClickhouseToDomain);
@@ -172,20 +196,26 @@ export const getTracesBySessionId = async (
export const hasAnyTrace = async (projectId: string) => {
const query = `
SELECT count(*) as count
SELECT 1
FROM traces
WHERE project_id = {projectId: String}
LIMIT 1
`;
const rows = await queryClickhouse<{ count: string }>({
const rows = await queryClickhouse<{ 1: number }>({
query,
params: {
projectId,
},
tags: {
feature: "tracing",
type: "trace",
kind: "hasAny",
projectId,
},
});
return rows.length > 0 && Number(rows[0].count) > 0;
return rows.length > 0;
};
export const getTraceCountsByProjectInCreationInterval = async ({
@@ -211,6 +241,11 @@ export const getTraceCountsByProjectInCreationInterval = async ({
start: convertDateToClickhouseDateTime(start),
end: convertDateToClickhouseDateTime(end),
},
tags: {
feature: "tracing",
type: "trace",
kind: "analytic",
},
});
return rows.map((row) => ({
@@ -243,6 +278,12 @@ export const getTraceById = async (
? { timestamp: convertDateToClickhouseDateTime(timestamp) }
: {}),
},
tags: {
feature: "tracing",
type: "trace",
kind: "byId",
projectId,
},
});
const res = records.map(convertClickhouseToDomain);
@@ -269,7 +310,7 @@ export const getTracesGroupedByName = async (
select
name as name,
count(*) as count
from traces t
from traces t FINAL
WHERE t.project_id = {projectId: String}
AND t.name IS NOT NULL
${timestampFilterRes?.query ? `AND ${timestampFilterRes.query}` : ""}
@@ -287,6 +328,12 @@ export const getTracesGroupedByName = async (
projectId: projectId,
...(timestampFilterRes ? timestampFilterRes.params : {}),
},
tags: {
feature: "tracing",
type: "trace",
kind: "analytic",
projectId,
},
});
return rows;
@@ -343,6 +390,12 @@ export const getTracesGroupedByUsers = async (
...(tracesFilterRes ? tracesFilterRes.params : {}),
...(searchQuery ? search.params : {}),
},
tags: {
feature: "tracing",
type: "trace",
kind: "analytic",
projectId,
},
});
return rows;
@@ -380,6 +433,12 @@ export const getTracesGroupedByTags = async (props: GroupedTracesQueryProp) => {
projectId: projectId,
...(filterRes ? filterRes.params : {}),
},
tags: {
feature: "tracing",
type: "trace",
kind: "analytic",
projectId,
},
});
return rows;
@@ -414,6 +473,12 @@ export const getTracesIdentifierForSession = async (
projectId,
sessionId,
},
tags: {
feature: "tracing",
type: "trace",
kind: "list",
projectId,
},
});
return rows.map((row) => ({
@@ -439,6 +504,39 @@ export const deleteTraces = async (projectId: string, traceIds: string[]) => {
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
tags: {
feature: "tracing",
type: "trace",
kind: "delete",
projectId,
},
});
};
export const deleteTracesOlderThanDays = async (
projectId: string,
days: number,
) => {
const query = `
DELETE FROM traces
WHERE project_id = {projectId: String}
AND timestamp < now() - INTERVAL {numDays: Int} DAYS;
`;
await commandClickhouse({
query: query,
params: {
projectId,
numDays: days,
},
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
tags: {
feature: "tracing",
type: "trace",
kind: "delete",
projectId,
},
});
};
@@ -455,9 +553,41 @@ export const deleteTracesByProjectId = async (projectId: string) => {
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
tags: {
feature: "tracing",
type: "trace",
kind: "delete",
projectId,
},
});
};
export const hasAnyUser = async (projectId: string) => {
const query = `
SELECT 1
FROM traces
WHERE project_id = {projectId: String}
AND user_id IS NOT NULL
AND user_id != ''
LIMIT 1
`;
const rows = await queryClickhouse<{ 1: number }>({
query,
params: {
projectId,
},
tags: {
feature: "tracing",
type: "user",
kind: "hasAny",
projectId,
},
});
return rows.length > 0;
};
export const getTotalUserCount = async (
projectId: string,
filter: FilterState,
@@ -489,6 +619,12 @@ export const getTotalUserCount = async (
...tracesFilterRes.params,
...search.params,
},
tags: {
feature: "tracing",
type: "trace",
kind: "analytic",
projectId,
},
});
};
@@ -617,6 +753,12 @@ export const getUserMetrics = async (
}
: {}),
},
tags: {
feature: "tracing",
type: "trace",
kind: "analytic",
projectId,
},
});
return rows.map((row) => ({
@@ -677,6 +819,12 @@ export const getTracesForPostHog = async function* (
minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
},
tags: {
feature: "posthog",
type: "trace",
kind: "analytic",
projectId,
},
});
const baseUrl = env.NEXTAUTH_URL?.replace("/api/auth", "");
@@ -721,6 +869,11 @@ export const getTracesByIdsForAnyProject = async (traceIds: string[]) => {
params: {
traceIds,
},
tags: {
feature: "tracing",
type: "trace",
kind: "list",
},
});
return records.map((record) => ({
@@ -1,8 +1,9 @@
import { Prisma, Trace } from "@prisma/client";
import { Prisma } from "@prisma/client";
import { parseClickhouseUTCDateTimeFormat } from "./clickhouse";
import { TraceRecordReadType } from "./definitions";
import { convertDateToClickhouseDateTime } from "../clickhouse/client";
import { parseJsonPrioritised } from "../../utils/json";
import { Trace } from "./types";
export const convertTraceDomainToClickhouse = (
trace: Trace,
@@ -13,6 +14,7 @@ export const convertTraceDomainToClickhouse = (
name: trace.name,
user_id: trace.userId,
metadata: trace.metadata as Record<string, string>,
environment: trace.environment,
release: trace.release,
version: trace.version,
project_id: trace.projectId,
@@ -37,6 +39,7 @@ export const convertClickhouseToDomain = (
projectId: record.project_id,
name: record.name ?? null,
timestamp: parseClickhouseUTCDateTimeFormat(record.timestamp),
environment: record.environment,
tags: record.tags,
bookmarked: record.bookmarked,
release: record.release ?? null,
@@ -1,3 +1,144 @@
import { Prisma, ScoreDataType } from "@prisma/client";
import Decimal from "decimal.js";
export type TableCount = {
count: number;
};
export const ObservationType = {
SPAN: "SPAN",
EVENT: "EVENT",
GENERATION: "GENERATION",
} as const;
export type ObservationType =
(typeof ObservationType)[keyof typeof ObservationType];
export const ObservationLevel = {
DEBUG: "DEBUG",
DEFAULT: "DEFAULT",
WARNING: "WARNING",
ERROR: "ERROR",
} as const;
export type ObservationLevelType =
(typeof ObservationLevel)[keyof typeof ObservationLevel];
export const ScoreSource = {
ANNOTATION: "ANNOTATION",
API: "API",
EVAL: "EVAL",
} as const;
export type ScoreSourceType = (typeof ScoreSource)[keyof typeof ScoreSource];
export type Observation = {
id: string;
traceId: string | null;
projectId: string;
environment: string;
type: ObservationType;
startTime: Date;
endTime: Date | null;
name: string | null;
metadata: Prisma.JsonValue | null;
parentObservationId: string | null;
level: ObservationLevelType;
statusMessage: string | null;
version: string | null;
createdAt: Date;
updatedAt: Date;
model: string | null;
internalModel: string | null;
internalModelId: string | null;
modelParameters: unknown | null;
input: unknown | null;
output: unknown | null;
promptTokens: number;
completionTokens: number;
totalTokens: number;
unit: string | null;
inputCost: Decimal | null;
outputCost: Decimal | null;
totalCost: Decimal | null;
calculatedInputCost: Decimal | null;
calculatedOutputCost: Decimal | null;
calculatedTotalCost: Decimal | null;
completionStartTime: Date | null;
promptId: string | null;
};
export type ObservationView = {
id: string;
traceId: string | null;
projectId: string;
type: ObservationType;
startTime: Date;
endTime: Date | null;
environment: string;
name: string | null;
metadata: Prisma.JsonValue | null;
parentObservationId: string | null;
level: ObservationLevelType;
statusMessage: string | null;
version: string | null;
createdAt: Date;
updatedAt: Date;
model: string | null;
modelParameters: unknown | null;
input: unknown | null;
output: unknown | null;
promptTokens: number;
completionTokens: number;
totalTokens: number;
unit: string | null;
completionStartTime: Date | null;
promptId: string | null;
promptName: string | null;
promptVersion: number | null;
modelId: string | null;
inputPrice: Decimal | null;
outputPrice: Decimal | null;
totalPrice: Decimal | null;
calculatedInputCost: Decimal | null;
calculatedOutputCost: Decimal | null;
calculatedTotalCost: Decimal | null;
latency: number | null;
timeToFirstToken: number | null;
};
export type Score = {
id: string;
timestamp: Date;
projectId: string;
environment: string;
name: string;
value: number | null;
source: ScoreSourceType;
authorUserId: string | null;
comment: string | null;
traceId: string;
observationId: string | null;
configId: string | null;
stringValue: string | null;
queueId: string | null;
createdAt: Date;
updatedAt: Date;
dataType: ScoreDataType;
};
export type Trace = {
id: string;
timestamp: Date;
name: string | null;
userId: string | null;
environment: string;
metadata: Prisma.JsonValue | null;
release: string | null;
version: string | null;
projectId: string;
public: boolean;
bookmarked: boolean;
tags: string[];
input: unknown | null;
output: unknown | null;
sessionId: string | null;
createdAt: Date;
updatedAt: Date;
externalId: string | null;
};
@@ -49,6 +49,7 @@ export const getSessionsTableCount = async (props: {
orderBy: props.orderBy,
limit: props.limit,
page: props.page,
tags: { kind: "count" },
});
return rows.length > 0 ? Number(rows[0].count) : 0;
@@ -68,6 +69,7 @@ export const getSessionsTable = async (props: {
orderBy: props.orderBy,
limit: props.limit,
page: props.page,
tags: { kind: "list" },
});
return rows.map((row) => ({
@@ -90,6 +92,7 @@ export const getSessionsWithMetrics = async (props: {
orderBy: props.orderBy,
limit: props.limit,
page: props.page,
tags: { kind: "analytic" },
});
return rows.map((row) => ({
@@ -107,6 +110,7 @@ export type FetchSessionsTableProps = {
orderBy?: OrderByState;
limit?: number;
page?: number;
tags?: Record<string, string>;
};
const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {
@@ -267,7 +271,9 @@ const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {
? `
,
sum(o.obs_count) as total_observations,
date_diff('millisecond', min(min_start_time), max(max_end_time)) as duration,
-- Use minIf, because ClickHouse fills 1970-01-01 on left joins. We assume that no
-- LLM session started on that date so this behaviour should yield better results.
date_diff('millisecond', minIf(min_start_time, min_start_time > '1970-01-01'), max(max_end_time)) as duration,
sumMap(o.sum_usage_details) as session_usage_details,
sumMap(o.sum_cost_details) as session_cost_details,
arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, sumMap(o.sum_cost_details)))) as session_input_cost,
@@ -313,6 +319,12 @@ const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {
? { observationsStartTime: obsStartTimeValue }
: {}),
},
tags: {
...(props.tags ?? {}),
feature: "tracing",
type: "sessions-table",
projectId,
},
});
return res;
@@ -1,4 +1,3 @@
import { ObservationLevel } from "@prisma/client";
import { OrderByState } from "../../interfaces/orderBy";
import { tracesTableUiColumnDefinitions } from "../../tableDefinitions";
import { FilterState } from "../../types";
@@ -13,18 +12,17 @@ import {
} from "../queries/clickhouse-sql/factory";
import { orderByToClickhouseSql } from "../queries/clickhouse-sql/orderby-factory";
import { clickhouseSearchCondition } from "../queries/clickhouse-sql/search";
import {
parseClickhouseUTCDateTimeFormat,
queryClickhouse,
} from "../repositories/clickhouse";
import { TraceRecordReadType } from "../repositories/definitions";
import Decimal from "decimal.js";
import { ScoreAggregate } from "../../features/scores";
import {
OBSERVATIONS_TO_TRACE_INTERVAL,
SCORE_TO_TRACE_OBSERVATIONS_INTERVAL,
} from "../repositories/constants";
import Decimal from "decimal.js";
import { ScoreAggregate } from "../../features/scores";
import { reduceUsageOrCostDetails } from "../repositories";
ObservationLevelType,
reduceUsageOrCostDetails,
parseClickhouseUTCDateTimeFormat,
queryClickhouse,
} from "../repositories";
export type TracesTableReturnType = Pick<
TraceRecordReadType,
@@ -62,7 +60,7 @@ export type TracesMetricsUiReturnType = {
completionTokens: bigint;
totalTokens: bigint;
latency: number | null;
level: ObservationLevel;
level: ObservationLevelType;
observationCount: bigint;
calculatedTotalCost: Decimal | null;
calculatedInputCost: Decimal | null;
@@ -140,7 +138,7 @@ export type TracesTableMetricsClickhouseReturnType = {
id: string;
project_id: string;
timestamp: Date;
level: ObservationLevel;
level: ObservationLevelType;
observation_count: number | null;
latency: string | null;
usage_details: Record<string, number>;
@@ -160,6 +158,7 @@ export type FetchTracesTableProps = {
orderBy?: OrderByState;
limit?: number;
page?: number;
tags?: Record<string, string>;
};
export const getTracesTableCount = async (props: {
@@ -172,6 +171,7 @@ export const getTracesTableCount = async (props: {
}) => {
const countRows = await getTracesTableGeneric<{ count: string }>({
select: "count",
tags: { kind: "count" },
...props,
});
@@ -193,6 +193,7 @@ export const getTracesTableMetrics = async (props: {
const countRows =
await getTracesTableGeneric<TracesTableMetricsClickhouseReturnType>({
select: "metrics",
tags: { kind: "analytic" },
...props,
});
@@ -209,6 +210,7 @@ export const getTracesTable = async (
) => {
const rows = await getTracesTableGeneric<TracesTableReturnType>({
select: "rows",
tags: { kind: "list" },
projectId,
filter,
searchQuery,
@@ -354,6 +356,7 @@ const getTracesTableGeneric = async <T>(props: FetchTracesTableProps) => {
column: "timestamp_to_date",
order: orderBy.order,
},
{ column: "timestamp", order: orderBy.order },
{ column: "event_ts", order: "DESC" as "DESC" },
]
: null,
@@ -442,6 +445,12 @@ const getTracesTableGeneric = async <T>(props: FetchTracesTableProps) => {
...scoresFilterRes.params,
...search.params,
},
tags: {
...(props.tags ?? {}),
feature: "tracing",
type: "traces-table",
projectId,
},
});
return res;
@@ -11,6 +11,7 @@ export const createTrace = (trace: Partial<TraceRecordInsertType>) => {
project_id: v4(),
session_id: v4(),
timestamp: Date.now(),
environment: "default",
metadata: {
source: "API",
server: "Node",
@@ -38,6 +39,7 @@ export const createObservation = (
trace_id: v4(),
project_id: v4(),
type: "GENERATION",
environment: "default",
metadata: {
source: "API",
server: "Node",
@@ -76,6 +78,7 @@ export const createScore = (score: Partial<ScoreRecordInsertType>) => {
project_id: v4(),
trace_id: v4(),
observation_id: v4(),
environment: "default",
name: "test-score" + v4(),
timestamp: Date.now(),
value: 100.5,
@@ -145,6 +145,7 @@ export const observationsTableUiColumnDefinitions: UiColumnMapping[] = [
clickhouseTableName: "observations",
clickhouseSelect:
"arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, usage_details)))",
clickhouseTypeOverwrite: "Decimal64(3)",
},
{
uiTableName: "Output Tokens",
@@ -152,6 +153,7 @@ export const observationsTableUiColumnDefinitions: UiColumnMapping[] = [
clickhouseTableName: "observations",
clickhouseSelect:
"arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, usage_details)))",
clickhouseTypeOverwrite: "Decimal64(3)",
},
{
uiTableName: "Total Tokens",
@@ -159,6 +161,7 @@ export const observationsTableUiColumnDefinitions: UiColumnMapping[] = [
clickhouseTableName: "observations",
clickhouseSelect:
"if(mapExists((k, v) -> (k = 'total'), usage_details), usage_details['total'], NULL)",
clickhouseTypeOverwrite: "Decimal64(3)",
},
{
uiTableName: "Usage",
@@ -166,6 +169,7 @@ export const observationsTableUiColumnDefinitions: UiColumnMapping[] = [
clickhouseTableName: "observations",
clickhouseSelect:
"if(mapExists((k, v) -> (k = 'total'), usage_details), usage_details['total'], NULL)",
clickhouseTypeOverwrite: "Decimal64(3)",
},
{
uiTableName: "Metadata",
@@ -58,30 +58,35 @@ export const sessionCols: UiColumnMapping[] = [
uiTableId: "inputTokens",
clickhouseTableName: "traces",
clickhouseSelect: "session_input_usage",
clickhouseTypeOverwrite: "Decimal64(3)",
},
{
uiTableName: "Output Tokens",
uiTableId: "outputTokens",
clickhouseTableName: "traces",
clickhouseSelect: "session_output_usage",
clickhouseTypeOverwrite: "Decimal64(3)",
},
{
uiTableName: "Total Tokens",
uiTableId: "totalTokens",
clickhouseTableName: "traces",
clickhouseSelect: "session_total_usage",
clickhouseTypeOverwrite: "Decimal64(3)",
},
{
uiTableName: "Usage",
uiTableId: "totalTokens",
clickhouseTableName: "traces",
clickhouseSelect: "session_total_usage",
clickhouseTypeOverwrite: "Decimal64(3)",
},
{
uiTableName: "Session Total Usage",
uiTableId: "usage",
clickhouseTableName: "traces",
clickhouseSelect: "session_total_usage",
clickhouseTypeOverwrite: "Decimal64(3)",
},
{
uiTableName: "Session Duration (s)",
@@ -98,6 +98,7 @@ export const tracesTableUiColumnDefinitions: UiColumnMapping[] = [
clickhouseTableName: "observations",
clickhouseSelect:
"arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, usage_details)))",
clickhouseTypeOverwrite: "Decimal64(3)",
},
{
uiTableName: "Output Tokens",
@@ -105,6 +106,7 @@ export const tracesTableUiColumnDefinitions: UiColumnMapping[] = [
clickhouseTableName: "observations",
clickhouseSelect:
"arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, usage_details)))",
clickhouseTypeOverwrite: "Decimal64(3)",
},
{
uiTableName: "Total Tokens",
@@ -112,6 +114,7 @@ export const tracesTableUiColumnDefinitions: UiColumnMapping[] = [
clickhouseTableName: "observations",
clickhouseSelect:
"if(mapExists((k, v) -> (k = 'total'), usage_details), usage_details['total'], NULL)",
clickhouseTypeOverwrite: "Decimal64(3)",
},
{
uiTableName: "Usage",
@@ -119,6 +122,7 @@ export const tracesTableUiColumnDefinitions: UiColumnMapping[] = [
clickhouseTableName: "observations",
clickhouseSelect:
"if(mapExists((k, v) -> (k = 'total'), usage_details), usage_details['total'], NULL)",
clickhouseTypeOverwrite: "Decimal64(3)",
},
{
uiTableName: "Scores",
@@ -1,4 +1,4 @@
import { ObservationLevel } from "@prisma/client";
import { ObservationLevelType } from "../server";
import { ColumnDefinition, OptionsDefinition } from "..";
export const tracesOnlyCols: ColumnDefinition[] = [
@@ -62,7 +62,12 @@ export const tracesOnlyCols: ColumnDefinition[] = [
id: "level",
type: "stringOptions",
internal: '"level"',
options: Object.values(ObservationLevel).map((value) => ({ value })),
options: [
{ value: "DEBUG" },
{ value: "DEFAULT" },
{ value: "WARNING" },
{ value: "ERROR" },
] as { value: ObservationLevelType }[],
},
{
name: "Tags",
+1 -35
View File
@@ -1,6 +1,4 @@
import { z } from "zod";
import { merge } from "lodash";
import { JsonNested, jsonSchema } from "./zod";
import { JsonNested } from "./zod";
/**
* Deeply parses a JSON string or object for nested stringified JSON
@@ -10,7 +8,6 @@ import { JsonNested, jsonSchema } from "./zod";
export function deepParseJson(json: unknown): unknown {
if (typeof json === "string") {
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const parsed = JSON.parse(json);
if (typeof parsed === "number") return json; // numbers that were strings in the input should remain as strings
return deepParseJson(parsed); // Recursively parse parsed value
@@ -40,16 +37,6 @@ export function deepParseJson(json: unknown): unknown {
return json;
}
export const mergeJson = (
json1?: z.infer<typeof jsonSchema>,
json2?: z.infer<typeof jsonSchema>,
) => {
if (json1 === undefined) {
return json2;
}
return merge(json1, json2);
};
export const parseJsonPrioritised = (
json: string,
): JsonNested | string | undefined => {
@@ -59,24 +46,3 @@ export const parseJsonPrioritised = (
return json;
}
};
export const convertRecordToJsonSchema = (
record: Record<string, string>,
): JsonNested | undefined => {
const jsonSchema: JsonNested = {};
// if record is empty, return undefined
if (Object.keys(record).length === 0) {
return undefined;
}
for (const key in record) {
try {
jsonSchema[key] = JSON.parse(record[key]);
} catch (e) {
jsonSchema[key] = record[key];
}
}
return jsonSchema;
};
+20 -14
View File
@@ -4,22 +4,28 @@ export function getIsCharOrUnderscore(value: string): boolean {
return charOrUnderscore.test(value);
}
// Regex for valid variable names (letters, underscores, starting with letter)
export const VARIABLE_REGEX = /^[a-zA-Z][a-zA-Z_]*$/;
// Regex to find variables in mustache syntax
export const MUSTACHE_REGEX = /{{([^{}]*)}}+/g;
// Regex to find multiline variables
export const MULTILINE_VARIABLE_REGEX = /{{[^}]*\n[^}]*}}/g;
// Regex to find unclosed variables
export const UNCLOSED_VARIABLE_REGEX = /{{(?![^{]*}})/g;
export function isValidVariableName(variable: string): boolean {
return VARIABLE_REGEX.test(variable);
}
export function extractVariables(mustacheString: string): string[] {
const mustacheRegex = /\{\{(.*?)\}\}/g;
const uniqueVariables = new Set<string>();
const matches = Array.from(mustacheString.matchAll(MUSTACHE_REGEX))
.map((match) => match[1])
.filter(isValidVariableName);
for (const match of mustacheString.matchAll(mustacheRegex)) {
uniqueVariables.add(match[1]);
}
for (const variable of uniqueVariables) {
// if validated fails, remove from set
if (!getIsCharOrUnderscore(variable)) {
uniqueVariables.delete(variable);
}
}
return Array.from(uniqueVariables);
return [...new Set(matches)];
}
export function stringifyValue(value: unknown) {
+2280 -1603
View File
File diff suppressed because it is too large Load Diff
+7 -4
View File
@@ -108,13 +108,16 @@ ENV NEXT_MANUAL_SIG_HANDLE true
RUN apk add --no-cache dumb-init tzdata
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
# Don't run production as root
ARG UID=1001
ARG GID=1001
RUN addgroup --system --gid ${GID} nodejs
RUN adduser --system --uid ${UID} nextjs
RUN npm install -g --no-package-lock --no-save prisma@5.22.0
RUN npm install -g --no-package-lock --no-save prisma@6.3.0
RUN MIGRATE_TARGET_ARCH=$(echo ${TARGETPLATFORM:-linux/amd64} | sed 's/\//-/g') && \
wget -q -O- https://github.com/golang-migrate/migrate/releases/download/v4.18.0/migrate.$MIGRATE_TARGET_ARCH.tar.gz | tar xvz && \
wget -q -O- https://github.com/golang-migrate/migrate/releases/download/v4.18.2/migrate.$MIGRATE_TARGET_ARCH.tar.gz | tar xvz && \
mv migrate /usr/bin/migrate
COPY --from=builder --chown=nextjs:nodejs /app/web/next.config.mjs .

Some files were not shown because too many files have changed in this diff Show More