langfuse-haystack 0.2.0__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (21) hide show
  1. {langfuse_haystack-0.2.0 → langfuse_haystack-0.4.0}/.gitignore +9 -0
  2. langfuse_haystack-0.4.0/CHANGELOG.md +39 -0
  3. {langfuse_haystack-0.2.0 → langfuse_haystack-0.4.0}/PKG-INFO +31 -5
  4. {langfuse_haystack-0.2.0 → langfuse_haystack-0.4.0}/README.md +30 -4
  5. langfuse_haystack-0.4.0/example/chat.py +54 -0
  6. {langfuse_haystack-0.2.0 → langfuse_haystack-0.4.0}/pyproject.toml +14 -26
  7. {langfuse_haystack-0.2.0 → langfuse_haystack-0.4.0}/src/haystack_integrations/components/connectors/langfuse/langfuse_connector.py +18 -9
  8. {langfuse_haystack-0.2.0 → langfuse_haystack-0.4.0}/src/haystack_integrations/tracing/langfuse/tracer.py +19 -4
  9. langfuse_haystack-0.4.0/tests/test_tracing.py +62 -0
  10. langfuse_haystack-0.2.0/CHANGELOG.md +0 -17
  11. langfuse_haystack-0.2.0/example/chat.py +0 -29
  12. langfuse_haystack-0.2.0/tests/test_tracing.py +0 -57
  13. {langfuse_haystack-0.2.0 → langfuse_haystack-0.4.0}/LICENSE.txt +0 -0
  14. {langfuse_haystack-0.2.0 → langfuse_haystack-0.4.0}/example/basic_rag.py +0 -0
  15. {langfuse_haystack-0.2.0 → langfuse_haystack-0.4.0}/example/requirements.txt +0 -0
  16. {langfuse_haystack-0.2.0 → langfuse_haystack-0.4.0}/pydoc/config.yml +0 -0
  17. {langfuse_haystack-0.2.0 → langfuse_haystack-0.4.0}/src/haystack_integrations/components/connectors/langfuse/__init__.py +0 -0
  18. {langfuse_haystack-0.2.0 → langfuse_haystack-0.4.0}/src/haystack_integrations/tracing/langfuse/__init__.py +0 -0
  19. {langfuse_haystack-0.2.0 → langfuse_haystack-0.4.0}/tests/__init__.py +0 -0
  20. {langfuse_haystack-0.2.0 → langfuse_haystack-0.4.0}/tests/test_langfuse_span.py +0 -0
  21. {langfuse_haystack-0.2.0 → langfuse_haystack-0.4.0}/tests/test_tracer.py +0 -0
@@ -135,3 +135,12 @@ dmypy.json
135
135
  # Docs generation artifacts
136
136
  _readme_*.md
137
137
  .idea
138
+
139
+ # macOS
140
+ .DS_Store
141
+
142
+ # http cache (requests-cache)
143
+ **/http_cache.sqlite
144
+
145
+ # ruff
146
+ .ruff_cache
@@ -0,0 +1,39 @@
1
+ # Changelog
2
+
3
+ ## [unreleased]
4
+
5
+ ### 🚜 Refactor
6
+
7
+ - Remove usage of deprecated `ChatMessage.to_openai_format` (#1001)
8
+
9
+ ### 📚 Documentation
10
+
11
+ - Add link to langfuse in LangfuseConnector (#981)
12
+
13
+ ### 🧪 Testing
14
+
15
+ - Do not retry tests in `hatch run test` command (#954)
16
+
17
+ ### ⚙️ Miscellaneous Tasks
18
+
19
+ - Retry tests to reduce flakyness (#836)
20
+ - `Langfuse` - replace DynamicChatPromptBuilder with ChatPromptBuilder (#925)
21
+ - Remove all `DynamicChatPromptBuilder` references in Langfuse integration (#931)
22
+
23
+ ## [integrations/langfuse-v0.2.0] - 2024-06-18
24
+
25
+ ## [integrations/langfuse-v0.1.0] - 2024-06-13
26
+
27
+ ### 🚀 Features
28
+
29
+ - Langfuse integration (#686)
30
+
31
+ ### 🐛 Bug Fixes
32
+
33
+ - Performance optimizations and value error when streaming in langfuse (#798)
34
+
35
+ ### ⚙️ Miscellaneous Tasks
36
+
37
+ - Use ChatMessage to_openai_format, update unit tests, pydocs (#725)
38
+
39
+ <!-- generated by git-cliff -->
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: langfuse-haystack
3
- Version: 0.2.0
3
+ Version: 0.4.0
4
4
  Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/langfuse#readme
5
5
  Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
6
6
  Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/langfuse
@@ -50,7 +50,33 @@ To enable tracing in your Haystack pipeline, add the `LangfuseConnector` to your
50
50
  You also need to set the `LANGFUSE_SECRET_KEY` and `LANGFUSE_PUBLIC_KEY` environment variables in order to connect to Langfuse account.
51
51
  You can get these keys by signing up for an account on the Langfuse website.
52
52
 
53
- Here's an example:
53
+ ⚠️ **Important:** To ensure proper tracing, always set environment variables before importing any Haystack components. This is crucial because Haystack initializes its internal tracing components during import.
54
+
55
+ Here's the correct way to set up your script:
56
+
57
+ ```python
58
+ import os
59
+
60
+ # Set environment variables first
61
+ os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com"
62
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
63
+ os.environ["HAYSTACK_CONTENT_TRACING_ENABLED"] = "true"
64
+
65
+ # Then import Haystack components
66
+ from haystack.components.builders import ChatPromptBuilder
67
+ from haystack.components.generators.chat import OpenAIChatGenerator
68
+ from haystack.dataclasses import ChatMessage
69
+ from haystack import Pipeline
70
+
71
+ from haystack_integrations.components.connectors.langfuse import LangfuseConnector
72
+
73
+ # Rest of your code...
74
+ ```
75
+
76
+ Alternatively, an even better practice is to set these environment variables in your shell before running the script.
77
+
78
+
79
+ Here's a full example:
54
80
 
55
81
  ```python
56
82
  import os
@@ -59,7 +85,7 @@ os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com"
59
85
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
60
86
  os.environ["HAYSTACK_CONTENT_TRACING_ENABLED"] = "true"
61
87
 
62
- from haystack.components.builders import DynamicChatPromptBuilder
88
+ from haystack.components.builders import ChatPromptBuilder
63
89
  from haystack.components.generators.chat import OpenAIChatGenerator
64
90
  from haystack.dataclasses import ChatMessage
65
91
  from haystack import Pipeline
@@ -69,7 +95,7 @@ from haystack_integrations.components.connectors.langfuse import LangfuseConnect
69
95
  if __name__ == "__main__":
70
96
  pipe = Pipeline()
71
97
  pipe.add_component("tracer", LangfuseConnector("Chat example"))
72
- pipe.add_component("prompt_builder", DynamicChatPromptBuilder())
98
+ pipe.add_component("prompt_builder", ChatPromptBuilder())
73
99
  pipe.add_component("llm", OpenAIChatGenerator(model="gpt-3.5-turbo"))
74
100
 
75
101
  pipe.connect("prompt_builder.prompt", "llm.messages")
@@ -80,7 +106,7 @@ if __name__ == "__main__":
80
106
  ]
81
107
 
82
108
  response = pipe.run(
83
- data={"prompt_builder": {"template_variables": {"location": "Berlin"}, "prompt_source": messages}}
109
+ data={"prompt_builder": {"template_variables": {"location": "Berlin"}, "template": messages}}
84
110
  )
85
111
  print(response["llm"]["replies"][0])
86
112
  print(response["tracer"]["trace_url"])
@@ -27,7 +27,33 @@ To enable tracing in your Haystack pipeline, add the `LangfuseConnector` to your
27
27
  You also need to set the `LANGFUSE_SECRET_KEY` and `LANGFUSE_PUBLIC_KEY` environment variables in order to connect to Langfuse account.
28
28
  You can get these keys by signing up for an account on the Langfuse website.
29
29
 
30
- Here's an example:
30
+ ⚠️ **Important:** To ensure proper tracing, always set environment variables before importing any Haystack components. This is crucial because Haystack initializes its internal tracing components during import.
31
+
32
+ Here's the correct way to set up your script:
33
+
34
+ ```python
35
+ import os
36
+
37
+ # Set environment variables first
38
+ os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com"
39
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
40
+ os.environ["HAYSTACK_CONTENT_TRACING_ENABLED"] = "true"
41
+
42
+ # Then import Haystack components
43
+ from haystack.components.builders import ChatPromptBuilder
44
+ from haystack.components.generators.chat import OpenAIChatGenerator
45
+ from haystack.dataclasses import ChatMessage
46
+ from haystack import Pipeline
47
+
48
+ from haystack_integrations.components.connectors.langfuse import LangfuseConnector
49
+
50
+ # Rest of your code...
51
+ ```
52
+
53
+ Alternatively, an even better practice is to set these environment variables in your shell before running the script.
54
+
55
+
56
+ Here's a full example:
31
57
 
32
58
  ```python
33
59
  import os
@@ -36,7 +62,7 @@ os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com"
36
62
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
37
63
  os.environ["HAYSTACK_CONTENT_TRACING_ENABLED"] = "true"
38
64
 
39
- from haystack.components.builders import DynamicChatPromptBuilder
65
+ from haystack.components.builders import ChatPromptBuilder
40
66
  from haystack.components.generators.chat import OpenAIChatGenerator
41
67
  from haystack.dataclasses import ChatMessage
42
68
  from haystack import Pipeline
@@ -46,7 +72,7 @@ from haystack_integrations.components.connectors.langfuse import LangfuseConnect
46
72
  if __name__ == "__main__":
47
73
  pipe = Pipeline()
48
74
  pipe.add_component("tracer", LangfuseConnector("Chat example"))
49
- pipe.add_component("prompt_builder", DynamicChatPromptBuilder())
75
+ pipe.add_component("prompt_builder", ChatPromptBuilder())
50
76
  pipe.add_component("llm", OpenAIChatGenerator(model="gpt-3.5-turbo"))
51
77
 
52
78
  pipe.connect("prompt_builder.prompt", "llm.messages")
@@ -57,7 +83,7 @@ if __name__ == "__main__":
57
83
  ]
58
84
 
59
85
  response = pipe.run(
60
- data={"prompt_builder": {"template_variables": {"location": "Berlin"}, "prompt_source": messages}}
86
+ data={"prompt_builder": {"template_variables": {"location": "Berlin"}, "template": messages}}
61
87
  )
62
88
  print(response["llm"]["replies"][0])
63
89
  print(response["tracer"]["trace_url"])
@@ -0,0 +1,54 @@
1
+ import os
2
+
3
+ # See README.md for more information on how to set up the environment variables
4
+ # before running this script
5
+
6
+ # In addition to setting the environment variables, you need to install the following packages:
7
+ # pip install cohere-haystack anthropic-haystack
8
+ os.environ["HAYSTACK_CONTENT_TRACING_ENABLED"] = "true"
9
+
10
+ from haystack import Pipeline
11
+ from haystack.components.builders import ChatPromptBuilder
12
+ from haystack.components.generators.chat import HuggingFaceAPIChatGenerator, OpenAIChatGenerator
13
+ from haystack.dataclasses import ChatMessage
14
+ from haystack.utils.auth import Secret
15
+ from haystack.utils.hf import HFGenerationAPIType
16
+
17
+ from haystack_integrations.components.connectors.langfuse import LangfuseConnector
18
+ from haystack_integrations.components.generators.anthropic import AnthropicChatGenerator
19
+ from haystack_integrations.components.generators.cohere import CohereChatGenerator
20
+
21
+ os.environ["HAYSTACK_CONTENT_TRACING_ENABLED"] = "true"
22
+
23
+ selected_chat_generator = "openai"
24
+
25
+ generators = {
26
+ "openai": OpenAIChatGenerator,
27
+ "anthropic": AnthropicChatGenerator,
28
+ "hf_api": lambda: HuggingFaceAPIChatGenerator(
29
+ api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API,
30
+ api_params={"model": "mistralai/Mixtral-8x7B-Instruct-v0.1"},
31
+ token=Secret.from_token(os.environ["HF_API_KEY"]),
32
+ ),
33
+ "cohere": CohereChatGenerator,
34
+ }
35
+
36
+ selected_chat_generator = generators[selected_chat_generator]()
37
+
38
+ if __name__ == "__main__":
39
+
40
+ pipe = Pipeline()
41
+ pipe.add_component("tracer", LangfuseConnector("Chat example"))
42
+ pipe.add_component("prompt_builder", ChatPromptBuilder())
43
+ pipe.add_component("llm", selected_chat_generator)
44
+
45
+ pipe.connect("prompt_builder.prompt", "llm.messages")
46
+
47
+ messages = [
48
+ ChatMessage.from_system("Always respond in German even if some input data is in other languages."),
49
+ ChatMessage.from_user("Tell me about {{location}}"),
50
+ ]
51
+
52
+ response = pipe.run(data={"prompt_builder": {"template_variables": {"location": "Berlin"}, "template": messages}})
53
+ print(response["llm"]["replies"][0])
54
+ print(response["tracer"]["trace_url"])
@@ -10,9 +10,7 @@ readme = "README.md"
10
10
  requires-python = ">=3.8"
11
11
  license = "Apache-2.0"
12
12
  keywords = []
13
- authors = [
14
- { name = "deepset GmbH", email = "info@deepset.ai" },
15
- ]
13
+ authors = [{ name = "deepset GmbH", email = "info@deepset.ai" }]
16
14
  classifiers = [
17
15
  "Development Status :: 4 - Beta",
18
16
  "Programming Language :: Python",
@@ -24,10 +22,7 @@ classifiers = [
24
22
  "Programming Language :: Python :: Implementation :: CPython",
25
23
  "Programming Language :: Python :: Implementation :: PyPy",
26
24
  ]
27
- dependencies = [
28
- "haystack-ai>=2.1.0",
29
- "langfuse"
30
- ]
25
+ dependencies = ["haystack-ai>=2.1.0", "langfuse"]
31
26
 
32
27
  [project.urls]
33
28
  Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/langfuse#readme"
@@ -50,19 +45,18 @@ git_describe_command = 'git describe --tags --match="integrations/langfuse-v[0-9
50
45
  dependencies = [
51
46
  "coverage[toml]>=6.5",
52
47
  "pytest",
48
+ "pytest-rerunfailures",
53
49
  "haystack-pydoc-tools",
50
+ "anthropic-haystack",
51
+ "cohere-haystack"
54
52
  ]
55
53
  [tool.hatch.envs.default.scripts]
56
54
  test = "pytest {args:tests}"
57
55
  test-cov = "coverage run -m pytest {args:tests}"
58
- cov-report = [
59
- "- coverage combine",
60
- "coverage report",
61
- ]
62
- cov = [
63
- "test-cov",
64
- "cov-report",
65
- ]
56
+ test-cov-retry = "test-cov --reruns 3 --reruns-delay 30 -x"
57
+ cov-report = ["- coverage combine", "coverage report"]
58
+ cov = ["test-cov", "cov-report"]
59
+ cov-retry = ["test-cov-retry", "cov-report"]
66
60
  docs = ["pydoc-markdown pydoc/config.yml"]
67
61
 
68
62
 
@@ -75,8 +69,8 @@ dependencies = ["black>=23.1.0", "mypy>=1.0.0", "ruff>=0.0.243"]
75
69
 
76
70
  [tool.hatch.envs.lint.scripts]
77
71
  typing = "mypy --install-types --non-interactive --explicit-package-bases {args:src/ tests}"
78
- style = ["ruff check {args:.}", "black --check --diff {args:.}"]
79
- fmt = ["black {args:.}", "ruff --fix {args:.}", "style"]
72
+ style = ["ruff check {args:. --exclude tests/}", "black --check --diff {args:.}"]
73
+ fmt = ["black {args:.}", "ruff --fix {args:. --exclude tests/}", "style"]
80
74
  all = ["style", "typing"]
81
75
 
82
76
  [tool.hatch.metadata]
@@ -160,12 +154,8 @@ parallel = false
160
154
 
161
155
  [tool.coverage.report]
162
156
  omit = ["*/tests/*", "*/__init__.py"]
163
- show_missing=true
164
- exclude_lines = [
165
- "no cov",
166
- "if __name__ == .__main__.:",
167
- "if TYPE_CHECKING:",
168
- ]
157
+ show_missing = true
158
+ exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"]
169
159
 
170
160
  [[tool.mypy.overrides]]
171
161
  module = [
@@ -179,7 +169,5 @@ ignore_missing_imports = true
179
169
 
180
170
  [tool.pytest.ini_options]
181
171
  addopts = "--strict-markers"
182
- markers = [
183
- "integration: integration tests",
184
- ]
172
+ markers = ["integration: integration tests"]
185
173
  log_cli = true
@@ -1,14 +1,14 @@
1
1
  from haystack import component, tracing
2
- from haystack_integrations.tracing.langfuse import LangfuseTracer
3
2
 
3
+ from haystack_integrations.tracing.langfuse import LangfuseTracer
4
4
  from langfuse import Langfuse
5
5
 
6
6
 
7
7
  @component
8
8
  class LangfuseConnector:
9
9
  """
10
- LangfuseConnector connects Haystack LLM framework with Langfuse in order to enable the tracing of operations
11
- and data flow within various components of a pipeline.
10
+ LangfuseConnector connects Haystack LLM framework with [Langfuse](https://langfuse.com) in order to enable the
11
+ tracing of operations and data flow within various components of a pipeline.
12
12
 
13
13
  Simply add this component to your pipeline, but *do not* connect it to any other component. The LangfuseConnector
14
14
  will automatically trace the operations and data flow within the pipeline.
@@ -40,6 +40,7 @@ class LangfuseConnector:
40
40
 
41
41
  # ...
42
42
 
43
+
43
44
  @app.on_event("shutdown")
44
45
  async def shutdown_event():
45
46
  tracer.actual_tracer.flush()
@@ -53,27 +54,35 @@ class LangfuseConnector:
53
54
  os.environ["HAYSTACK_CONTENT_TRACING_ENABLED"] = "true"
54
55
 
55
56
  from haystack import Pipeline
56
- from haystack.components.builders import DynamicChatPromptBuilder
57
+ from haystack.components.builders import ChatPromptBuilder
57
58
  from haystack.components.generators.chat import OpenAIChatGenerator
58
59
  from haystack.dataclasses import ChatMessage
59
- from haystack_integrations.components.connectors.langfuse import LangfuseConnector
60
+ from haystack_integrations.components.connectors.langfuse import (
61
+ LangfuseConnector,
62
+ )
60
63
 
61
64
  if __name__ == "__main__":
62
-
63
65
  pipe = Pipeline()
64
66
  pipe.add_component("tracer", LangfuseConnector("Chat example"))
65
- pipe.add_component("prompt_builder", DynamicChatPromptBuilder())
67
+ pipe.add_component("prompt_builder", ChatPromptBuilder())
66
68
  pipe.add_component("llm", OpenAIChatGenerator(model="gpt-3.5-turbo"))
67
69
 
68
70
  pipe.connect("prompt_builder.prompt", "llm.messages")
69
71
 
70
72
  messages = [
71
- ChatMessage.from_system("Always respond in German even if some input data is in other languages."),
73
+ ChatMessage.from_system(
74
+ "Always respond in German even if some input data is in other languages."
75
+ ),
72
76
  ChatMessage.from_user("Tell me about {{location}}"),
73
77
  ]
74
78
 
75
79
  response = pipe.run(
76
- data={"prompt_builder": {"template_variables": {"location": "Berlin"}, "prompt_source": messages}}
80
+ data={
81
+ "prompt_builder": {
82
+ "template_variables": {"location": "Berlin"},
83
+ "template": messages,
84
+ }
85
+ }
77
86
  )
78
87
  print(response["llm"]["replies"][0])
79
88
  print(response["tracer"]["trace_url"])
@@ -2,6 +2,7 @@ import contextlib
2
2
  import os
3
3
  from typing import Any, Dict, Iterator, Optional, Union
4
4
 
5
+ from haystack.components.generators.openai_utils import _convert_message_to_openai_format
5
6
  from haystack.dataclasses import ChatMessage
6
7
  from haystack.tracing import Span, Tracer, tracer
7
8
  from haystack.tracing import utils as tracing_utils
@@ -9,8 +10,22 @@ from haystack.tracing import utils as tracing_utils
9
10
  import langfuse
10
11
 
11
12
  HAYSTACK_LANGFUSE_ENFORCE_FLUSH_ENV_VAR = "HAYSTACK_LANGFUSE_ENFORCE_FLUSH"
12
- _SUPPORTED_GENERATORS = ["AzureOpenAIGenerator", "OpenAIGenerator"]
13
- _SUPPORTED_CHAT_GENERATORS = ["AzureOpenAIChatGenerator", "OpenAIChatGenerator"]
13
+ _SUPPORTED_GENERATORS = [
14
+ "AzureOpenAIGenerator",
15
+ "OpenAIGenerator",
16
+ "AnthropicGenerator",
17
+ "HuggingFaceAPIGenerator",
18
+ "HuggingFaceLocalGenerator",
19
+ "CohereGenerator",
20
+ ]
21
+ _SUPPORTED_CHAT_GENERATORS = [
22
+ "AzureOpenAIChatGenerator",
23
+ "OpenAIChatGenerator",
24
+ "AnthropicChatGenerator",
25
+ "HuggingFaceAPIChatGenerator",
26
+ "HuggingFaceLocalChatGenerator",
27
+ "CohereChatGenerator",
28
+ ]
14
29
  _ALL_SUPPORTED_GENERATORS = _SUPPORTED_GENERATORS + _SUPPORTED_CHAT_GENERATORS
15
30
 
16
31
 
@@ -51,14 +66,14 @@ class LangfuseSpan(Span):
51
66
  return
52
67
  if key.endswith(".input"):
53
68
  if "messages" in value:
54
- messages = [m.to_openai_format() for m in value["messages"]]
69
+ messages = [_convert_message_to_openai_format(m) for m in value["messages"]]
55
70
  self._span.update(input=messages)
56
71
  else:
57
72
  self._span.update(input=value)
58
73
  elif key.endswith(".output"):
59
74
  if "replies" in value:
60
75
  if all(isinstance(r, ChatMessage) for r in value["replies"]):
61
- replies = [m.to_openai_format() for m in value["replies"]]
76
+ replies = [_convert_message_to_openai_format(m) for m in value["replies"]]
62
77
  else:
63
78
  replies = value["replies"]
64
79
  self._span.update(output=replies)
@@ -0,0 +1,62 @@
1
+ import os
2
+ import pytest
3
+ from urllib.parse import urlparse
4
+ import requests
5
+ from requests.auth import HTTPBasicAuth
6
+ from haystack import Pipeline
7
+ from haystack.components.builders import ChatPromptBuilder
8
+ from haystack.dataclasses import ChatMessage
9
+ from haystack_integrations.components.connectors.langfuse import LangfuseConnector
10
+ from haystack.components.generators.chat import OpenAIChatGenerator
11
+
12
+ from haystack_integrations.components.generators.anthropic import AnthropicChatGenerator
13
+ from haystack_integrations.components.generators.cohere import CohereChatGenerator
14
+
15
+ # don't remove (or move) this env var setting from here, it's needed to turn tracing on
16
+ os.environ["HAYSTACK_CONTENT_TRACING_ENABLED"] = "true"
17
+
18
+
19
+ @pytest.mark.integration
20
+ @pytest.mark.parametrize(
21
+ "llm_class, env_var, expected_trace",
22
+ [
23
+ (OpenAIChatGenerator, "OPENAI_API_KEY", "OpenAI"),
24
+ (AnthropicChatGenerator, "ANTHROPIC_API_KEY", "Anthropic"),
25
+ (CohereChatGenerator, "COHERE_API_KEY", "Cohere"),
26
+ ],
27
+ )
28
+ def test_tracing_integration(llm_class, env_var, expected_trace):
29
+ if not all([os.environ.get("LANGFUSE_SECRET_KEY"), os.environ.get("LANGFUSE_PUBLIC_KEY"), os.environ.get(env_var)]):
30
+ pytest.skip(f"Missing required environment variables: LANGFUSE_SECRET_KEY, LANGFUSE_PUBLIC_KEY, or {env_var}")
31
+
32
+ pipe = Pipeline()
33
+ pipe.add_component("tracer", LangfuseConnector(name=f"Chat example - {expected_trace}", public=True))
34
+ pipe.add_component("prompt_builder", ChatPromptBuilder())
35
+ pipe.add_component("llm", llm_class())
36
+ pipe.connect("prompt_builder.prompt", "llm.messages")
37
+
38
+ messages = [
39
+ ChatMessage.from_system("Always respond in German even if some input data is in other languages."),
40
+ ChatMessage.from_user("Tell me about {{location}}"),
41
+ ]
42
+
43
+ response = pipe.run(data={"prompt_builder": {"template_variables": {"location": "Berlin"}, "template": messages}})
44
+ assert "Berlin" in response["llm"]["replies"][0].content
45
+ assert response["tracer"]["trace_url"]
46
+
47
+ url = "https://cloud.langfuse.com/api/public/traces/"
48
+ trace_url = response["tracer"]["trace_url"]
49
+ uuid = os.path.basename(urlparse(trace_url).path)
50
+
51
+ try:
52
+ response = requests.get(
53
+ url + uuid, auth=HTTPBasicAuth(os.environ["LANGFUSE_PUBLIC_KEY"], os.environ["LANGFUSE_SECRET_KEY"])
54
+ )
55
+ assert response.status_code == 200, f"Failed to retrieve data from Langfuse API: {response.status_code}"
56
+
57
+ # check if the trace contains the expected LLM name
58
+ assert expected_trace in str(response.content)
59
+ # check if the trace contains the expected generation span
60
+ assert "GENERATION" in str(response.content)
61
+ except requests.exceptions.RequestException as e:
62
+ pytest.fail(f"Failed to retrieve data from Langfuse API: {e}")
@@ -1,17 +0,0 @@
1
- # Changelog
2
-
3
- ## [integrations/langfuse-v0.1.0] - 2024-06-13
4
-
5
- ### 🚀 Features
6
-
7
- - Langfuse integration (#686)
8
-
9
- ### 🐛 Bug Fixes
10
-
11
- - Performance optimizations and value error when streaming in langfuse (#798)
12
-
13
- ### ⚙️ Miscellaneous Tasks
14
-
15
- - Use ChatMessage to_openai_format, update unit tests, pydocs (#725)
16
-
17
- <!-- generated by git-cliff -->
@@ -1,29 +0,0 @@
1
- import os
2
-
3
- os.environ["HAYSTACK_CONTENT_TRACING_ENABLED"] = "true"
4
-
5
- from haystack import Pipeline
6
- from haystack.components.builders import DynamicChatPromptBuilder
7
- from haystack.components.generators.chat import OpenAIChatGenerator
8
- from haystack.dataclasses import ChatMessage
9
- from haystack_integrations.components.connectors.langfuse import LangfuseConnector
10
-
11
- if __name__ == "__main__":
12
-
13
- pipe = Pipeline()
14
- pipe.add_component("tracer", LangfuseConnector("Chat example"))
15
- pipe.add_component("prompt_builder", DynamicChatPromptBuilder())
16
- pipe.add_component("llm", OpenAIChatGenerator(model="gpt-3.5-turbo"))
17
-
18
- pipe.connect("prompt_builder.prompt", "llm.messages")
19
-
20
- messages = [
21
- ChatMessage.from_system("Always respond in German even if some input data is in other languages."),
22
- ChatMessage.from_user("Tell me about {{location}}"),
23
- ]
24
-
25
- response = pipe.run(
26
- data={"prompt_builder": {"template_variables": {"location": "Berlin"}, "prompt_source": messages}}
27
- )
28
- print(response["llm"]["replies"][0])
29
- print(response["tracer"]["trace_url"])
@@ -1,57 +0,0 @@
1
- import os
2
-
3
- # don't remove (or move) this env var setting from here, it's needed to turn tracing on
4
- os.environ["HAYSTACK_CONTENT_TRACING_ENABLED"] = "true"
5
-
6
- from urllib.parse import urlparse
7
-
8
- import pytest
9
- import requests
10
-
11
- from haystack import Pipeline
12
- from haystack.components.builders import DynamicChatPromptBuilder
13
- from haystack.components.generators.chat import OpenAIChatGenerator
14
- from haystack.dataclasses import ChatMessage
15
- from requests.auth import HTTPBasicAuth
16
-
17
- from haystack_integrations.components.connectors.langfuse import LangfuseConnector
18
-
19
-
20
- @pytest.mark.integration
21
- @pytest.mark.skipif(
22
- not os.environ.get("LANGFUSE_SECRET_KEY", None) and not os.environ.get("LANGFUSE_PUBLIC_KEY", None),
23
- reason="Export an env var called LANGFUSE_SECRET_KEY and LANGFUSE_PUBLIC_KEY containing Langfuse credentials.",
24
- )
25
- def test_tracing_integration():
26
-
27
- pipe = Pipeline()
28
- pipe.add_component("tracer", LangfuseConnector(name="Chat example", public=True)) # public so anyone can verify run
29
- pipe.add_component("prompt_builder", DynamicChatPromptBuilder())
30
- pipe.add_component("llm", OpenAIChatGenerator(model="gpt-3.5-turbo"))
31
-
32
- pipe.connect("prompt_builder.prompt", "llm.messages")
33
-
34
- messages = [
35
- ChatMessage.from_system("Always respond in German even if some input data is in other languages."),
36
- ChatMessage.from_user("Tell me about {{location}}"),
37
- ]
38
-
39
- response = pipe.run(
40
- data={"prompt_builder": {"template_variables": {"location": "Berlin"}, "prompt_source": messages}}
41
- )
42
- assert "Berlin" in response["llm"]["replies"][0].content
43
- assert response["tracer"]["trace_url"]
44
- url = "https://cloud.langfuse.com/api/public/traces/"
45
- trace_url = response["tracer"]["trace_url"]
46
- parsed_url = urlparse(trace_url)
47
- # trace id is the last part of the path (after the last '/')
48
- uuid = os.path.basename(parsed_url.path)
49
- try:
50
- # GET request with Basic Authentication on the Langfuse API
51
- response = requests.get(
52
- url + uuid, auth=HTTPBasicAuth(os.environ.get("LANGFUSE_PUBLIC_KEY"), os.environ.get("LANGFUSE_SECRET_KEY"))
53
- )
54
-
55
- assert response.status_code == 200, f"Failed to retrieve data from Langfuse API: {response.status_code}"
56
- except requests.exceptions.RequestException as e:
57
- assert False, f"Failed to retrieve data from Langfuse API: {e}"