langfuse-haystack 0.3.0__tar.gz → 0.5.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.5.0/CHANGELOG.md +43 -0
  2. {langfuse_haystack-0.3.0 → langfuse_haystack-0.5.0}/PKG-INFO +1 -1
  3. {langfuse_haystack-0.3.0 → langfuse_haystack-0.5.0}/example/basic_rag.py +1 -0
  4. langfuse_haystack-0.5.0/example/chat.py +64 -0
  5. {langfuse_haystack-0.3.0 → langfuse_haystack-0.5.0}/pyproject.toml +11 -8
  6. {langfuse_haystack-0.3.0 → langfuse_haystack-0.5.0}/src/haystack_integrations/components/connectors/langfuse/langfuse_connector.py +14 -2
  7. {langfuse_haystack-0.3.0 → langfuse_haystack-0.5.0}/src/haystack_integrations/tracing/langfuse/tracer.py +16 -2
  8. {langfuse_haystack-0.3.0 → langfuse_haystack-0.5.0}/tests/test_langfuse_span.py +2 -0
  9. {langfuse_haystack-0.3.0 → langfuse_haystack-0.5.0}/tests/test_tracer.py +1 -1
  10. langfuse_haystack-0.5.0/tests/test_tracing.py +76 -0
  11. langfuse_haystack-0.3.0/CHANGELOG.md +0 -19
  12. langfuse_haystack-0.3.0/example/chat.py +0 -27
  13. langfuse_haystack-0.3.0/tests/test_tracing.py +0 -55
  14. {langfuse_haystack-0.3.0 → langfuse_haystack-0.5.0}/.gitignore +0 -0
  15. {langfuse_haystack-0.3.0 → langfuse_haystack-0.5.0}/LICENSE.txt +0 -0
  16. {langfuse_haystack-0.3.0 → langfuse_haystack-0.5.0}/README.md +0 -0
  17. {langfuse_haystack-0.3.0 → langfuse_haystack-0.5.0}/example/requirements.txt +0 -0
  18. {langfuse_haystack-0.3.0 → langfuse_haystack-0.5.0}/pydoc/config.yml +0 -0
  19. {langfuse_haystack-0.3.0 → langfuse_haystack-0.5.0}/src/haystack_integrations/components/connectors/langfuse/__init__.py +0 -0
  20. {langfuse_haystack-0.3.0 → langfuse_haystack-0.5.0}/src/haystack_integrations/tracing/langfuse/__init__.py +0 -0
  21. {langfuse_haystack-0.3.0 → langfuse_haystack-0.5.0}/tests/__init__.py +0 -0
@@ -0,0 +1,43 @@
1
+ # Changelog
2
+
3
+ ## [integrations/langfuse-v0.4.0] - 2024-09-17
4
+
5
+ ### 🚀 Features
6
+
7
+ - Langfuse - support generation span for more LLMs (#1087)
8
+
9
+ ### 🚜 Refactor
10
+
11
+ - Remove usage of deprecated `ChatMessage.to_openai_format` (#1001)
12
+
13
+ ### 📚 Documentation
14
+
15
+ - Add link to langfuse in LangfuseConnector (#981)
16
+
17
+ ### 🧪 Testing
18
+
19
+ - Do not retry tests in `hatch run test` command (#954)
20
+
21
+ ### ⚙️ Miscellaneous Tasks
22
+
23
+ - Retry tests to reduce flakyness (#836)
24
+ - `Langfuse` - replace DynamicChatPromptBuilder with ChatPromptBuilder (#925)
25
+ - Remove all `DynamicChatPromptBuilder` references in Langfuse integration (#931)
26
+
27
+ ## [integrations/langfuse-v0.2.0] - 2024-06-18
28
+
29
+ ## [integrations/langfuse-v0.1.0] - 2024-06-13
30
+
31
+ ### 🚀 Features
32
+
33
+ - Langfuse integration (#686)
34
+
35
+ ### 🐛 Bug Fixes
36
+
37
+ - Performance optimizations and value error when streaming in langfuse (#798)
38
+
39
+ ### ⚙️ Miscellaneous Tasks
40
+
41
+ - Use ChatMessage to_openai_format, update unit tests, pydocs (#725)
42
+
43
+ <!-- generated by git-cliff -->
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: langfuse-haystack
3
- Version: 0.3.0
3
+ Version: 0.5.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
@@ -10,6 +10,7 @@ from haystack.components.embedders import SentenceTransformersDocumentEmbedder,
10
10
  from haystack.components.generators import OpenAIGenerator
11
11
  from haystack.components.retrievers import InMemoryEmbeddingRetriever
12
12
  from haystack.document_stores.in_memory import InMemoryDocumentStore
13
+
13
14
  from haystack_integrations.components.connectors.langfuse import LangfuseConnector
14
15
 
15
16
 
@@ -0,0 +1,64 @@
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(
53
+ data={
54
+ "prompt_builder": {
55
+ "template_variables": {"location": "Berlin"},
56
+ "template": messages,
57
+ },
58
+ "tracer": {
59
+ "invocation_context": {"some_key": "some_value"},
60
+ },
61
+ }
62
+ )
63
+ print(response["llm"]["replies"][0])
64
+ print(response["tracer"]["trace_url"])
@@ -47,6 +47,8 @@ dependencies = [
47
47
  "pytest",
48
48
  "pytest-rerunfailures",
49
49
  "haystack-pydoc-tools",
50
+ "anthropic-haystack",
51
+ "cohere-haystack"
50
52
  ]
51
53
  [tool.hatch.envs.default.scripts]
52
54
  test = "pytest {args:tests}"
@@ -67,8 +69,8 @@ dependencies = ["black>=23.1.0", "mypy>=1.0.0", "ruff>=0.0.243"]
67
69
 
68
70
  [tool.hatch.envs.lint.scripts]
69
71
  typing = "mypy --install-types --non-interactive --explicit-package-bases {args:src/ tests}"
70
- style = ["ruff check {args:. --exclude tests/}", "black --check --diff {args:.}"]
71
- fmt = ["black {args:.}", "ruff --fix {args:. --exclude tests/}", "style"]
72
+ style = ["ruff check {args:}", "black --check --diff {args:.}"]
73
+ fmt = ["black {args:.}", "ruff check --fix {args:}", "style"]
72
74
  all = ["style", "typing"]
73
75
 
74
76
  [tool.hatch.metadata]
@@ -82,7 +84,10 @@ skip-string-normalization = true
82
84
  [tool.ruff]
83
85
  target-version = "py38"
84
86
  line-length = 120
85
- lint.select = [
87
+ exclude = ["example", "tests"]
88
+
89
+ [tool.ruff.lint]
90
+ select = [
86
91
  "A",
87
92
  "ARG",
88
93
  "B",
@@ -108,8 +113,7 @@ lint.select = [
108
113
  "W",
109
114
  "YTT",
110
115
  ]
111
-
112
- lint.ignore = [
116
+ ignore = [
113
117
  # Allow non-abstract empty methods in abstract base classes
114
118
  "B027",
115
119
  # Ignore checks for possible passwords
@@ -125,14 +129,13 @@ lint.ignore = [
125
129
  # Asserts
126
130
  "S101",
127
131
  ]
128
- lint.unfixable = [
132
+ unfixable = [
129
133
  # Don't touch unused imports
130
134
  "F401",
131
135
  ]
132
- extend-exclude = ["tests", "example"]
133
136
 
134
137
  [tool.ruff.lint.isort]
135
- known-first-party = ["src"]
138
+ known-first-party = ["haystack_integrations"]
136
139
 
137
140
  [tool.ruff.lint.flake8-tidy-imports]
138
141
  ban-relative-imports = "parents"
@@ -1,8 +1,12 @@
1
- from haystack import component, tracing
1
+ from typing import Any, Dict, Optional
2
+
3
+ from haystack import component, logging, tracing
2
4
 
3
5
  from haystack_integrations.tracing.langfuse import LangfuseTracer
4
6
  from langfuse import Langfuse
5
7
 
8
+ logger = logging.getLogger(__name__)
9
+
6
10
 
7
11
  @component
8
12
  class LangfuseConnector:
@@ -105,12 +109,20 @@ class LangfuseConnector:
105
109
  tracing.enable_tracing(self.tracer)
106
110
 
107
111
  @component.output_types(name=str, trace_url=str)
108
- def run(self):
112
+ def run(self, invocation_context: Optional[Dict[str, Any]] = None):
109
113
  """
110
114
  Runs the LangfuseConnector component.
111
115
 
116
+ :param invocation_context: A dictionary with additional context for the invocation. This parameter
117
+ is useful when users want to mark this particular invocation with additional information, e.g.
118
+ a run id from their own execution framework, user id, etc. These key-value pairs are then visible
119
+ in the Langfuse traces.
112
120
  :returns: A dictionary with the following keys:
113
121
  - `name`: The name of the tracing component.
114
122
  - `trace_url`: The URL to the tracing data.
115
123
  """
124
+ logger.debug(
125
+ "Langfuse tracer invoked with the following context: '{invocation_context}'",
126
+ invocation_context=invocation_context,
127
+ )
116
128
  return {"name": self.name, "trace_url": self.tracer.get_trace_url()}
@@ -10,8 +10,22 @@ from haystack.tracing import utils as tracing_utils
10
10
  import langfuse
11
11
 
12
12
  HAYSTACK_LANGFUSE_ENFORCE_FLUSH_ENV_VAR = "HAYSTACK_LANGFUSE_ENFORCE_FLUSH"
13
- _SUPPORTED_GENERATORS = ["AzureOpenAIGenerator", "OpenAIGenerator"]
14
- _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
+ ]
15
29
  _ALL_SUPPORTED_GENERATORS = _SUPPORTED_GENERATORS + _SUPPORTED_CHAT_GENERATORS
16
30
 
17
31
 
@@ -3,7 +3,9 @@ import os
3
3
  os.environ["HAYSTACK_CONTENT_TRACING_ENABLED"] = "true"
4
4
 
5
5
  from unittest.mock import Mock
6
+
6
7
  from haystack.dataclasses import ChatMessage
8
+
7
9
  from haystack_integrations.tracing.langfuse.tracer import LangfuseSpan
8
10
 
9
11
 
@@ -1,5 +1,5 @@
1
1
  import os
2
- from unittest.mock import Mock, MagicMock, patch
2
+ from unittest.mock import MagicMock, Mock, patch
3
3
 
4
4
  from haystack_integrations.tracing.langfuse.tracer import LangfuseTracer
5
5
 
@@ -0,0 +1,76 @@
1
+ import os
2
+ import random
3
+ import time
4
+ from urllib.parse import urlparse
5
+
6
+ import pytest
7
+ import requests
8
+ from haystack import Pipeline
9
+ from haystack.components.builders import ChatPromptBuilder
10
+ from haystack.components.generators.chat import OpenAIChatGenerator
11
+ from haystack.dataclasses import ChatMessage
12
+ from requests.auth import HTTPBasicAuth
13
+
14
+ from haystack_integrations.components.connectors.langfuse import LangfuseConnector
15
+ from haystack_integrations.components.generators.anthropic import AnthropicChatGenerator
16
+ from haystack_integrations.components.generators.cohere import CohereChatGenerator
17
+
18
+ # don't remove (or move) this env var setting from here, it's needed to turn tracing on
19
+ os.environ["HAYSTACK_CONTENT_TRACING_ENABLED"] = "true"
20
+
21
+
22
+ @pytest.mark.integration
23
+ @pytest.mark.parametrize(
24
+ "llm_class, env_var, expected_trace",
25
+ [
26
+ (OpenAIChatGenerator, "OPENAI_API_KEY", "OpenAI"),
27
+ (AnthropicChatGenerator, "ANTHROPIC_API_KEY", "Anthropic"),
28
+ (CohereChatGenerator, "COHERE_API_KEY", "Cohere"),
29
+ ],
30
+ )
31
+ def test_tracing_integration(llm_class, env_var, expected_trace):
32
+ if not all([os.environ.get("LANGFUSE_SECRET_KEY"), os.environ.get("LANGFUSE_PUBLIC_KEY"), os.environ.get(env_var)]):
33
+ pytest.skip(f"Missing required environment variables: LANGFUSE_SECRET_KEY, LANGFUSE_PUBLIC_KEY, or {env_var}")
34
+
35
+ pipe = Pipeline()
36
+ pipe.add_component("tracer", LangfuseConnector(name=f"Chat example - {expected_trace}", public=True))
37
+ pipe.add_component("prompt_builder", ChatPromptBuilder())
38
+ pipe.add_component("llm", llm_class())
39
+ pipe.connect("prompt_builder.prompt", "llm.messages")
40
+
41
+ messages = [
42
+ ChatMessage.from_system("Always respond in German even if some input data is in other languages."),
43
+ ChatMessage.from_user("Tell me about {{location}}"),
44
+ ]
45
+
46
+ response = pipe.run(
47
+ data={
48
+ "prompt_builder": {"template_variables": {"location": "Berlin"}, "template": messages},
49
+ "tracer": {"invocation_context": {"user_id": "user_42"}},
50
+ }
51
+ )
52
+ assert "Berlin" in response["llm"]["replies"][0].content
53
+ assert response["tracer"]["trace_url"]
54
+
55
+ # add a random delay between 1 and 3 seconds to make sure the trace is flushed
56
+ # and that the trace is available in Langfuse when we fetch it below
57
+ time.sleep(random.uniform(1, 3))
58
+
59
+ url = "https://cloud.langfuse.com/api/public/traces/"
60
+ trace_url = response["tracer"]["trace_url"]
61
+ uuid = os.path.basename(urlparse(trace_url).path)
62
+
63
+ try:
64
+ response = requests.get(
65
+ url + uuid, auth=HTTPBasicAuth(os.environ["LANGFUSE_PUBLIC_KEY"], os.environ["LANGFUSE_SECRET_KEY"])
66
+ )
67
+ assert response.status_code == 200, f"Failed to retrieve data from Langfuse API: {response.status_code}"
68
+
69
+ # check if the trace contains the expected LLM name
70
+ assert expected_trace in str(response.content)
71
+ # check if the trace contains the expected generation span
72
+ assert "GENERATION" in str(response.content)
73
+ # check if the trace contains the expected user_id
74
+ assert "user_42" in str(response.content)
75
+ except requests.exceptions.RequestException as e:
76
+ pytest.fail(f"Failed to retrieve data from Langfuse API: {e}")
@@ -1,19 +0,0 @@
1
- # Changelog
2
-
3
- ## [integrations/langfuse-v0.2.0] - 2024-06-18
4
-
5
- ## [integrations/langfuse-v0.1.0] - 2024-06-13
6
-
7
- ### 🚀 Features
8
-
9
- - Langfuse integration (#686)
10
-
11
- ### 🐛 Bug Fixes
12
-
13
- - Performance optimizations and value error when streaming in langfuse (#798)
14
-
15
- ### ⚙️ Miscellaneous Tasks
16
-
17
- - Use ChatMessage to_openai_format, update unit tests, pydocs (#725)
18
-
19
- <!-- generated by git-cliff -->
@@ -1,27 +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 ChatPromptBuilder
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", ChatPromptBuilder())
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(data={"prompt_builder": {"template_variables": {"location": "Berlin"}, "template": messages}})
26
- print(response["llm"]["replies"][0])
27
- print(response["tracer"]["trace_url"])
@@ -1,55 +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 ChatPromptBuilder
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", ChatPromptBuilder())
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(data={"prompt_builder": {"template_variables": {"location": "Berlin"}, "template": messages}})
40
- assert "Berlin" in response["llm"]["replies"][0].content
41
- assert response["tracer"]["trace_url"]
42
- url = "https://cloud.langfuse.com/api/public/traces/"
43
- trace_url = response["tracer"]["trace_url"]
44
- parsed_url = urlparse(trace_url)
45
- # trace id is the last part of the path (after the last '/')
46
- uuid = os.path.basename(parsed_url.path)
47
- try:
48
- # GET request with Basic Authentication on the Langfuse API
49
- response = requests.get(
50
- url + uuid, auth=HTTPBasicAuth(os.environ.get("LANGFUSE_PUBLIC_KEY"), os.environ.get("LANGFUSE_SECRET_KEY"))
51
- )
52
-
53
- assert response.status_code == 200, f"Failed to retrieve data from Langfuse API: {response.status_code}"
54
- except requests.exceptions.RequestException as e:
55
- assert False, f"Failed to retrieve data from Langfuse API: {e}"