repo_name stringlengths 1 62 | dataset stringclasses 1 value | lang stringclasses 11 values | pr_id int64 1 20.1k | owner stringlengths 2 34 | reviewer stringlengths 2 39 | diff_hunk stringlengths 15 262k | code_review_comment stringlengths 1 99.6k |
|---|---|---|---|---|---|---|---|
langfuse-python | github_2023 | python | 384 | langfuse | maxdeichmann | @@ -0,0 +1,366 @@
+from collections import defaultdict
+from typing import Any, Dict, List, Optional, Union, Tuple, Callable
+from uuid import uuid4
+import logging
+
+from langfuse.client import (
+ StatefulSpanClient,
+ StatefulTraceClient,
+ StatefulGenerationClient,
+)
+from langfuse.decorators.error_logging import (
+ auto_decorate_methods_with,
+ catch_and_log_errors,
+)
+from langfuse.callback.base import BaseCallbackHandler as LangfuseBaseCallbackHandler
+from langfuse.callback.utils import CallbackEvent
+
+try:
+ from llama_index.core.callbacks.base_handler import (
+ BaseCallbackHandler as LLamaIndexBaseCallbackHandler,
+ )
+ from llama_index.core.callbacks.schema import (
+ CBEventType,
+ BASE_TRACE_EVENT,
+ EventPayload,
+ )
+ from llama_index.core.utilities.token_counting import TokenCounter
+except ImportError:
+ raise ModuleNotFoundError(
+ "Please install llama-index to use the Langfuse llama-index integration: 'pip install llama-index'"
+ )
+
+
+@auto_decorate_methods_with(catch_and_log_errors)
+class LLamaIndexCallbackHandler(
+ LLamaIndexBaseCallbackHandler, LangfuseBaseCallbackHandler
+):
+ log = logging.getLogger("langfuse")
+
+ def __init__(
+ self,
+ *,
+ public_key: Optional[str] = None,
+ secret_key: Optional[str] = None,
+ host: Optional[str] = None,
+ debug: bool = False,
+ stateful_client: Optional[
+ Union[StatefulTraceClient, StatefulSpanClient]
+ ] = None,
+ session_id: Optional[str] = None,
+ user_id: Optional[str] = None,
+ trace_name: Optional[str] = None,
+ release: Optional[str] = None,
+ version: Optional[str] = None,
+ threads: Optional[int] = None,
+ flush_at: Optional[int] = None,
+ flush_interval: Optional[int] = None,
+ max_retries: Optional[int] = None,
+ timeout: Optional[int] = None,
+ event_starts_to_ignore: Optional[List[CBEventType]] = None,
+ event_ends_to_ignore: Optional[List[CBEventType]] = None,
+ tokenizer: Optional[Callable[[str], list]] = None,
+ ) -> None:
+ LLamaIndexBaseCallbackHandler.__init__(
+ self,
+ event_starts_to_ignore=event_starts_to_ignore or [],
+ event_ends_to_ignore=event_ends_to_ignore or [],
+ )
+ LangfuseBaseCallbackHandler.__init__(
+ self,
+ public_key=public_key,
+ secret_key=secret_key,
+ host=host,
+ debug=debug,
+ stateful_client=stateful_client,
+ session_id=session_id,
+ user_id=user_id,
+ trace_name=trace_name,
+ release=release,
+ version=version,
+ threads=threads,
+ flush_at=flush_at,
+ flush_interval=flush_interval,
+ max_retries=max_retries,
+ timeout=timeout,
+ sdk_integration="llama-index",
+ )
+
+ self.root = stateful_client
+ self.event_map: Dict[str, List[CallbackEvent]] = defaultdict(list)
+ self._cur_trace_id: Optional[str] = None
+ self._token_counter = TokenCounter(tokenizer)
+
+ def start_trace(self, trace_id: Optional[str] = None) -> None:
+ """Run when an overall trace is launched."""
+ self._cur_trace_id = trace_id
+
+ def end_trace(
+ self,
+ trace_id: Optional[str] = None,
+ trace_map: Optional[Dict[str, List[str]]] = None,
+ ) -> None:
+ """Run when an overall trace is exited."""
+ if not trace_map:
+ self.log.debug("No events in trace map to create the observation tree.")
+ return
+
+ self._create_observations_from_trace_map(
+ event_id=BASE_TRACE_EVENT, trace_map=trace_map
+ )
+ self.flush()
+
+ def on_event_start(
+ self,
+ event_type: CBEventType,
+ payload: Optional[Dict[str, Any]] = None,
+ event_id: str = "",
+ parent_id: str = "",
+ **kwargs: Any,
+ ) -> str:
+ """Run when an event starts and return id of event."""
+ start_event = CallbackEvent(
+ event_id=event_id, event_type=event_type, payload=payload
+ )
+ self.event_map[event_id].append(start_event)
+
+ return event_id
+
+ def on_event_end(
+ self,
+ event_type: CBEventType,
+ payload: Optional[Dict[str, Any]] = None,
+ event_id: str = "",
+ **kwargs: Any,
+ ) -> None:
+ """Run when an event ends."""
+ end_event = CallbackEvent(
+ event_id=event_id, event_type=event_type, payload=payload
+ )
+ self.event_map[event_id].append(end_event)
+
+ def _create_observations_from_trace_map(
+ self,
+ event_id: str,
+ trace_map: Dict[str, List[str]],
+ parent: Optional[
+ Union[StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient]
+ ] = None,
+ ) -> None:
+ """Recursively create langfuse observations based on the trace_map."""
+ if event_id != BASE_TRACE_EVENT and not self.event_map.get(event_id):
+ return
+
+ if event_id == BASE_TRACE_EVENT:
+ observation = self._get_root_observation()
+ else:
+ observation = self._create_observation(
+ event_id=event_id, parent=parent, trace_id=self.trace.id
+ )
+
+ for child_event_id in trace_map.get(event_id, []):
+ self._create_observations_from_trace_map(
+ event_id=child_event_id, parent=observation, trace_map=trace_map
+ )
+
+ def _get_root_observation(self) -> Union[StatefulTraceClient, StatefulSpanClient]:
+ if self.root is not None:
+ return self.root # return user-provided root trace or span
+
+ else:
+ self.trace = self.langfuse.trace(
+ id=str(uuid4()),
+ name=self.trace_name or f"LlamaIndex_{self._cur_trace_id}",
+ version=self.version,
+ session_id=self.session_id,
+ user_id=self.user_id,
+ )
+
+ return self.trace
+
+ def _create_observation(
+ self,
+ event_id: str,
+ parent: Union[
+ StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient
+ ],
+ trace_id: str,
+ ) -> Union[StatefulSpanClient, StatefulGenerationClient]:
+ event_type = self.event_map[event_id][0].event_type
+
+ if event_type == CBEventType.LLM:
+ return self._handle_LLM_events(event_id, parent, trace_id)
+ elif event_type == CBEventType.EMBEDDING:
+ return self._handle_embedding_events(event_id, parent, trace_id)
+ else:
+ return self._handle_span_events(event_id, parent, trace_id)
+
+ def _handle_LLM_events(
+ self,
+ event_id: str,
+ parent: Union[
+ StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient
+ ],
+ trace_id: str,
+ ) -> StatefulGenerationClient:
+ start_event, end_event = self.event_map[event_id]
+
+ if start_event.payload and EventPayload.SERIALIZED in start_event.payload:
+ serialized = start_event.payload.get(EventPayload.SERIALIZED, {})
+ name = serialized.get("class_name", "LLM")
+ temperature = serialized.get("temperature", None)
+ max_tokens = serialized.get("max_tokens", None)
+ timeout = serialized.get("timeout", None)
+
+ if end_event.payload:
+ if EventPayload.PROMPT in end_event.payload:
+ input = end_event.payload.get(EventPayload.PROMPT)
+ output = end_event.payload.get(EventPayload.COMPLETION)
+
+ elif EventPayload.MESSAGES in end_event.payload:
+ input = end_event.payload.get(EventPayload.MESSAGES)
+ response = end_event.payload.get(EventPayload.RESPONSE, {})
+ output = response.message
+ model = response.raw.get("model", None)
+ token_usage = dict(response.raw.get("usage", {}))
+ usage = None
+ if token_usage:
+ usage = {
+ "prompt_tokens": token_usage.get("prompt_tokens"),
+ "completion_tokens": token_usage.get("completion_tokens"),
+ "total_tokens": token_usage.get("total_tokens"),
+ }
+
+ generation = parent.generation(
+ id=event_id,
+ trace_id=trace_id,
+ version=self.version,
+ name=name,
+ start_time=start_event.time,
+ end_time=end_event.time,
+ usage=usage or None,
+ model=model,
+ input=input,
+ output=output,
+ metadata=end_event.payload,
+ model_parameters={
+ "temperature": temperature,
+ "max_tokens": max_tokens,
+ "request_timeout": timeout,
+ },
+ )
+
+ return generation
+
+ def _handle_embedding_events(
+ self,
+ event_id: str,
+ parent: Union[
+ StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient
+ ],
+ trace_id: str,
+ ) -> StatefulGenerationClient:
+ start_event, end_event = self.event_map[event_id]
+
+ if start_event.payload and EventPayload.SERIALIZED in start_event.payload:
+ serialized = start_event.payload.get(EventPayload.SERIALIZED, {})
+ name = serialized.get("class_name", "Embedding")
+ model = serialized.get("model_name", None)
+ timeout = serialized.get("timeout", None)
+
+ if end_event.payload:
+ chunks = end_event.payload.get(EventPayload.CHUNKS, [])
+ embeddings = end_event.payload.get(EventPayload.EMBEDDINGS, [])
+ metadata = {"num_embeddings": len(embeddings)}
+
+ usage = None
+ token_count = 0
+ for chunk in chunks:
+ token_count += self._token_counter.get_string_tokens(chunk)
+
+ usage = {
+ "prompt_tokens": token_count or None, | switch to `total` |
langfuse-python | github_2023 | python | 384 | langfuse | maxdeichmann | @@ -0,0 +1,366 @@
+from collections import defaultdict
+from typing import Any, Dict, List, Optional, Union, Tuple, Callable
+from uuid import uuid4
+import logging
+
+from langfuse.client import (
+ StatefulSpanClient,
+ StatefulTraceClient,
+ StatefulGenerationClient,
+)
+from langfuse.decorators.error_logging import (
+ auto_decorate_methods_with,
+ catch_and_log_errors,
+)
+from langfuse.callback.base import BaseCallbackHandler as LangfuseBaseCallbackHandler
+from langfuse.callback.utils import CallbackEvent
+
+try:
+ from llama_index.core.callbacks.base_handler import (
+ BaseCallbackHandler as LLamaIndexBaseCallbackHandler,
+ )
+ from llama_index.core.callbacks.schema import (
+ CBEventType,
+ BASE_TRACE_EVENT,
+ EventPayload,
+ )
+ from llama_index.core.utilities.token_counting import TokenCounter
+except ImportError:
+ raise ModuleNotFoundError(
+ "Please install llama-index to use the Langfuse llama-index integration: 'pip install llama-index'"
+ )
+
+
+@auto_decorate_methods_with(catch_and_log_errors)
+class LLamaIndexCallbackHandler(
+ LLamaIndexBaseCallbackHandler, LangfuseBaseCallbackHandler
+):
+ log = logging.getLogger("langfuse")
+
+ def __init__(
+ self,
+ *,
+ public_key: Optional[str] = None,
+ secret_key: Optional[str] = None,
+ host: Optional[str] = None,
+ debug: bool = False,
+ stateful_client: Optional[
+ Union[StatefulTraceClient, StatefulSpanClient]
+ ] = None,
+ session_id: Optional[str] = None,
+ user_id: Optional[str] = None,
+ trace_name: Optional[str] = None,
+ release: Optional[str] = None,
+ version: Optional[str] = None,
+ threads: Optional[int] = None,
+ flush_at: Optional[int] = None,
+ flush_interval: Optional[int] = None,
+ max_retries: Optional[int] = None,
+ timeout: Optional[int] = None,
+ event_starts_to_ignore: Optional[List[CBEventType]] = None,
+ event_ends_to_ignore: Optional[List[CBEventType]] = None,
+ tokenizer: Optional[Callable[[str], list]] = None,
+ ) -> None:
+ LLamaIndexBaseCallbackHandler.__init__(
+ self,
+ event_starts_to_ignore=event_starts_to_ignore or [],
+ event_ends_to_ignore=event_ends_to_ignore or [],
+ )
+ LangfuseBaseCallbackHandler.__init__(
+ self,
+ public_key=public_key,
+ secret_key=secret_key,
+ host=host,
+ debug=debug,
+ stateful_client=stateful_client,
+ session_id=session_id,
+ user_id=user_id,
+ trace_name=trace_name,
+ release=release,
+ version=version,
+ threads=threads,
+ flush_at=flush_at,
+ flush_interval=flush_interval,
+ max_retries=max_retries,
+ timeout=timeout,
+ sdk_integration="llama-index",
+ )
+
+ self.root = stateful_client
+ self.event_map: Dict[str, List[CallbackEvent]] = defaultdict(list)
+ self._cur_trace_id: Optional[str] = None
+ self._token_counter = TokenCounter(tokenizer)
+
+ def start_trace(self, trace_id: Optional[str] = None) -> None:
+ """Run when an overall trace is launched."""
+ self._cur_trace_id = trace_id
+
+ def end_trace(
+ self,
+ trace_id: Optional[str] = None,
+ trace_map: Optional[Dict[str, List[str]]] = None,
+ ) -> None:
+ """Run when an overall trace is exited."""
+ if not trace_map:
+ self.log.debug("No events in trace map to create the observation tree.")
+ return
+
+ self._create_observations_from_trace_map(
+ event_id=BASE_TRACE_EVENT, trace_map=trace_map
+ )
+ self.flush()
+
+ def on_event_start(
+ self,
+ event_type: CBEventType,
+ payload: Optional[Dict[str, Any]] = None,
+ event_id: str = "",
+ parent_id: str = "",
+ **kwargs: Any,
+ ) -> str:
+ """Run when an event starts and return id of event."""
+ start_event = CallbackEvent(
+ event_id=event_id, event_type=event_type, payload=payload
+ )
+ self.event_map[event_id].append(start_event)
+
+ return event_id
+
+ def on_event_end(
+ self,
+ event_type: CBEventType,
+ payload: Optional[Dict[str, Any]] = None,
+ event_id: str = "",
+ **kwargs: Any,
+ ) -> None:
+ """Run when an event ends."""
+ end_event = CallbackEvent(
+ event_id=event_id, event_type=event_type, payload=payload
+ )
+ self.event_map[event_id].append(end_event)
+
+ def _create_observations_from_trace_map(
+ self,
+ event_id: str,
+ trace_map: Dict[str, List[str]],
+ parent: Optional[
+ Union[StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient]
+ ] = None,
+ ) -> None:
+ """Recursively create langfuse observations based on the trace_map."""
+ if event_id != BASE_TRACE_EVENT and not self.event_map.get(event_id):
+ return
+
+ if event_id == BASE_TRACE_EVENT:
+ observation = self._get_root_observation()
+ else:
+ observation = self._create_observation(
+ event_id=event_id, parent=parent, trace_id=self.trace.id
+ )
+
+ for child_event_id in trace_map.get(event_id, []):
+ self._create_observations_from_trace_map(
+ event_id=child_event_id, parent=observation, trace_map=trace_map
+ )
+
+ def _get_root_observation(self) -> Union[StatefulTraceClient, StatefulSpanClient]:
+ if self.root is not None:
+ return self.root # return user-provided root trace or span
+
+ else:
+ self.trace = self.langfuse.trace(
+ id=str(uuid4()),
+ name=self.trace_name or f"LlamaIndex_{self._cur_trace_id}",
+ version=self.version,
+ session_id=self.session_id,
+ user_id=self.user_id,
+ )
+
+ return self.trace
+
+ def _create_observation(
+ self,
+ event_id: str,
+ parent: Union[
+ StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient
+ ],
+ trace_id: str,
+ ) -> Union[StatefulSpanClient, StatefulGenerationClient]:
+ event_type = self.event_map[event_id][0].event_type
+
+ if event_type == CBEventType.LLM:
+ return self._handle_LLM_events(event_id, parent, trace_id)
+ elif event_type == CBEventType.EMBEDDING:
+ return self._handle_embedding_events(event_id, parent, trace_id)
+ else:
+ return self._handle_span_events(event_id, parent, trace_id)
+
+ def _handle_LLM_events(
+ self,
+ event_id: str,
+ parent: Union[
+ StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient
+ ],
+ trace_id: str,
+ ) -> StatefulGenerationClient:
+ start_event, end_event = self.event_map[event_id]
+
+ if start_event.payload and EventPayload.SERIALIZED in start_event.payload:
+ serialized = start_event.payload.get(EventPayload.SERIALIZED, {})
+ name = serialized.get("class_name", "LLM")
+ temperature = serialized.get("temperature", None)
+ max_tokens = serialized.get("max_tokens", None)
+ timeout = serialized.get("timeout", None)
+
+ if end_event.payload:
+ if EventPayload.PROMPT in end_event.payload:
+ input = end_event.payload.get(EventPayload.PROMPT)
+ output = end_event.payload.get(EventPayload.COMPLETION)
+
+ elif EventPayload.MESSAGES in end_event.payload:
+ input = end_event.payload.get(EventPayload.MESSAGES)
+ response = end_event.payload.get(EventPayload.RESPONSE, {})
+ output = response.message
+ model = response.raw.get("model", None)
+ token_usage = dict(response.raw.get("usage", {}))
+ usage = None
+ if token_usage:
+ usage = {
+ "prompt_tokens": token_usage.get("prompt_tokens"),
+ "completion_tokens": token_usage.get("completion_tokens"),
+ "total_tokens": token_usage.get("total_tokens"),
+ }
+
+ generation = parent.generation(
+ id=event_id,
+ trace_id=trace_id,
+ version=self.version,
+ name=name,
+ start_time=start_event.time,
+ end_time=end_event.time,
+ usage=usage or None,
+ model=model,
+ input=input,
+ output=output,
+ metadata=end_event.payload,
+ model_parameters={
+ "temperature": temperature,
+ "max_tokens": max_tokens,
+ "request_timeout": timeout,
+ },
+ )
+
+ return generation
+
+ def _handle_embedding_events(
+ self,
+ event_id: str,
+ parent: Union[
+ StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient
+ ],
+ trace_id: str,
+ ) -> StatefulGenerationClient:
+ start_event, end_event = self.event_map[event_id]
+
+ if start_event.payload and EventPayload.SERIALIZED in start_event.payload:
+ serialized = start_event.payload.get(EventPayload.SERIALIZED, {})
+ name = serialized.get("class_name", "Embedding")
+ model = serialized.get("model_name", None)
+ timeout = serialized.get("timeout", None)
+
+ if end_event.payload:
+ chunks = end_event.payload.get(EventPayload.CHUNKS, [])
+ embeddings = end_event.payload.get(EventPayload.EMBEDDINGS, [])
+ metadata = {"num_embeddings": len(embeddings)}
+
+ usage = None
+ token_count = 0
+ for chunk in chunks:
+ token_count += self._token_counter.get_string_tokens(chunk)
+
+ usage = {
+ "prompt_tokens": token_count or None,
+ }
+
+ generation = parent.generation(
+ id=event_id,
+ trace_id=trace_id,
+ name=name,
+ start_time=start_event.time,
+ end_time=end_event.time,
+ version=self.version,
+ model=model,
+ input=chunks, | Remove the input, as this will be too large for our API |
langfuse-python | github_2023 | python | 384 | langfuse | maxdeichmann | @@ -0,0 +1,366 @@
+from collections import defaultdict
+from typing import Any, Dict, List, Optional, Union, Tuple, Callable
+from uuid import uuid4
+import logging
+
+from langfuse.client import (
+ StatefulSpanClient,
+ StatefulTraceClient,
+ StatefulGenerationClient,
+)
+from langfuse.decorators.error_logging import (
+ auto_decorate_methods_with,
+ catch_and_log_errors,
+)
+from langfuse.callback.base import BaseCallbackHandler as LangfuseBaseCallbackHandler
+from langfuse.callback.utils import CallbackEvent
+
+try:
+ from llama_index.core.callbacks.base_handler import (
+ BaseCallbackHandler as LLamaIndexBaseCallbackHandler,
+ )
+ from llama_index.core.callbacks.schema import (
+ CBEventType,
+ BASE_TRACE_EVENT,
+ EventPayload,
+ )
+ from llama_index.core.utilities.token_counting import TokenCounter
+except ImportError:
+ raise ModuleNotFoundError(
+ "Please install llama-index to use the Langfuse llama-index integration: 'pip install llama-index'"
+ )
+
+
+@auto_decorate_methods_with(catch_and_log_errors)
+class LLamaIndexCallbackHandler(
+ LLamaIndexBaseCallbackHandler, LangfuseBaseCallbackHandler
+):
+ log = logging.getLogger("langfuse")
+
+ def __init__(
+ self,
+ *,
+ public_key: Optional[str] = None,
+ secret_key: Optional[str] = None,
+ host: Optional[str] = None,
+ debug: bool = False,
+ stateful_client: Optional[
+ Union[StatefulTraceClient, StatefulSpanClient]
+ ] = None,
+ session_id: Optional[str] = None,
+ user_id: Optional[str] = None,
+ trace_name: Optional[str] = None,
+ release: Optional[str] = None,
+ version: Optional[str] = None,
+ threads: Optional[int] = None,
+ flush_at: Optional[int] = None,
+ flush_interval: Optional[int] = None,
+ max_retries: Optional[int] = None,
+ timeout: Optional[int] = None,
+ event_starts_to_ignore: Optional[List[CBEventType]] = None,
+ event_ends_to_ignore: Optional[List[CBEventType]] = None,
+ tokenizer: Optional[Callable[[str], list]] = None,
+ ) -> None:
+ LLamaIndexBaseCallbackHandler.__init__(
+ self,
+ event_starts_to_ignore=event_starts_to_ignore or [],
+ event_ends_to_ignore=event_ends_to_ignore or [],
+ )
+ LangfuseBaseCallbackHandler.__init__(
+ self,
+ public_key=public_key,
+ secret_key=secret_key,
+ host=host,
+ debug=debug,
+ stateful_client=stateful_client,
+ session_id=session_id,
+ user_id=user_id,
+ trace_name=trace_name,
+ release=release,
+ version=version,
+ threads=threads,
+ flush_at=flush_at,
+ flush_interval=flush_interval,
+ max_retries=max_retries,
+ timeout=timeout,
+ sdk_integration="llama-index",
+ )
+
+ self.root = stateful_client
+ self.event_map: Dict[str, List[CallbackEvent]] = defaultdict(list)
+ self._cur_trace_id: Optional[str] = None
+ self._token_counter = TokenCounter(tokenizer)
+
+ def start_trace(self, trace_id: Optional[str] = None) -> None:
+ """Run when an overall trace is launched."""
+ self._cur_trace_id = trace_id
+
+ def end_trace(
+ self,
+ trace_id: Optional[str] = None,
+ trace_map: Optional[Dict[str, List[str]]] = None,
+ ) -> None:
+ """Run when an overall trace is exited."""
+ if not trace_map:
+ self.log.debug("No events in trace map to create the observation tree.")
+ return
+
+ self._create_observations_from_trace_map(
+ event_id=BASE_TRACE_EVENT, trace_map=trace_map
+ )
+ self.flush()
+
+ def on_event_start(
+ self,
+ event_type: CBEventType,
+ payload: Optional[Dict[str, Any]] = None,
+ event_id: str = "",
+ parent_id: str = "",
+ **kwargs: Any,
+ ) -> str:
+ """Run when an event starts and return id of event."""
+ start_event = CallbackEvent(
+ event_id=event_id, event_type=event_type, payload=payload
+ )
+ self.event_map[event_id].append(start_event)
+
+ return event_id
+
+ def on_event_end(
+ self,
+ event_type: CBEventType,
+ payload: Optional[Dict[str, Any]] = None,
+ event_id: str = "",
+ **kwargs: Any,
+ ) -> None:
+ """Run when an event ends."""
+ end_event = CallbackEvent(
+ event_id=event_id, event_type=event_type, payload=payload
+ )
+ self.event_map[event_id].append(end_event)
+
+ def _create_observations_from_trace_map(
+ self,
+ event_id: str,
+ trace_map: Dict[str, List[str]],
+ parent: Optional[
+ Union[StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient]
+ ] = None,
+ ) -> None:
+ """Recursively create langfuse observations based on the trace_map."""
+ if event_id != BASE_TRACE_EVENT and not self.event_map.get(event_id):
+ return
+
+ if event_id == BASE_TRACE_EVENT:
+ observation = self._get_root_observation()
+ else:
+ observation = self._create_observation(
+ event_id=event_id, parent=parent, trace_id=self.trace.id
+ )
+
+ for child_event_id in trace_map.get(event_id, []):
+ self._create_observations_from_trace_map(
+ event_id=child_event_id, parent=observation, trace_map=trace_map
+ )
+
+ def _get_root_observation(self) -> Union[StatefulTraceClient, StatefulSpanClient]:
+ if self.root is not None:
+ return self.root # return user-provided root trace or span
+
+ else:
+ self.trace = self.langfuse.trace(
+ id=str(uuid4()),
+ name=self.trace_name or f"LlamaIndex_{self._cur_trace_id}",
+ version=self.version,
+ session_id=self.session_id,
+ user_id=self.user_id,
+ )
+
+ return self.trace
+
+ def _create_observation(
+ self,
+ event_id: str,
+ parent: Union[
+ StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient
+ ],
+ trace_id: str,
+ ) -> Union[StatefulSpanClient, StatefulGenerationClient]:
+ event_type = self.event_map[event_id][0].event_type
+
+ if event_type == CBEventType.LLM:
+ return self._handle_LLM_events(event_id, parent, trace_id)
+ elif event_type == CBEventType.EMBEDDING:
+ return self._handle_embedding_events(event_id, parent, trace_id)
+ else:
+ return self._handle_span_events(event_id, parent, trace_id)
+
+ def _handle_LLM_events(
+ self,
+ event_id: str,
+ parent: Union[
+ StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient
+ ],
+ trace_id: str,
+ ) -> StatefulGenerationClient:
+ start_event, end_event = self.event_map[event_id]
+
+ if start_event.payload and EventPayload.SERIALIZED in start_event.payload:
+ serialized = start_event.payload.get(EventPayload.SERIALIZED, {})
+ name = serialized.get("class_name", "LLM")
+ temperature = serialized.get("temperature", None)
+ max_tokens = serialized.get("max_tokens", None)
+ timeout = serialized.get("timeout", None)
+
+ if end_event.payload:
+ if EventPayload.PROMPT in end_event.payload:
+ input = end_event.payload.get(EventPayload.PROMPT)
+ output = end_event.payload.get(EventPayload.COMPLETION)
+
+ elif EventPayload.MESSAGES in end_event.payload:
+ input = end_event.payload.get(EventPayload.MESSAGES)
+ response = end_event.payload.get(EventPayload.RESPONSE, {})
+ output = response.message
+ model = response.raw.get("model", None)
+ token_usage = dict(response.raw.get("usage", {}))
+ usage = None
+ if token_usage:
+ usage = {
+ "prompt_tokens": token_usage.get("prompt_tokens"),
+ "completion_tokens": token_usage.get("completion_tokens"),
+ "total_tokens": token_usage.get("total_tokens"),
+ }
+
+ generation = parent.generation(
+ id=event_id,
+ trace_id=trace_id,
+ version=self.version,
+ name=name,
+ start_time=start_event.time,
+ end_time=end_event.time,
+ usage=usage or None,
+ model=model,
+ input=input,
+ output=output,
+ metadata=end_event.payload,
+ model_parameters={
+ "temperature": temperature,
+ "max_tokens": max_tokens,
+ "request_timeout": timeout,
+ },
+ )
+
+ return generation
+
+ def _handle_embedding_events(
+ self,
+ event_id: str,
+ parent: Union[
+ StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient
+ ],
+ trace_id: str,
+ ) -> StatefulGenerationClient:
+ start_event, end_event = self.event_map[event_id]
+
+ if start_event.payload and EventPayload.SERIALIZED in start_event.payload:
+ serialized = start_event.payload.get(EventPayload.SERIALIZED, {})
+ name = serialized.get("class_name", "Embedding")
+ model = serialized.get("model_name", None)
+ timeout = serialized.get("timeout", None)
+
+ if end_event.payload:
+ chunks = end_event.payload.get(EventPayload.CHUNKS, [])
+ embeddings = end_event.payload.get(EventPayload.EMBEDDINGS, [])
+ metadata = {"num_embeddings": len(embeddings)}
+
+ usage = None
+ token_count = 0
+ for chunk in chunks:
+ token_count += self._token_counter.get_string_tokens(chunk)
+
+ usage = {
+ "prompt_tokens": token_count or None,
+ }
+
+ generation = parent.generation(
+ id=event_id,
+ trace_id=trace_id,
+ name=name,
+ start_time=start_event.time,
+ end_time=end_event.time,
+ version=self.version,
+ model=model,
+ input=chunks,
+ usage=usage or None,
+ metadata=metadata,
+ model_parameters={
+ "request_timeout": timeout,
+ },
+ )
+
+ return generation
+
+ def _handle_span_events(
+ self,
+ event_id: str,
+ parent: Union[
+ StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient
+ ],
+ trace_id: str,
+ ) -> StatefulSpanClient:
+ start_event, end_event = self.event_map[event_id]
+ input = start_event.payload
+ output = end_event.payload
+
+ if start_event.event_type == CBEventType.NODE_PARSING:
+ input, output = self._handle_node_parsing_payload(self.event_map[event_id])
+
+ elif start_event.event_type == CBEventType.CHUNKING:
+ input, output = self.handle_chunking_payload(self.event_map[event_id])
+
+ span = parent.span(
+ id=event_id,
+ trace_id=trace_id,
+ start_time=start_event.time,
+ name=start_event.event_type.value,
+ version=self.version,
+ session_id=self.session_id,
+ user_id=self.user_id, | there is no user_id on span |
langfuse-python | github_2023 | others | 384 | langfuse | maxdeichmann | @@ -7,14 +7,15 @@ license = "MIT"
readme = "README.md"
[tool.poetry.dependencies]
-python = ">=3.8.1,<4.0"
+python = ">=3.8.1,<3.12"
httpx = ">=0.15.4,<0.26.0"
pydantic = ">=1.10.7, <3.0"
backoff = "^2.2.1"
openai = ">=0.27.8"
wrapt = "1.14"
langchain = { version = ">=0.0.309", optional = true }
chevron = "^0.14.0"
+llama-index = {version = "^0.10.6", optional = true} | Do you know by any chance ntil when this implementation is stable? It would be great to also support versions which are a couple of months old. |
langfuse-python | github_2023 | python | 384 | langfuse | maxdeichmann | @@ -0,0 +1,369 @@
+from collections import defaultdict
+from typing import Any, Dict, List, Optional, Union, Tuple, Callable
+from uuid import uuid4
+import logging
+
+from langfuse.client import (
+ StatefulSpanClient,
+ StatefulTraceClient,
+ StatefulGenerationClient,
+)
+from langfuse.decorators.error_logging import (
+ auto_decorate_methods_with,
+ catch_and_log_errors,
+)
+from langfuse.callback.base import BaseCallbackHandler as LangfuseBaseCallbackHandler
+from langfuse.callback.utils import CallbackEvent
+
+try:
+ from llama_index.core.callbacks.base_handler import (
+ BaseCallbackHandler as LLamaIndexBaseCallbackHandler,
+ )
+ from llama_index.core.callbacks.schema import (
+ CBEventType,
+ BASE_TRACE_EVENT,
+ EventPayload,
+ )
+ from llama_index.core.utilities.token_counting import TokenCounter
+except ImportError:
+ raise ModuleNotFoundError(
+ "Please install llama-index to use the Langfuse llama-index integration: 'pip install llama-index'"
+ )
+
+
+@auto_decorate_methods_with(catch_and_log_errors, exclude=["__init__"])
+class LLamaIndexCallbackHandler(
+ LLamaIndexBaseCallbackHandler, LangfuseBaseCallbackHandler
+):
+ log = logging.getLogger("langfuse")
+
+ def __init__(
+ self,
+ *,
+ public_key: Optional[str] = None,
+ secret_key: Optional[str] = None,
+ host: Optional[str] = None,
+ debug: bool = False,
+ stateful_client: Optional[
+ Union[StatefulTraceClient, StatefulSpanClient]
+ ] = None,
+ session_id: Optional[str] = None,
+ user_id: Optional[str] = None,
+ trace_name: Optional[str] = None,
+ release: Optional[str] = None,
+ version: Optional[str] = None,
+ threads: Optional[int] = None,
+ flush_at: Optional[int] = None,
+ flush_interval: Optional[int] = None,
+ max_retries: Optional[int] = None,
+ timeout: Optional[int] = None,
+ event_starts_to_ignore: Optional[List[CBEventType]] = None,
+ event_ends_to_ignore: Optional[List[CBEventType]] = None,
+ tokenizer: Optional[Callable[[str], list]] = None,
+ ) -> None:
+ LLamaIndexBaseCallbackHandler.__init__(
+ self,
+ event_starts_to_ignore=event_starts_to_ignore or [],
+ event_ends_to_ignore=event_ends_to_ignore or [],
+ )
+ LangfuseBaseCallbackHandler.__init__(
+ self,
+ public_key=public_key,
+ secret_key=secret_key,
+ host=host,
+ debug=debug,
+ stateful_client=stateful_client,
+ session_id=session_id,
+ user_id=user_id,
+ trace_name=trace_name,
+ release=release,
+ version=version,
+ threads=threads,
+ flush_at=flush_at,
+ flush_interval=flush_interval,
+ max_retries=max_retries,
+ timeout=timeout,
+ sdk_integration="llama-index",
+ )
+
+ self.root = stateful_client
+ self.event_map: Dict[str, List[CallbackEvent]] = defaultdict(list)
+ self._cur_trace_id: Optional[str] = None
+ self._token_counter = TokenCounter(tokenizer)
+ | I think it would be great to have variable declaraitons for these at the top at class level to help our IDEs. |
langfuse-python | github_2023 | python | 384 | langfuse | maxdeichmann | @@ -0,0 +1,369 @@
+from collections import defaultdict
+from typing import Any, Dict, List, Optional, Union, Tuple, Callable
+from uuid import uuid4
+import logging
+
+from langfuse.client import (
+ StatefulSpanClient,
+ StatefulTraceClient,
+ StatefulGenerationClient,
+)
+from langfuse.decorators.error_logging import (
+ auto_decorate_methods_with,
+ catch_and_log_errors,
+)
+from langfuse.callback.base import BaseCallbackHandler as LangfuseBaseCallbackHandler
+from langfuse.callback.utils import CallbackEvent
+
+try:
+ from llama_index.core.callbacks.base_handler import (
+ BaseCallbackHandler as LLamaIndexBaseCallbackHandler,
+ )
+ from llama_index.core.callbacks.schema import (
+ CBEventType,
+ BASE_TRACE_EVENT,
+ EventPayload,
+ )
+ from llama_index.core.utilities.token_counting import TokenCounter
+except ImportError:
+ raise ModuleNotFoundError(
+ "Please install llama-index to use the Langfuse llama-index integration: 'pip install llama-index'"
+ )
+
+
+@auto_decorate_methods_with(catch_and_log_errors, exclude=["__init__"])
+class LLamaIndexCallbackHandler(
+ LLamaIndexBaseCallbackHandler, LangfuseBaseCallbackHandler
+):
+ log = logging.getLogger("langfuse")
+
+ def __init__(
+ self,
+ *,
+ public_key: Optional[str] = None,
+ secret_key: Optional[str] = None,
+ host: Optional[str] = None,
+ debug: bool = False,
+ stateful_client: Optional[
+ Union[StatefulTraceClient, StatefulSpanClient]
+ ] = None,
+ session_id: Optional[str] = None,
+ user_id: Optional[str] = None,
+ trace_name: Optional[str] = None,
+ release: Optional[str] = None,
+ version: Optional[str] = None,
+ threads: Optional[int] = None,
+ flush_at: Optional[int] = None,
+ flush_interval: Optional[int] = None,
+ max_retries: Optional[int] = None,
+ timeout: Optional[int] = None,
+ event_starts_to_ignore: Optional[List[CBEventType]] = None,
+ event_ends_to_ignore: Optional[List[CBEventType]] = None,
+ tokenizer: Optional[Callable[[str], list]] = None,
+ ) -> None:
+ LLamaIndexBaseCallbackHandler.__init__(
+ self,
+ event_starts_to_ignore=event_starts_to_ignore or [],
+ event_ends_to_ignore=event_ends_to_ignore or [],
+ )
+ LangfuseBaseCallbackHandler.__init__(
+ self,
+ public_key=public_key,
+ secret_key=secret_key,
+ host=host,
+ debug=debug,
+ stateful_client=stateful_client,
+ session_id=session_id,
+ user_id=user_id,
+ trace_name=trace_name,
+ release=release,
+ version=version,
+ threads=threads,
+ flush_at=flush_at,
+ flush_interval=flush_interval,
+ max_retries=max_retries,
+ timeout=timeout,
+ sdk_integration="llama-index",
+ )
+
+ self.root = stateful_client
+ self.event_map: Dict[str, List[CallbackEvent]] = defaultdict(list)
+ self._cur_trace_id: Optional[str] = None
+ self._token_counter = TokenCounter(tokenizer)
+
+ def start_trace(self, trace_id: Optional[str] = None) -> None:
+ """Run when an overall trace is launched."""
+ self._cur_trace_id = trace_id | Could you add a quick note that the trace_id is not a uuid or similar but rather a task name? |
langfuse-python | github_2023 | python | 384 | langfuse | maxdeichmann | @@ -0,0 +1,369 @@
+from collections import defaultdict
+from typing import Any, Dict, List, Optional, Union, Tuple, Callable
+from uuid import uuid4
+import logging
+
+from langfuse.client import (
+ StatefulSpanClient,
+ StatefulTraceClient,
+ StatefulGenerationClient,
+)
+from langfuse.decorators.error_logging import (
+ auto_decorate_methods_with,
+ catch_and_log_errors,
+)
+from langfuse.callback.base import BaseCallbackHandler as LangfuseBaseCallbackHandler
+from langfuse.callback.utils import CallbackEvent
+
+try:
+ from llama_index.core.callbacks.base_handler import (
+ BaseCallbackHandler as LLamaIndexBaseCallbackHandler,
+ )
+ from llama_index.core.callbacks.schema import (
+ CBEventType,
+ BASE_TRACE_EVENT,
+ EventPayload,
+ )
+ from llama_index.core.utilities.token_counting import TokenCounter
+except ImportError:
+ raise ModuleNotFoundError(
+ "Please install llama-index to use the Langfuse llama-index integration: 'pip install llama-index'"
+ )
+
+
+@auto_decorate_methods_with(catch_and_log_errors, exclude=["__init__"])
+class LLamaIndexCallbackHandler(
+ LLamaIndexBaseCallbackHandler, LangfuseBaseCallbackHandler
+):
+ log = logging.getLogger("langfuse")
+
+ def __init__(
+ self,
+ *,
+ public_key: Optional[str] = None,
+ secret_key: Optional[str] = None,
+ host: Optional[str] = None,
+ debug: bool = False,
+ stateful_client: Optional[
+ Union[StatefulTraceClient, StatefulSpanClient]
+ ] = None,
+ session_id: Optional[str] = None,
+ user_id: Optional[str] = None,
+ trace_name: Optional[str] = None,
+ release: Optional[str] = None,
+ version: Optional[str] = None,
+ threads: Optional[int] = None,
+ flush_at: Optional[int] = None,
+ flush_interval: Optional[int] = None,
+ max_retries: Optional[int] = None,
+ timeout: Optional[int] = None,
+ event_starts_to_ignore: Optional[List[CBEventType]] = None,
+ event_ends_to_ignore: Optional[List[CBEventType]] = None,
+ tokenizer: Optional[Callable[[str], list]] = None,
+ ) -> None:
+ LLamaIndexBaseCallbackHandler.__init__(
+ self,
+ event_starts_to_ignore=event_starts_to_ignore or [],
+ event_ends_to_ignore=event_ends_to_ignore or [],
+ )
+ LangfuseBaseCallbackHandler.__init__(
+ self,
+ public_key=public_key,
+ secret_key=secret_key,
+ host=host,
+ debug=debug,
+ stateful_client=stateful_client,
+ session_id=session_id,
+ user_id=user_id,
+ trace_name=trace_name,
+ release=release,
+ version=version,
+ threads=threads,
+ flush_at=flush_at,
+ flush_interval=flush_interval,
+ max_retries=max_retries,
+ timeout=timeout,
+ sdk_integration="llama-index",
+ )
+
+ self.root = stateful_client
+ self.event_map: Dict[str, List[CallbackEvent]] = defaultdict(list)
+ self._cur_trace_id: Optional[str] = None
+ self._token_counter = TokenCounter(tokenizer)
+
+ def start_trace(self, trace_id: Optional[str] = None) -> None:
+ """Run when an overall trace is launched."""
+ self._cur_trace_id = trace_id
+
+ def end_trace(
+ self,
+ trace_id: Optional[str] = None,
+ trace_map: Optional[Dict[str, List[str]]] = None,
+ ) -> None:
+ """Run when an overall trace is exited."""
+ if not trace_map:
+ self.log.debug("No events in trace map to create the observation tree.")
+ return
+
+ self._create_observations_from_trace_map(
+ event_id=BASE_TRACE_EVENT, trace_map=trace_map
+ )
+
+ def on_event_start(
+ self,
+ event_type: CBEventType,
+ payload: Optional[Dict[str, Any]] = None,
+ event_id: str = "",
+ parent_id: str = "",
+ **kwargs: Any,
+ ) -> str:
+ """Run when an event starts and return id of event."""
+ start_event = CallbackEvent(
+ event_id=event_id, event_type=event_type, payload=payload
+ )
+ self.event_map[event_id].append(start_event)
+
+ return event_id
+
+ def on_event_end(
+ self,
+ event_type: CBEventType,
+ payload: Optional[Dict[str, Any]] = None,
+ event_id: str = "",
+ **kwargs: Any,
+ ) -> None:
+ """Run when an event ends."""
+ end_event = CallbackEvent(
+ event_id=event_id, event_type=event_type, payload=payload
+ )
+ self.event_map[event_id].append(end_event)
+
+ def _create_observations_from_trace_map(
+ self,
+ event_id: str,
+ trace_map: Dict[str, List[str]],
+ parent: Optional[
+ Union[StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient]
+ ] = None,
+ ) -> None:
+ """Recursively create langfuse observations based on the trace_map."""
+ if event_id != BASE_TRACE_EVENT and not self.event_map.get(event_id):
+ return
+
+ if event_id == BASE_TRACE_EVENT:
+ observation = self._get_root_observation()
+ else:
+ observation = self._create_observation(
+ event_id=event_id, parent=parent, trace_id=self.trace.id
+ )
+
+ for child_event_id in trace_map.get(event_id, []):
+ self._create_observations_from_trace_map(
+ event_id=child_event_id, parent=observation, trace_map=trace_map
+ )
+
+ def _get_root_observation(self) -> Union[StatefulTraceClient, StatefulSpanClient]:
+ if self.root is not None:
+ return self.root # return user-provided root trace or span
+
+ else:
+ self.trace = self.langfuse.trace(
+ id=str(uuid4()),
+ name=self.trace_name or f"LlamaIndex_{self._cur_trace_id}",
+ version=self.version,
+ session_id=self.session_id,
+ user_id=self.user_id,
+ )
+
+ return self.trace
+
+ def _create_observation(
+ self,
+ event_id: str,
+ parent: Union[
+ StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient
+ ],
+ trace_id: str,
+ ) -> Union[StatefulSpanClient, StatefulGenerationClient]:
+ event_type = self.event_map[event_id][0].event_type
+
+ if event_type == CBEventType.LLM:
+ return self._handle_LLM_events(event_id, parent, trace_id)
+ elif event_type == CBEventType.EMBEDDING:
+ return self._handle_embedding_events(event_id, parent, trace_id)
+ else:
+ return self._handle_span_events(event_id, parent, trace_id)
+
+ def _handle_LLM_events(
+ self,
+ event_id: str,
+ parent: Union[
+ StatefulTraceClient, StatefulSpanClient, StatefulGenerationClient
+ ],
+ trace_id: str,
+ ) -> StatefulGenerationClient:
+ start_event, end_event = self.event_map[event_id]
+
+ if start_event.payload and EventPayload.SERIALIZED in start_event.payload:
+ serialized = start_event.payload.get(EventPayload.SERIALIZED, {})
+ name = serialized.get("class_name", "LLM")
+ temperature = serialized.get("temperature", None)
+ max_tokens = serialized.get("max_tokens", None)
+ timeout = serialized.get("timeout", None)
+
+ if end_event.payload:
+ if EventPayload.PROMPT in end_event.payload:
+ input = end_event.payload.get(EventPayload.PROMPT)
+ output = end_event.payload.get(EventPayload.COMPLETION)
+
+ elif EventPayload.MESSAGES in end_event.payload:
+ input = end_event.payload.get(EventPayload.MESSAGES)
+ response = end_event.payload.get(EventPayload.RESPONSE, {})
+ output = response.message
+ if hasattr(output, "additional_kwargs"):
+ delattr(output, "additional_kwargs") | I think we would want to keep the additional_kwargs in case there is something in there. |
langfuse-python | github_2023 | python | 384 | langfuse | maxdeichmann | @@ -0,0 +1,369 @@
+from collections import defaultdict
+from typing import Any, Dict, List, Optional, Union, Tuple, Callable
+from uuid import uuid4
+import logging
+
+from langfuse.client import (
+ StatefulSpanClient,
+ StatefulTraceClient,
+ StatefulGenerationClient,
+)
+from langfuse.decorators.error_logging import (
+ auto_decorate_methods_with,
+ catch_and_log_errors,
+)
+from langfuse.callback.base import BaseCallbackHandler as LangfuseBaseCallbackHandler
+from langfuse.callback.utils import CallbackEvent
+
+try:
+ from llama_index.core.callbacks.base_handler import (
+ BaseCallbackHandler as LLamaIndexBaseCallbackHandler,
+ )
+ from llama_index.core.callbacks.schema import (
+ CBEventType,
+ BASE_TRACE_EVENT,
+ EventPayload,
+ )
+ from llama_index.core.utilities.token_counting import TokenCounter
+except ImportError:
+ raise ModuleNotFoundError(
+ "Please install llama-index to use the Langfuse llama-index integration: 'pip install llama-index'"
+ )
+
+
+@auto_decorate_methods_with(catch_and_log_errors, exclude=["__init__"])
+class LLamaIndexCallbackHandler(
+ LLamaIndexBaseCallbackHandler, LangfuseBaseCallbackHandler
+):
+ log = logging.getLogger("langfuse")
+
+ def __init__(
+ self,
+ *,
+ public_key: Optional[str] = None,
+ secret_key: Optional[str] = None,
+ host: Optional[str] = None,
+ debug: bool = False,
+ stateful_client: Optional[
+ Union[StatefulTraceClient, StatefulSpanClient]
+ ] = None,
+ session_id: Optional[str] = None,
+ user_id: Optional[str] = None,
+ trace_name: Optional[str] = None,
+ release: Optional[str] = None,
+ version: Optional[str] = None,
+ threads: Optional[int] = None,
+ flush_at: Optional[int] = None,
+ flush_interval: Optional[int] = None,
+ max_retries: Optional[int] = None,
+ timeout: Optional[int] = None,
+ event_starts_to_ignore: Optional[List[CBEventType]] = None,
+ event_ends_to_ignore: Optional[List[CBEventType]] = None,
+ tokenizer: Optional[Callable[[str], list]] = None,
+ ) -> None:
+ LLamaIndexBaseCallbackHandler.__init__(
+ self,
+ event_starts_to_ignore=event_starts_to_ignore or [],
+ event_ends_to_ignore=event_ends_to_ignore or [],
+ )
+ LangfuseBaseCallbackHandler.__init__(
+ self,
+ public_key=public_key,
+ secret_key=secret_key,
+ host=host,
+ debug=debug,
+ stateful_client=stateful_client,
+ session_id=session_id,
+ user_id=user_id,
+ trace_name=trace_name,
+ release=release,
+ version=version,
+ threads=threads,
+ flush_at=flush_at,
+ flush_interval=flush_interval,
+ max_retries=max_retries,
+ timeout=timeout,
+ sdk_integration="llama-index",
+ )
+
+ self.root = stateful_client
+ self.event_map: Dict[str, List[CallbackEvent]] = defaultdict(list)
+ self._cur_trace_id: Optional[str] = None
+ self._token_counter = TokenCounter(tokenizer)
+
+ def start_trace(self, trace_id: Optional[str] = None) -> None:
+ """Run when an overall trace is launched."""
+ self._cur_trace_id = trace_id
+
+ def end_trace(
+ self,
+ trace_id: Optional[str] = None,
+ trace_map: Optional[Dict[str, List[str]]] = None,
+ ) -> None:
+ """Run when an overall trace is exited."""
+ if not trace_map:
+ self.log.debug("No events in trace map to create the observation tree.")
+ return
+
+ self._create_observations_from_trace_map( | can you add a short comment on why we do this at the end and the performance implications for index + query? |
langfuse-python | github_2023 | python | 367 | langfuse | maxdeichmann | @@ -0,0 +1,94 @@
+from contextlib import asynccontextmanager
+from fastapi import FastAPI, Query, BackgroundTasks
+import os
+import sys
+from langfuse import Langfuse
+from langfuse.openai import openai
+import uvicorn
+
+
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+ # Operation on startup
+
+ yield # wait until shutdown
+
+ # Flush all events to be sent to Langfuse on shutdown. This operation is blocking.
+ langfuse.flush()
+
+
+app = FastAPI(lifespan=lifespan)
+
+
+@app.get("/")
+async def main_route():
+ return {"message": "Hey, this is an example showing how to use Langfuse with FastAPI."}
+
+# Initialize Langfuse
+langfuse = Langfuse(public_key="pk-lf-1234567890", secret_key="sk-lf-1234567890", host="http://localhost:3000")
+
+async def get_response_openai(prompt, background_tasks: BackgroundTasks): | I think we can remove the function parameters here, right? |
langfuse-python | github_2023 | python | 367 | langfuse | maxdeichmann | @@ -0,0 +1,94 @@
+from contextlib import asynccontextmanager
+from fastapi import FastAPI, Query, BackgroundTasks
+import os
+import sys
+from langfuse import Langfuse
+from langfuse.openai import openai
+import uvicorn
+ | We can also remove all the unused imports here |
langfuse-python | github_2023 | others | 367 | langfuse | maxdeichmann | @@ -0,0 +1,24 @@
+# fastapi_example
+
+This is an example FastAPI application showcasing integration with Langfuse for event tracing and response generation.
+
+1. **Shutdown Behavior**: The application defines shutdown logic using FastAPI's lifespan feature. On shutdown, it flushes all events to Langfuse, ensuring data integrity and completeness.
+
+2. **Endpoints**:
+ - `/`: Returns a simple message demonstrating the usage of Langfuse with FastAPI.
+ - `/campaign/`: Accepts a prompt query parameter and utilizes OpenAI to generate a response. It also traces events using Langfuse.
+
+3. **Integration**:
+ - Langfuse: Utilized for event tracing with `trace`, `score`, `generation`, and `span` operations. (Note that OpenAI is not actually used here to generate an answer to the prompt. This example is just to show how to use FastAPI with the Langfuse SDK)
+
+4. **Dependencies**:
+ - FastAPI: Web framework for building APIs.
+ - Langfuse: Library for event tracing and management.
+ - OpenAI: AI platform for natural language processing. | I think we can remove openai here, as this is not used, right? |
langfuse-python | github_2023 | others | 367 | langfuse | maxdeichmann | @@ -0,0 +1,19 @@
+[tool.poetry]
+name = "fastapi-example"
+version = "0.1.0"
+description = ""
+authors = ["ChrisTho23 <christophe.thomassin23@gmail.com>"]
+readme = "README.md"
+
+[tool.poetry.dependencies]
+python = "^3.10"
+fastapi = "^0.109.2"
+uvicorn = "^0.27.1"
+langfuse = "2.13.3a0" | can you use latest langfuse here always? |
langfuse-python | github_2023 | python | 367 | langfuse | maxdeichmann | @@ -0,0 +1,11 @@
+from django.shortcuts import render
+from django.http import JsonResponse, HttpResponseServerError
+from myapp.langfuse_integration import get_response_openai, langfuse | i think here are some unused imports |
langfuse-python | github_2023 | others | 367 | langfuse | maxdeichmann | @@ -0,0 +1,16 @@
+[tool.poetry]
+name = "django-example"
+version = "0.1.0"
+description = ""
+authors = ["ChrisTho23 <christophe.thomassin23@gmail.com>"]
+readme = "README.md"
+
+[tool.poetry.dependencies]
+python = "^3.10"
+django = "^5.0.2"
+langfuse = "^2.13.3" | Can we also use latest here always? |
langfuse-python | github_2023 | python | 367 | langfuse | maxdeichmann | @@ -0,0 +1,16 @@
+import os
+import signal
+import sys
+from .langfuse_integration import langfuse_flush
+
+def shutdwon_handler(*args):
+ """
+ This function handles the shutdown process.
+
+ It calls the langfuse_flush function to flush any pending changes,
+ and then exits the program with a status code of 0.
+ """
+ langfuse_flush()
+ sys.exit(0)
+
+signal.signal(signal.SIGINT, shutdwon_handler) | I think we can also listen to sigterm here as this is used to gracefully terminate a process. https://www.baeldung.com/linux/sigint-and-other-termination-signals |
langfuse-python | github_2023 | others | 343 | langfuse | maxdeichmann | @@ -79,3 +79,11 @@ poetry run pre-commit install
- Create PyPi API token: https://pypi.org/manage/account/token/
- Setup: `poetry config pypi-token.pypi your-api-token`
9. Create a release on GitHub with the changelog
+
+### SDK Reference
+
+The SDK reference is generated via pdoc. To update the reference, run the following command:
+
+```
+poetry run pdoc -o docs/ langfuse | can you also add a comment on hot wo install the docs group before running this command? |
langfuse-python | github_2023 | python | 332 | langfuse | maxdeichmann | @@ -23,7 +23,7 @@ def __init__(
base_url: str,
version: str,
timeout: int,
- session: httpx.Client,
+ session: httpx.Client = httpx.Client(), | why is this change required? |
langfuse-python | github_2023 | python | 326 | langfuse | maxdeichmann | @@ -59,3 +59,13 @@ def __init__(self, prompt: Prompt):
def compile(self, **kwargs) -> str:
return chevron.render(self.prompt, kwargs)
+
+ def __eq__(self, other): | This here is only used in testing code at the moment, correct? |
langfuse-python | github_2023 | python | 102 | langfuse | maxdeichmann | @@ -524,7 +538,9 @@ def on_llm_end(
)
self.runs[run_id].state = self.runs[run_id].state.update(
- UpdateGeneration(completion=extracted_response, end_time=datetime.now(), usage=llm_usage)
+ UpdateGeneration(
+ completion=extracted_response, end_time=datetime.now(), usage=llm_usage, metadata=token_metadata | Why do you want to put the token metadata on the metadata as well? We are already tracking that in `usage`. |
langfuse-python | github_2023 | python | 150 | langfuse | maxdeichmann | @@ -652,6 +652,36 @@ def initialize_huggingface_llm(prompt: PromptTemplate) -> LLMChain:
assert observation["output"] is not None
assert observation["output"] != ""
+def test_callback_huggingface_pipeline(): | ```
tests/test_langchain.py::test_callback_huggingface_pipeline FAILED
============================================================================================= FAILURES ==============================================================================================
________________________________________________________________________________ test_callback_huggingface_pipeline _________________________________________________________________________________
def test_callback_huggingface_pipeline():
api_wrapper = LangfuseAPI()
handler = CallbackHandler(debug=False)
def initialize_huggingface_llm(prompt: PromptTemplate) -> LLMChain:
class fake_llm:
task = "summarization"
def __call__(self, *args: Any, **kwds: Any) -> Any:
return [{"summary_text": "fake"}]
llm = HuggingFacePipeline(pipeline=fake_llm())
return LLMChain(prompt=prompt, llm=llm)
> hugging_chain = initialize_huggingface_llm(prompt=PromptTemplate(input_variables=["title"], template="""fake"""))
tests/test_langchain.py:814:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
../../../../Library/Caches/pypoetry/virtualenvs/langfuse-3vNqg5EL-py3.9/lib/python3.9/site-packages/langchain/load/serializable.py:97: in __init__
super().__init__(**kwargs)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
> ???
E pydantic.error_wrappers.ValidationError: 1 validation error for PromptTemplate
E __root__
E Invalid prompt schema; check for mismatched or missing input parameters. {'title'} (type=value_error)
pydantic/main.py:341: ValidationError
```
Do you get the same error when executing this? |
langfuse-python | github_2023 | python | 215 | langfuse | marcklingen | @@ -274,7 +294,8 @@ def on_agent_action(
if run_id not in self.runs:
raise Exception("run not found")
- self.runs[run_id] = self.runs[run_id].update(UpdateSpan(endTime=datetime.now(), output=action, version=self.version))
+ self.runs[run_id] = self.runs[run_id].update(endTime=datetime.now(), output=action, version=self.version)
+ self.__update_trace(run_id, parent_run_id, action) | why arent agent actions spans? |
langfuse-python | github_2023 | python | 215 | langfuse | marcklingen | @@ -415,82 +597,228 @@ def _add_default_values(self, body: dict):
body["start_time"] = datetime.now()
return body
- def generation(self, body: CreateGeneration):
+ def generation(
+ self,
+ *,
+ id: typing.Optional[str] = None,
+ name: typing.Optional[str] = None,
+ start_time: typing.Optional[dt.datetime] = None,
+ end_time: typing.Optional[dt.datetime] = None,
+ metadata: typing.Optional[typing.Any] = None,
+ level: typing.Optional[Literal["DEBUG", "DEFAULT", "WARNING", "ERROR"]] = None,
+ status_message: typing.Optional[str] = None,
+ version: typing.Optional[str] = None,
+ completion_start_time: typing.Optional[dt.datetime] = None,
+ model: typing.Optional[str] = None,
+ model_parameters: typing.Optional[typing.Dict[str, MapValue]] = None,
+ input: typing.Optional[typing.Any] = None,
+ output: typing.Optional[typing.Any] = None,
+ usage: typing.Optional[typing.Union[pydantic.BaseModel, ModelUsage]] = None,
+ **kwargs,
+ ):
try:
- generation_id = str(uuid.uuid4()) if body.id is None else body.id
+ generation_id = str(uuid.uuid4()) if id is None else id
+
+ generation_body = {
+ "id": generation_id,
+ "name": name,
+ "start_time": start_time if start_time is not None else datetime.now(),
+ "metadata": metadata,
+ "level": level,
+ "status_message": status_message,
+ "version": version,
+ "end_time": end_time,
+ "completion_start_time": completion_start_time,
+ "model": model,
+ "model_parameters": model_parameters,
+ "input": input,
+ "output": output,
+ "usage": _convert_usage_input(usage) if usage is not None else None,
+ }
+
+ if kwargs is not None:
+ generation_body.update(kwargs)
- new_body = body.copy(update={"id": generation_id})
- new_body = self._add_state_to_event(new_body.dict())
- new_body = self._add_default_values(new_body)
+ generation_body = self._add_state_to_event(generation_body)
+ new_body = self._add_default_values(generation_body)
- new_body = CreateGenerationRequest(**new_body)
+ new_body = CreateGenerationBody(**new_body)
+
+ event = {
+ "id": str(uuid.uuid4()),
+ "type": "generation-create",
+ "body": new_body.dict(exclude_none=True),
+ }
self.log.debug(f"Creating generation {new_body}...")
- self.task_manager.add_task(
- convert_observation_to_event(new_body, "GENERATION"),
+ self.task_manager.add_task(event)
+
+ return StatefulGenerationClient(
+ self.client,
+ generation_id,
+ StateType.OBSERVATION,
+ self.trace_id,
+ task_manager=self.task_manager,
)
- return StatefulGenerationClient(self.client, generation_id, StateType.OBSERVATION, self.trace_id, task_manager=self.task_manager)
except Exception as e:
self.log.exception(e)
- def span(self, body: CreateSpan):
+ def span(
+ self,
+ *,
+ id: typing.Optional[str] = None,
+ name: typing.Optional[str] = None,
+ start_time: typing.Optional[dt.datetime] = None,
+ end_time: typing.Optional[dt.datetime] = None,
+ metadata: typing.Optional[typing.Any] = None,
+ input: typing.Optional[typing.Any] = None,
+ output: typing.Optional[typing.Any] = None,
+ level: typing.Optional[Literal["DEBUG", "DEFAULT", "WARNING", "ERROR"]] = None,
+ status_message: typing.Optional[str] = None,
+ version: typing.Optional[str] = None,
+ **kwargs,
+ ):
try:
- span_id = str(uuid.uuid4()) if body.id is None else body.id
+ span_id = str(uuid.uuid4()) if id is None else id
+
+ span_body = {
+ "id": span_id,
+ "name": name,
+ "start_time": start_time if start_time is not None else datetime.now(),
+ "metadata": metadata,
+ "input": input,
+ "output": output,
+ "level": level,
+ "status_message": status_message,
+ "version": version,
+ "end_time": end_time,
+ }
- new_body = body.copy(update={"id": span_id})
- self.log.debug(f"Creating span {new_body}...")
+ if kwargs is not None:
+ span_body.update(kwargs)
- new_dict = self._add_state_to_event(new_body.dict())
+ self.log.debug(f"Creating span {span_body}...")
+
+ new_dict = self._add_state_to_event(span_body)
new_body = self._add_default_values(new_dict)
- request = CreateSpanRequest(**new_dict)
- event = convert_observation_to_event(request, "SPAN")
+ event = CreateSpanBody(**new_body)
+
+ event = {
+ "id": str(uuid.uuid4()),
+ "type": "span-create",
+ "body": event.dict(exclude_none=True),
+ }
self.task_manager.add_task(event)
- return StatefulSpanClient(self.client, span_id, StateType.OBSERVATION, self.trace_id, task_manager=self.task_manager)
+ return StatefulSpanClient(
+ self.client,
+ span_id,
+ StateType.OBSERVATION,
+ self.trace_id,
+ task_manager=self.task_manager,
+ )
except Exception as e:
self.log.exception(e)
- def score(self, body: CreateScore):
+ def score(
+ self,
+ *,
+ id: typing.Optional[str] = None,
+ name: str,
+ value: float,
+ comment: typing.Optional[str] = None,
+ kwargs=None,
+ ):
try:
- score_id = str(uuid.uuid4()) if body.id is None else body.id
+ score_id = str(uuid.uuid4()) if id is None else id
+
+ new_score = {
+ "id": score_id,
+ "trace_id": self.trace_id,
+ "name": name,
+ "value": value,
+ "comment": comment,
+ }
+
+ if kwargs is not None:
+ new_score.update(kwargs)
- new_body = body.copy(update={"id": score_id})
- self.log.debug(f"Creating score {new_body}...")
+ self.log.debug(f"Creating score {new_score}...")
- new_dict = self._add_state_to_event(new_body.dict())
+ new_dict = self._add_state_to_event(new_score)
if self.state_type == StateType.OBSERVATION:
new_dict["observationId"] = self.id
- request = CreateScoreRequest(**new_dict)
+ request = ScoreBody(**new_dict)
event = {
"id": str(uuid.uuid4()),
"type": "score-create",
- "body": request.dict(),
+ "body": request.dict(exclude_none=True),
}
self.task_manager.add_task(event)
- return StatefulClient(self.client, self.id, StateType.OBSERVATION, self.trace_id, task_manager=self.task_manager)
+ return StatefulClient(
+ self.client,
+ self.id,
+ StateType.OBSERVATION,
+ self.trace_id,
+ task_manager=self.task_manager,
+ )
except Exception as e:
self.log.exception(e)
- def event(self, body: CreateEvent):
+ def event( | event() does not exist in `class Langfuse` |
langfuse-python | github_2023 | python | 215 | langfuse | marcklingen | @@ -143,16 +158,29 @@ def _get_langfuse_data_from_kwargs(resource: OpenAiDefinition, langfuse: Langfus
modelParameters = {
"temperature": kwargs.get("temperature", 1),
- "maxTokens": kwargs.get("max_tokens", float("inf")),
+ "maxTokens": kwargs.get("max_tokens", float("inf")), # casing? | max_tokens? added comment to be able to comment on this |
langfuse-python | github_2023 | python | 134 | langfuse | maxdeichmann | @@ -466,6 +466,8 @@ def __on_llm_action(
)
if kwargs["invocation_params"]["_type"] in ["anthropic-llm", "anthropic-chat"]:
model_name = "anthropic" # unfortunately no model info by anthropic provided.
+ elif kwargs["invocation_params"]["_type"] == "amazon_bedrock":
+ model_name = "claude" # unfortunately no model info by Bedrock provided. | @kobrinartem thanks for the contribution! Did you test whether Langchain somehow provides the model name? |
langfuse-python | github_2023 | python | 144 | langfuse | maxdeichmann | @@ -11,7 +11,10 @@
class TraceWithDetails(Trace):
observations: typing.List[str] = pydantic.Field(description=("List of observation ids\n"))
- scores: typing.List[str] = pydantic.Field(description=("List of score ids\n"))
+ scores: typing.List[str] = pydantic.Field(
+ description=("List of score ids\n"),
+ default_factory=list | is this wanted? |
langfuse-python | github_2023 | python | 103 | langfuse | maxdeichmann | @@ -0,0 +1,16 @@
+from dotenv import load_dotenv
+from langfuse.integrations import openai
+
+load_dotenv()
+
+
+def test_openai_chat_completion():
+ completion = openai.ChatCompletion.create(
+ model="gpt-3.5-turbo", messages=[{"role": "user", "content": "1 + 1 = "}], temperature=0
+ )
+ assert len(completion.choices) != 0
+
+
+def test_openai_completion():
+ completion = openai.Completion.create(model="gpt-3.5-turbo-instruct", prompt="1 + 1 = ", temperature=0)
+ assert len(completion.choices) != 0 | can you expose the flush function and call it in the tests? Also, did you try running this locally? |
langfuse-python | github_2023 | python | 103 | langfuse | maxdeichmann | @@ -0,0 +1,83 @@
+import os
+import functools
+from datetime import datetime
+from dotenv import load_dotenv
+
+import openai
+from openai.api_resources import ChatCompletion, Completion
+
+from langfuse import Langfuse
+from langfuse.client import InitialGeneration
+from langfuse.api.resources.commons.types.llm_usage import LlmUsage
+
+
+load_dotenv() | Why is this needed here? So far this worked without |
langfuse-python | github_2023 | python | 103 | langfuse | maxdeichmann | @@ -0,0 +1,83 @@
+import os
+import functools
+from datetime import datetime
+from dotenv import load_dotenv
+
+import openai
+from openai.api_resources import ChatCompletion, Completion
+
+from langfuse import Langfuse
+from langfuse.client import InitialGeneration
+from langfuse.api.resources.commons.types.llm_usage import LlmUsage
+
+
+load_dotenv()
+
+
+class OpenAILangfuse: | I would maybe rename the class to reflect a bit better of how it works. |
langfuse-python | github_2023 | python | 103 | langfuse | maxdeichmann | @@ -0,0 +1,83 @@
+import os
+import functools
+from datetime import datetime
+from dotenv import load_dotenv
+
+import openai
+from openai.api_resources import ChatCompletion, Completion
+
+from langfuse import Langfuse
+from langfuse.client import InitialGeneration
+from langfuse.api.resources.commons.types.llm_usage import LlmUsage
+
+
+load_dotenv()
+
+
+class OpenAILangfuse:
+ def __init__(self):
+ self.langfuse = Langfuse(os.environ["LF_PK"], os.environ["LF_SK"], os.environ["HOST"])
+
+ def _get_call_details(self, result, **kwargs):
+ if result.object == "chat.completion":
+ prompt = kwargs.get("messages", [{}])[-1].get("content", "")
+ completion = result.choices[-1].message.content
+ elif result.object == "text_completion":
+ prompt = kwargs.get("prompt", "")
+ completion = result.choices[-1].text
+ else:
+ completion = ""
+ model = result.model
+ usage = None if result.usage is None else LlmUsage(**result.usage)
+ endTime = datetime.now()
+ modelParameters = {
+ "temperature": kwargs.get("temperature", 1),
+ "maxTokens": kwargs.get("max_tokens", float("inf")),
+ "top_p": kwargs.get("top_p", 1),
+ "frequency_penalty": kwargs.get("frequency_penalty", 0),
+ "presence_penalty": kwargs.get("presence_penalty", 0),
+ }
+ all_details = {
+ "prompt": prompt,
+ "completion": completion,
+ "endTime": endTime,
+ "model": model,
+ "modelParameters": modelParameters,
+ "usage": usage,
+ }
+ return all_details
+
+ def _log_result(self, result, call_details):
+ generation = InitialGeneration(name="OpenAI-generation", **call_details)
+ self.langfuse.generation(generation)
+ self.langfuse.flush()
+ return result
+
+ def langfuse_modified(self, func):
+ @functools.wraps(func)
+ def wrapper(**kwargs):
+ try:
+ startTime = datetime.now()
+ result = func(**kwargs)
+ call_details = self._get_call_details(result, **kwargs)
+ call_details["startTime"] = startTime
+ except Exception as ex:
+ raise ex
+
+ return self._log_result(result, call_details)
+
+ return wrapper
+
+ def set_openai_funcs(self): | maybe `replace_openai_funcs`? |
langfuse-python | github_2023 | python | 103 | langfuse | maxdeichmann | @@ -0,0 +1,40 @@
+import os
+from dotenv import load_dotenv
+from langfuse.integrations import openai
+from langfuse.api.client import FintoLangfuse
+from langfuse.version import __version__ as version
+
+from tests.utils import create_uuid
+
+
+load_dotenv()
+
+api = FintoLangfuse(
+ environment=os.environ["HOST"],
+ username=os.environ["LF_PK"],
+ password=os.environ["LF_SK"],
+)
+
+
+def test_openai_chat_completion():
+ trace_id = create_uuid()
+ completion = openai.ChatCompletion.create( | I just tested this out locally. openai is shown on my end as type any in the IDE, whereas when using the original openai SDK, i get autocompletions. Is there a way to solve that? |
langfuse-python | github_2023 | python | 103 | langfuse | maxdeichmann | @@ -0,0 +1,99 @@
+import os
+import functools
+from datetime import datetime
+from dotenv import load_dotenv
+
+import openai
+from openai.api_resources import ChatCompletion, Completion
+
+from langfuse import Langfuse
+from langfuse.client import InitialGeneration
+from langfuse.api.resources.commons.types.llm_usage import LlmUsage
+
+
+load_dotenv()
+
+
+class CreateArgsExtractor:
+ def __init__(self, name=None, **kwargs):
+ self.args = {}
+ self.args["name"] = name
+ self.kwargs = kwargs
+
+ def get_langfuse_args(self):
+ return {**self.args, **self.kwargs}
+
+ def get_openai_args(self):
+ return self.kwargs
+
+
+class OpenAILangfuse:
+ def __init__(self):
+ self.langfuse = Langfuse(os.environ["LF_PK"], os.environ["LF_SK"], os.environ["HOST"])
+
+ def _get_call_details(self, result, **kwargs):
+ name = kwargs.get("name", "OpenAI-generation")
+ if result.object == "chat.completion":
+ prompt = kwargs.get("messages", [{}])[-1].get("content", "")
+ completion = result.choices[-1].message.content
+ elif result.object == "text_completion":
+ prompt = kwargs.get("prompt", "")
+ completion = result.choices[-1].text
+ else:
+ completion = ""
+ model = result.model
+ usage = None if result.usage is None else LlmUsage(**result.usage)
+ endTime = datetime.now()
+ modelParameters = {
+ "temperature": kwargs.get("temperature", 1),
+ "maxTokens": kwargs.get("max_tokens", float("inf")),
+ "top_p": kwargs.get("top_p", 1),
+ "frequency_penalty": kwargs.get("frequency_penalty", 0),
+ "presence_penalty": kwargs.get("presence_penalty", 0),
+ }
+ all_details = {
+ "name": name,
+ "prompt": prompt,
+ "completion": completion,
+ "endTime": endTime,
+ "model": model,
+ "modelParameters": modelParameters,
+ "usage": usage,
+ }
+ return all_details
+
+ def _log_result(self, result, call_details):
+ generation = InitialGeneration(**call_details)
+ self.langfuse.generation(generation)
+ self.langfuse.flush()
+ return result
+
+ def langfuse_modified(self, func):
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ try:
+ startTime = datetime.now()
+ arg_extractor = CreateArgsExtractor(*args, **kwargs)
+ result = func(**arg_extractor.get_openai_args())
+ call_details = self._get_call_details(result, **arg_extractor.get_langfuse_args())
+ call_details["startTime"] = startTime
+ except Exception as ex:
+ raise ex
+
+ return self._log_result(result, call_details)
+
+ return wrapper
+
+ def replace_openai_funcs(self):
+ api_resources_classes = [
+ (ChatCompletion, "create"),
+ (Completion, "create"),
+ ]
+
+ for api_resource_class, method in api_resources_classes:
+ create_method = getattr(api_resource_class, method)
+ setattr(api_resource_class, method, self.langfuse_modified(create_method))
+
+
+modifier = OpenAILangfuse() | Do you think we can instantiate this as a Singleton? I fear our users will import this multiple times and then create multiple Langfuse objects under the hood.
I think one instantiation of the Langfuse object would be ideal. Could we also expose the flush function from there? If yes, we can remove it above in the `_log_result` method and thereby save latencies for our users |
langfuse-python | github_2023 | python | 103 | langfuse | fxmb | @@ -0,0 +1,99 @@
+import os
+import functools
+from datetime import datetime
+from dotenv import load_dotenv
+
+import openai
+from openai.api_resources import ChatCompletion, Completion | @maxdeichmann we should probably not fully import "lesser known" packages directly to provide more context. Can we change this to `from openai import api_resources` and then call like `api_resources.ChatCompletion`? Just a thought |
langfuse-python | github_2023 | python | 103 | langfuse | fxmb | @@ -0,0 +1,99 @@
+import os
+import functools
+from datetime import datetime
+from dotenv import load_dotenv
+
+import openai
+from openai.api_resources import ChatCompletion, Completion
+
+from langfuse import Langfuse
+from langfuse.client import InitialGeneration
+from langfuse.api.resources.commons.types.llm_usage import LlmUsage
+
+
+load_dotenv()
+
+
+class CreateArgsExtractor:
+ def __init__(self, name=None, **kwargs):
+ self.args = {}
+ self.args["name"] = name
+ self.kwargs = kwargs
+
+ def get_langfuse_args(self):
+ return {**self.args, **self.kwargs}
+
+ def get_openai_args(self):
+ return self.kwargs
+
+
+class OpenAILangfuse:
+ def __init__(self):
+ self.langfuse = Langfuse(os.environ["LF_PK"], os.environ["LF_SK"], os.environ["HOST"]) | This will throw an error if key is not present afaik. Is this intended? Rather use `getenv()` and provide fallback logic in case key is not present? It's a personal preference so feel free to ignore. |
langfuse-python | github_2023 | python | 116 | langfuse | github-advanced-security[bot] | @@ -1,5 +1,17 @@
+import os
from uuid import uuid4
+from langfuse.api.client import FintoLangfuse
+
def create_uuid():
return str(uuid4())
+
+
+def get_api():
+ print(os.environ.get("LANGFUSE_PUBLIC_KEY"), os.environ.get("LANGFUSE_SECRET_KEY"), os.environ.get("LANGFUSE_HOST")) | ## Clear-text logging of sensitive information
This expression logs [sensitive data (secret)](1) as clear text.
[Show more details](https://github.com/langfuse/langfuse-python/security/code-scanning/1) |
langfuse-python | github_2023 | python | 100 | langfuse | marcklingen | @@ -36,9 +36,6 @@ class Langfuse(object):
def __init__(
self,
- public_key: str,
- secret_key: str,
- host: Optional[str] = None, | For backwards compatibility, I'd suggest to keep the constructor arguments (public, secret, host) and make them optional. This applies to the SDK and the langchain callback handler.
If set, constructor arguments then take precedence over environment variable. Removing the argument leads to unexpected behavior for existing users
If no envs are set and no constructor arguments, I'd suggest to log a warning. This can be intended behavior for some users to prevent Langfuse from tracing executions in some environments (eg CI). |
langfuse-python | github_2023 | python | 100 | langfuse | maxdeichmann | @@ -34,14 +35,17 @@ def __init__(
statefulTraceClient: Optional[StatefulTraceClient] = None,
release: Optional[str] = None,
) -> None:
+ public_key = public_key if public_key else os.environ.get("LF_PK")
+ secret_key = secret_key if secret_key else os.environ.get("LF_SK")
+
# If we're provided a stateful trace client directly
if statefulTraceClient:
self.trace = Run(statefulTraceClient, None)
self.runs = {}
# Otherwise, initialize stateless using the provided keys
elif public_key and secret_key:
- self.langfuse = Langfuse(public_key, secret_key, host, debug=debug, release=release)
+ self.langfuse = Langfuse(debug=debug, release=release) | Should we set the keys here? |
langfuse-python | github_2023 | python | 100 | langfuse | marcklingen | @@ -31,6 +32,9 @@ def __init__(
statefulClient: Optional[StatefulTraceClient | StatefulSpanClient] = None,
release: Optional[str] = None,
) -> None:
+ public_key = public_key if public_key else os.environ.get("LF_PK") | Environment variables will be checked in Langfuse client, no need to do this here again. I'd suggest to just pass public_key and secret_key to Langfuse() |
langfuse-python | github_2023 | python | 100 | langfuse | marcklingen | @@ -71,15 +71,19 @@ def __init__(
self.task_manager = TaskManager()
+ public_key = public_key if public_key else os.environ.get("LF_PK")
+ secret_key = secret_key if secret_key else os.environ.get("LF_SK")
+ host = host if host else os.environ.get("HOST")
+
self.base_url = host if host else "https://cloud.langfuse.com"
if not public_key:
self.log.warning("public_key is not set.")
- raise ValueError("public_key is required")
+ raise ValueError("public_key is required. Set it as os.environ[LF_PK]='public_key'") | This suggests that env var is the only option. I'd suggest `"public_key is required, set as parameter or environment variable "LF_PK""` |
langfuse-python | github_2023 | python | 100 | langfuse | marcklingen | @@ -71,15 +71,19 @@ def __init__(
self.task_manager = TaskManager()
+ public_key = public_key if public_key else os.environ.get("LF_PK")
+ secret_key = secret_key if secret_key else os.environ.get("LF_SK")
+ host = host if host else os.environ.get("HOST")
+
self.base_url = host if host else "https://cloud.langfuse.com"
if not public_key:
self.log.warning("public_key is not set.")
- raise ValueError("public_key is required")
+ raise ValueError("public_key is required. Set it as os.environ[LF_PK]='public_key'")
if not secret_key:
self.log.warning("secret_key is not set.")
- raise ValueError("secret_key is required")
+ raise ValueError("public_key is required. Set it as os.environ[LF_SK]='secret_key'") | typo, should be secret_key |
langfuse-python | github_2023 | python | 100 | langfuse | marcklingen | @@ -1,10 +1,13 @@
+import os
import requests
class LangfuseAPI:
- def __init__(self, username=None, password=None, base_url="http://localhost:3000"):
- self.auth = (username, password) if username and password else None
- self.BASE_URL = base_url
+ def __init__(self, username=None, password=None, base_url=None): | Is this necessary? I'd assume that we never create the LangfuseAPI directly but only via Langfuse() |
langfuse-python | github_2023 | python | 100 | langfuse | marcklingen | @@ -67,23 +73,28 @@ def test_flush():
def test_setup_wthout_pk():
# set up the consumer with more requests than a single batch will allow
+ os.environ.pop("LF_PK")
with pytest.raises(ValueError):
- Langfuse(public_key=None, secret_key=os.environ.get("LF_SK"))
+ Langfuse()
+ os.environ["LF_PK"] = "test"
+
def test_setup_wthout_sk():
# set up the consumer with more requests than a single batch will allow
+ os.environ.pop("LF_SK")
with pytest.raises(ValueError):
- Langfuse(public_key=os.environ.get("LF_PK"), secret_key=None)
+ Langfuse()
+ os.environ["LF_SK"] = "test"
def test_public_key_in_header(): | Great, also add separate tests for LF_SK and LF_HOST parameter. Goal is to check that overriding env in constructor works |
langfuse-python | github_2023 | others | 4 | langfuse | derino | @@ -0,0 +1,76 @@
+on:
+ pull_request:
+ push:
+ branches:
+ - main
+ - master
+ workflow_dispatch:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
+ cancel-in-progress: false
+
+jobs:
+ ci:
+ runs-on: ubuntu-latest
+ env: # Or as an environment variable
+ HOST: ${{ secrets.HOST }}
+ LF_PK: ${{ secrets.LF_PK }}
+ LF_SK: ${{ secrets.LF_SK }}
+ OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
+ SERPAPI_API_KEY: ${{ secrets.SERPAPI_API_KEY }}
+ strategy:
+ matrix:
+ python-version:
+ # - "3.5"
+ # - "3.6"
+ - "3.7"
+ - "3.8"
+ - "3.9"
+ - "3.10"
+ - "3.11"
+ - "pypy3.8"
+ - "pypy3.9"
+ name: Test on Python version ${{ matrix.python-version }}
+ steps:
+ - uses: actions/checkout@v3
+
+ - name: Install Python
+ uses: actions/setup-python@v4
+ # see details (matrix, python-version, python-version-file, etc.)
+ # https://github.com/actions/setup-python
+ with:
+ python-version: ${{ matrix.python-version }}
+
+ - name: Install poetry
+ uses: abatilo/actions-poetry@v2
+
+ - name: Setup a local virtual environment (if no poetry.toml file)
+ run: |
+ poetry config virtualenvs.create true --local
+ poetry config virtualenvs.in-project true --local
+
+ - uses: actions/cache@v3
+ name: Define a cache for the virtual environment based on the dependencies lock file
+ with:
+ path: ./.venv
+ key: venv-${{ hashFiles('poetry.lock') }}
+
+ - name: Install the project dependencies
+ run: poetry install
+
+ - name: Run the automated tests | @maxdeichmann The tests don't seem to be run on the python version that is set up:
https://github.com/langfuse/langfuse-python/actions/runs/6309393965/job/17129223793?pr=107#step:12:16 |
langfuse-python | github_2023 | python | 35 | langfuse | maxdeichmann | @@ -12,6 +12,7 @@
class UpdateSpanRequest(pydantic.BaseModel):
span_id: str = pydantic.Field(alias="spanId")
trace_id: typing.Optional[str] = pydantic.Field(alias="traceId")
+ name: typing.Optional[str] | Good catch! All files in langfuse/api are auto-generated by fern. Added a PR on the core project and will update this PR as well https://github.com/langfuse/langfuse/pull/101
By keeping the openapi docs in core in sync, we can also update the TS SDK accordingly. |
langfuse-python | github_2023 | python | 35 | langfuse | maxdeichmann | @@ -138,8 +139,7 @@ def create_trace():
def create_span():
try:
- new_body = body.copy(update={"id": new_span_id})
- new_body = body.copy(update={"trace_id": new_trace_id})
+ new_body = body.copy(update={"id": new_span_id, "trace_id": new_trace_id}) | good catch! |
langfuse-python | github_2023 | python | 35 | langfuse | maxdeichmann | @@ -179,8 +179,7 @@ def create_trace():
def create_generation():
try:
- new_body = body.copy(update={"id": new_generation_id})
- new_body = body.copy(update={"trace_id": new_trace_id})
+ new_body = body.copy(update={"id": new_generation_id, "trace_id": new_trace_id}) | same here! |
langfuse-python | github_2023 | python | 35 | langfuse | maxdeichmann | @@ -190,8 +189,8 @@ def create_generation():
self.log.exception(e)
raise e
- self.task_manager.add_task(new_generation_id, create_generation)
self.task_manager.add_task(new_trace_id, create_trace)
+ self.task_manager.add_task(new_generation_id, create_generation) | Ordering does not matter, but more logical to have it this way |
langfuse-python | github_2023 | python | 35 | langfuse | maxdeichmann | @@ -358,7 +357,7 @@ def update(self, body: UpdateGeneration):
def task():
try:
- new_body = body.copy(update={"generation_id": self.id})
+ new_body = body.copy(update={"generation_id": self.id, "trace_id": self.trace_id}) | Why this change? It does not destroy anything but did it not work without? |
langfuse-python | github_2023 | python | 35 | langfuse | maxdeichmann | @@ -424,3 +426,76 @@ def test_create_trace_with_id_and_generation():
span = trace["observations"][0]
assert span["name"] == "generation"
assert span["traceId"] == trace["id"]
+
+
+def test_end_generation():
+ langfuse = Langfuse(os.environ.get("LF_PK"), os.environ.get("LF_SK"), os.environ.get("HOST"))
+ api_wrapper = LangfuseAPI(os.environ.get("LF_PK"), os.environ.get("LF_SK"), os.environ.get("HOST"))
+
+ timestamp = datetime.now()
+ generation = langfuse.generation(
+ InitialGeneration(
+ name="query-generation",
+ startTime=timestamp,
+ model="gpt-3.5-turbo",
+ modelParameters={"maxTokens": "1000", "temperature": "0.9"},
+ prompt=[
+ {"role": "system", "content": "You are a helpful assistant."},
+ {
+ "role": "user",
+ "content": "Please generate the start of a company documentation that contains the answer to the questinon: Write a summary of the Q3 OKR goals",
+ },
+ ],
+ completion="This document entails the OKR goals for ACME",
+ usage=Usage(promptTokens=50, completionTokens=49),
+ metadata={"interface": "whatsapp"},
+ )
+ )
+
+ time.sleep(5)
+ end_time = datetime.now()
+ generation.end()
+
+ langfuse.flush()
+
+ assert len(langfuse.task_manager.result_mapping) == 3
+
+ trace_id = langfuse.get_trace_id()
+
+ trace = api_wrapper.get_trace(trace_id)
+
+ span = trace["observations"][0]
+ iso_format_end_time = end_time.astimezone(pytz.UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+ assert span["endTime"] == iso_format_end_time | Do you think these type of tests work reliably as they base on time? Maybe we should just check that the endtime is not null? |
langfuse-python | github_2023 | python | 35 | langfuse | maxdeichmann | @@ -401,6 +416,14 @@ def task():
except Exception as e:
self.log.exception(e)
+ def end(self):
+ try:
+ end_time = datetime.now()
+ self.update(UpdateGeneration(endTime=end_time)) | I missed this one here: i think we need to return this function here so that end() returns a stateful client (also above). Otherwise good for me. |
laravel-filament-flexible-content-blocks | github_2023 | others | 25 | statikbe | sten | @@ -68,6 +68,7 @@ Here is a brief overview of the choices made:
- `spatie/laravel-sluggable`: for slugs
- `spatie/laravel-translatable`: for translations as this works together with the first party filament translatable package.
- `dereuromark/media-embed`: to support video embeds of [various media services](https://github.com/dereuromark/media-embed/blob/master/docs/supported.md).
+- `artesaos/seotools`: this is a soft dependency, you can use a different package to handle the SEO fields output if you like. | There is no real dependency on this library. It is only used in the examples. So I do not like to include it. You can use whatever you want.
In the future, I am planning to implement support for additional fields for SEO metadata types, like articles, pages, how-to lists, etc. Maybe other libs are more useful for this and we will have to make a choice. For now, it is nowhere used in the actual library.
We can add in the section about the example that it depends on `artesaos/seotools` |
laravel-filament-flexible-content-blocks | github_2023 | others | 25 | statikbe | sten | @@ -38,6 +38,7 @@
],
"require": {
"php": "^8.1",
+ "artesaos/seotools": "^1.2", | Please, remove. See comment above. |
laravel-filament-flexible-content-blocks | github_2023 | php | 25 | statikbe | sten | @@ -0,0 +1,17 @@
+<?php
+
+namespace App\View\Components;
+
+use Illuminate\View\Component;
+use Illuminate\View\View;
+
+class baseLayour extends Component | Typo in class name: BaseLayout |
laravel-filament-flexible-content-blocks | github_2023 | php | 6 | statikbe | sten | @@ -134,9 +134,9 @@ public function getChildComponents(): array
TextInput::make(static::FIELD_BUTTON_LABEL)
->label(trans('filament-flexible-content-blocks::filament-flexible-content-blocks.form_component.content_blocks.call_to_action_button_label'))
->columnSpan(3),
- Checkbox::make(static::FIELD_BUTTON_OPEN_NEW_WINDOW)
+ Toggle::make(static::FIELD_BUTTON_OPEN_NEW_WINDOW)
->label(trans('filament-flexible-content-blocks::filament-flexible-content-blocks.form_component.content_blocks.call_to_action_button_open_in_new_window'))
- ->columnSpan(1),
+ ->columnSpan(1)->inline(false), | zet `->inline(false)` op een new line |
timefold-solver | github_2023 | java | 1,463 | TimefoldAI | zepfred | @@ -3,32 +3,52 @@
import java.util.IdentityHashMap;
import java.util.Map;
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.bavet.uni.AbstractForEachUniNode;
+import ai.timefold.solver.core.impl.bavet.uni.AbstractForEachUniNode.LifecycleOperation;
public abstract class AbstractSession {
private final NodeNetwork nodeNetwork;
- private final Map<Class<?>, AbstractForEachUniNode<Object>[]> effectiveClassToNodeArrayMap;
+ private final Map<Class<?>, AbstractForEachUniNode<Object, Object>[]> initializeEffectiveClassToNodeArrayMap; | Cool! |
timefold-solver | github_2023 | java | 1,463 | TimefoldAI | zepfred | @@ -3,32 +3,52 @@
import java.util.IdentityHashMap;
import java.util.Map;
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.bavet.uni.AbstractForEachUniNode;
+import ai.timefold.solver.core.impl.bavet.uni.AbstractForEachUniNode.LifecycleOperation;
public abstract class AbstractSession {
private final NodeNetwork nodeNetwork;
- private final Map<Class<?>, AbstractForEachUniNode<Object>[]> effectiveClassToNodeArrayMap;
+ private final Map<Class<?>, AbstractForEachUniNode<Object, Object>[]> initializeEffectiveClassToNodeArrayMap;
+ private final Map<Class<?>, AbstractForEachUniNode<Object, Object>[]> insertEffectiveClassToNodeArrayMap;
+ private final Map<Class<?>, AbstractForEachUniNode<Object, Object>[]> updateEffectiveClassToNodeArrayMap;
+ private final Map<Class<?>, AbstractForEachUniNode<Object, Object>[]> retractEffectiveClassToNodeArrayMap;
protected AbstractSession(NodeNetwork nodeNetwork) {
this.nodeNetwork = nodeNetwork;
- this.effectiveClassToNodeArrayMap = new IdentityHashMap<>(nodeNetwork.forEachNodeCount());
+ this.initializeEffectiveClassToNodeArrayMap = new IdentityHashMap<>(nodeNetwork.forEachNodeCount());
+ this.insertEffectiveClassToNodeArrayMap = new IdentityHashMap<>(nodeNetwork.forEachNodeCount());
+ this.updateEffectiveClassToNodeArrayMap = new IdentityHashMap<>(nodeNetwork.forEachNodeCount());
+ this.retractEffectiveClassToNodeArrayMap = new IdentityHashMap<>(nodeNetwork.forEachNodeCount());
+ }
+
+ public final void initialize(Object workingSolution) {
+ for (var node : findNodes(PlanningSolution.class, LifecycleOperation.INITIALIZE)) { | We are passing an annotation class here. I'm unsure how `nodeNetwork.getForEachNodes()` will locate the solution class. |
timefold-solver | github_2023 | java | 1,463 | TimefoldAI | zepfred | @@ -83,7 +80,7 @@ public UniDataStream<Solution_, A> addNull() {
throw new UnsupportedOperationException();
}
- public AbstractDataset<Solution_, UniTuple<A>> createDataset() {
+ public UniDataset<Solution_, A> createDataset() { | Should we avoid the use of specialized classes here? |
timefold-solver | github_2023 | java | 1,463 | TimefoldAI | zepfred | @@ -10,24 +9,23 @@
import ai.timefold.solver.core.api.score.stream.Joiners;
import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
-import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.DataStreamFactory;
-import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.SolutionExtractor;
+import ai.timefold.solver.core.impl.move.streams.FromSolutionValueCollectingFunction;
import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.UniDataStream;
-import org.jspecify.annotations.NonNull;
+import org.jspecify.annotations.NullMarked;
-public final class DefaultDataStreamFactory<Solution_> implements DataStreamFactory<Solution_> {
+@NullMarked
+public final class DataStreamFactory<Solution_> { | Should this class be abstract, or will there be no default implementation? |
timefold-solver | github_2023 | java | 1,463 | TimefoldAI | zepfred | @@ -12,48 +11,40 @@
import ai.timefold.solver.core.impl.bavet.uni.ForEachExcludingUnassignedUniNode;
import ai.timefold.solver.core.impl.bavet.uni.ForEachFromSolutionUniNode;
import ai.timefold.solver.core.impl.bavet.uni.ForEachIncludingUnassignedUniNode;
-import ai.timefold.solver.core.impl.bavet.uni.ForEachStaticUniNode;
+import ai.timefold.solver.core.impl.move.streams.FromSolutionValueCollectingFunction;
import ai.timefold.solver.core.impl.move.streams.dataset.common.DataNodeBuildHelper;
-import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.SolutionExtractor;
+import org.jspecify.annotations.NullMarked;
+import org.jspecify.annotations.Nullable;
+
+@NullMarked
public final class ForEachDataStream<Solution_, A>
extends AbstractUniDataStream<Solution_, A>
implements TupleSource {
private final Class<A> forEachClass;
- private final Predicate<A> filter;
- private final SolutionExtractor<Solution_, A> extractor;
- private final Collection<A> source;
+ private final @Nullable FromSolutionValueCollectingFunction<Solution_, A> valueCollectingFunction; | Why not to add specialized classes, one for the predicate and another for the FromSolutionValueCollectingFunction? |
timefold-solver | github_2023 | java | 1,463 | TimefoldAI | zepfred | @@ -0,0 +1,136 @@
+package ai.timefold.solver.core.impl.move.streams;
+
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.BiPredicate;
+
+import ai.timefold.solver.core.impl.bavet.common.tuple.UniTuple;
+import ai.timefold.solver.core.impl.move.streams.dataset.AbstractDataStream;
+import ai.timefold.solver.core.impl.move.streams.dataset.AbstractDataset;
+import ai.timefold.solver.core.impl.move.streams.dataset.DatasetInstance;
+import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.BiMoveConstructor;
+import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.MoveStreamSession;
+import ai.timefold.solver.core.preview.api.move.Move;
+
+import org.jspecify.annotations.NullMarked;
+import org.jspecify.annotations.Nullable;
+
+@NullMarked
+public final class BiMoveProducer<Solution_, A, B> implements InnerMoveProducer<Solution_> {
+
+ private final AbstractDataset<Solution_, UniTuple<A>> aDataset;
+ private final AbstractDataset<Solution_, UniTuple<B>> bDataset;
+ private final BiMoveConstructor<Solution_, A, B> moveConstructor;
+ private final BiPredicate<A, B> filter;
+
+ public BiMoveProducer(AbstractDataset<Solution_, UniTuple<A>> aDataset, AbstractDataset<Solution_, UniTuple<B>> bDataset,
+ BiPredicate<A, B> filter, BiMoveConstructor<Solution_, A, B> moveConstructor) {
+ this.aDataset = Objects.requireNonNull(aDataset);
+ this.bDataset = Objects.requireNonNull(bDataset);
+ this.filter = Objects.requireNonNull(filter);
+ this.moveConstructor = Objects.requireNonNull(moveConstructor);
+ }
+
+ @Override
+ public Iterable<Move<Solution_>> getMoveIterable(MoveStreamSession<Solution_> moveStreamSession) {
+ return new BiMoveIterable((DefaultMoveStreamSession<Solution_>) moveStreamSession);
+ }
+
+ @Override
+ public void collectActiveDataStreams(Set<AbstractDataStream<Solution_>> activeDataStreamSet) {
+ aDataset.collectActiveDataStreams(activeDataStreamSet);
+ bDataset.collectActiveDataStreams(activeDataStreamSet);
+ }
+
+ private final class BiMoveIterator implements Iterator<Move<Solution_>> { | Nice! |
timefold-solver | github_2023 | java | 1,463 | TimefoldAI | zepfred | @@ -81,11 +81,11 @@ public abstract class AbstractScoreDirector<Solution_, Score_ extends Score<Scor
private int workingInitScore = 0;
private String undoMoveText;
- // Null when tracking disabled
- private final boolean trackingWorkingSolution;
private final SolutionTracker<Solution_> solutionTracker;
private final MoveDirector<Solution_> moveDirector = new MoveDirector<>(this);
+ // Null when tracking disabled
+ private final boolean trackingWorkingSolution; | It cannot be null |
timefold-solver | github_2023 | java | 1,463 | TimefoldAI | zepfred | @@ -59,6 +59,7 @@ public BavetConstraintStreamScoreDirector(
@Override
public void setWorkingSolution(Solution_ workingSolution) {
session = scoreDirectorFactory.newSession(workingSolution, constraintMatchPolicy, derived);
+ session.initialize(workingSolution); | Is this necessary at this stage of the implementation? |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -0,0 +1,222 @@
+package ai.timefold.solver.core.impl.bavet.common;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+import ai.timefold.solver.core.impl.bavet.NodeNetwork;
+import ai.timefold.solver.core.impl.bavet.common.tuple.AbstractTuple;
+import ai.timefold.solver.core.impl.bavet.common.tuple.LeftTupleLifecycle;
+import ai.timefold.solver.core.impl.bavet.common.tuple.RightTupleLifecycle;
+import ai.timefold.solver.core.impl.bavet.common.tuple.TupleLifecycle;
+import ai.timefold.solver.core.impl.bavet.uni.AbstractForEachUniNode;
+import ai.timefold.solver.core.impl.score.stream.bavet.common.BavetStreamBinaryOperation;
+
+public abstract class AbstractNodeBuildHelper<Stream_ extends BavetStream> {
+
+ private final Set<Stream_> activeStreamSet;
+ private final Map<AbstractNode, Stream_> nodeCreatorMap;
+ private final Map<Stream_, TupleLifecycle<? extends AbstractTuple>> tupleLifecycleMap;
+ private final Map<Stream_, Integer> storeIndexMap;
+
+ private List<AbstractNode> reversedNodeList;
+
+ public AbstractNodeBuildHelper(Set<Stream_> activeStreamSet) {
+ this.activeStreamSet = activeStreamSet;
+ int activeStreamSetSize = activeStreamSet.size();
+ this.nodeCreatorMap = new HashMap<>(Math.max(16, activeStreamSetSize));
+ this.tupleLifecycleMap = new HashMap<>(Math.max(16, activeStreamSetSize));
+ this.storeIndexMap = new HashMap<>(Math.max(16, activeStreamSetSize / 2));
+ this.reversedNodeList = new ArrayList<>(activeStreamSetSize);
+ }
+
+ public boolean isStreamActive(Stream_ stream) {
+ return activeStreamSet.contains(stream);
+ }
+
+ public void addNode(AbstractNode node, Stream_ creator) {
+ addNode(node, creator, creator);
+ }
+
+ public void addNode(AbstractNode node, Stream_ creator, Stream_ parent) {
+ reversedNodeList.add(node);
+ nodeCreatorMap.put(node, creator);
+ if (!(node instanceof AbstractForEachUniNode<?>)) {
+ if (parent == null) {
+ throw new IllegalStateException("Impossible state: The node (" + node + ") has no parent (" + parent + ")."); | Let's use `String::format` |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -0,0 +1,222 @@
+package ai.timefold.solver.core.impl.bavet.common;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+import ai.timefold.solver.core.impl.bavet.NodeNetwork;
+import ai.timefold.solver.core.impl.bavet.common.tuple.AbstractTuple;
+import ai.timefold.solver.core.impl.bavet.common.tuple.LeftTupleLifecycle;
+import ai.timefold.solver.core.impl.bavet.common.tuple.RightTupleLifecycle;
+import ai.timefold.solver.core.impl.bavet.common.tuple.TupleLifecycle;
+import ai.timefold.solver.core.impl.bavet.uni.AbstractForEachUniNode;
+import ai.timefold.solver.core.impl.score.stream.bavet.common.BavetStreamBinaryOperation;
+
+public abstract class AbstractNodeBuildHelper<Stream_ extends BavetStream> {
+
+ private final Set<Stream_> activeStreamSet;
+ private final Map<AbstractNode, Stream_> nodeCreatorMap;
+ private final Map<Stream_, TupleLifecycle<? extends AbstractTuple>> tupleLifecycleMap;
+ private final Map<Stream_, Integer> storeIndexMap;
+
+ private List<AbstractNode> reversedNodeList;
+
+ public AbstractNodeBuildHelper(Set<Stream_> activeStreamSet) {
+ this.activeStreamSet = activeStreamSet;
+ int activeStreamSetSize = activeStreamSet.size();
+ this.nodeCreatorMap = new HashMap<>(Math.max(16, activeStreamSetSize));
+ this.tupleLifecycleMap = new HashMap<>(Math.max(16, activeStreamSetSize));
+ this.storeIndexMap = new HashMap<>(Math.max(16, activeStreamSetSize / 2));
+ this.reversedNodeList = new ArrayList<>(activeStreamSetSize);
+ }
+
+ public boolean isStreamActive(Stream_ stream) {
+ return activeStreamSet.contains(stream);
+ }
+
+ public void addNode(AbstractNode node, Stream_ creator) {
+ addNode(node, creator, creator);
+ }
+
+ public void addNode(AbstractNode node, Stream_ creator, Stream_ parent) {
+ reversedNodeList.add(node);
+ nodeCreatorMap.put(node, creator);
+ if (!(node instanceof AbstractForEachUniNode<?>)) {
+ if (parent == null) {
+ throw new IllegalStateException("Impossible state: The node (" + node + ") has no parent (" + parent + ").");
+ }
+ putInsertUpdateRetract(parent, (TupleLifecycle<? extends AbstractTuple>) node);
+ }
+ }
+
+ public void addNode(AbstractNode node, Stream_ creator, Stream_ leftParent, Stream_ rightParent) {
+ reversedNodeList.add(node);
+ nodeCreatorMap.put(node, creator);
+ putInsertUpdateRetract(leftParent, TupleLifecycle.ofLeft((LeftTupleLifecycle<? extends AbstractTuple>) node));
+ putInsertUpdateRetract(rightParent, TupleLifecycle.ofRight((RightTupleLifecycle<? extends AbstractTuple>) node));
+ }
+
+ public <Tuple_ extends AbstractTuple> void putInsertUpdateRetract(Stream_ stream,
+ TupleLifecycle<Tuple_> tupleLifecycle) {
+ tupleLifecycleMap.put(stream, tupleLifecycle);
+ }
+
+ public <Tuple_ extends AbstractTuple> void putInsertUpdateRetract(Stream_ stream, List<? extends Stream_> childStreamList,
+ Function<TupleLifecycle<Tuple_>, TupleLifecycle<Tuple_>> tupleLifecycleFunction) {
+ TupleLifecycle<Tuple_> tupleLifecycle = getAggregatedTupleLifecycle(childStreamList);
+ putInsertUpdateRetract(stream, tupleLifecycleFunction.apply(tupleLifecycle));
+ }
+
+ @SuppressWarnings("unchecked")
+ public <Tuple_ extends AbstractTuple> TupleLifecycle<Tuple_>
+ getAggregatedTupleLifecycle(List<? extends Stream_> streamList) {
+ var tupleLifecycles = streamList.stream()
+ .filter(this::isStreamActive)
+ .map(s -> getTupleLifecycle(s, tupleLifecycleMap))
+ .toArray(TupleLifecycle[]::new);
+ return switch (tupleLifecycles.length) {
+ case 0 ->
+ throw new IllegalStateException("Impossible state: None of the streamList (" + streamList + ") are active."); | Please apply the previous comment to all similar occurrences |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -0,0 +1,222 @@
+package ai.timefold.solver.core.impl.bavet.common;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+import ai.timefold.solver.core.impl.bavet.NodeNetwork;
+import ai.timefold.solver.core.impl.bavet.common.tuple.AbstractTuple;
+import ai.timefold.solver.core.impl.bavet.common.tuple.LeftTupleLifecycle;
+import ai.timefold.solver.core.impl.bavet.common.tuple.RightTupleLifecycle;
+import ai.timefold.solver.core.impl.bavet.common.tuple.TupleLifecycle;
+import ai.timefold.solver.core.impl.bavet.uni.AbstractForEachUniNode;
+import ai.timefold.solver.core.impl.score.stream.bavet.common.BavetStreamBinaryOperation;
+
+public abstract class AbstractNodeBuildHelper<Stream_ extends BavetStream> {
+
+ private final Set<Stream_> activeStreamSet;
+ private final Map<AbstractNode, Stream_> nodeCreatorMap;
+ private final Map<Stream_, TupleLifecycle<? extends AbstractTuple>> tupleLifecycleMap;
+ private final Map<Stream_, Integer> storeIndexMap;
+
+ private List<AbstractNode> reversedNodeList;
+
+ public AbstractNodeBuildHelper(Set<Stream_> activeStreamSet) {
+ this.activeStreamSet = activeStreamSet;
+ int activeStreamSetSize = activeStreamSet.size();
+ this.nodeCreatorMap = new HashMap<>(Math.max(16, activeStreamSetSize));
+ this.tupleLifecycleMap = new HashMap<>(Math.max(16, activeStreamSetSize));
+ this.storeIndexMap = new HashMap<>(Math.max(16, activeStreamSetSize / 2));
+ this.reversedNodeList = new ArrayList<>(activeStreamSetSize);
+ }
+
+ public boolean isStreamActive(Stream_ stream) {
+ return activeStreamSet.contains(stream);
+ }
+
+ public void addNode(AbstractNode node, Stream_ creator) {
+ addNode(node, creator, creator);
+ }
+
+ public void addNode(AbstractNode node, Stream_ creator, Stream_ parent) {
+ reversedNodeList.add(node);
+ nodeCreatorMap.put(node, creator);
+ if (!(node instanceof AbstractForEachUniNode<?>)) {
+ if (parent == null) {
+ throw new IllegalStateException("Impossible state: The node (" + node + ") has no parent (" + parent + ").");
+ }
+ putInsertUpdateRetract(parent, (TupleLifecycle<? extends AbstractTuple>) node);
+ }
+ }
+
+ public void addNode(AbstractNode node, Stream_ creator, Stream_ leftParent, Stream_ rightParent) {
+ reversedNodeList.add(node);
+ nodeCreatorMap.put(node, creator);
+ putInsertUpdateRetract(leftParent, TupleLifecycle.ofLeft((LeftTupleLifecycle<? extends AbstractTuple>) node));
+ putInsertUpdateRetract(rightParent, TupleLifecycle.ofRight((RightTupleLifecycle<? extends AbstractTuple>) node));
+ }
+
+ public <Tuple_ extends AbstractTuple> void putInsertUpdateRetract(Stream_ stream,
+ TupleLifecycle<Tuple_> tupleLifecycle) {
+ tupleLifecycleMap.put(stream, tupleLifecycle);
+ }
+
+ public <Tuple_ extends AbstractTuple> void putInsertUpdateRetract(Stream_ stream, List<? extends Stream_> childStreamList,
+ Function<TupleLifecycle<Tuple_>, TupleLifecycle<Tuple_>> tupleLifecycleFunction) {
+ TupleLifecycle<Tuple_> tupleLifecycle = getAggregatedTupleLifecycle(childStreamList);
+ putInsertUpdateRetract(stream, tupleLifecycleFunction.apply(tupleLifecycle));
+ }
+
+ @SuppressWarnings("unchecked")
+ public <Tuple_ extends AbstractTuple> TupleLifecycle<Tuple_>
+ getAggregatedTupleLifecycle(List<? extends Stream_> streamList) {
+ var tupleLifecycles = streamList.stream()
+ .filter(this::isStreamActive)
+ .map(s -> getTupleLifecycle(s, tupleLifecycleMap))
+ .toArray(TupleLifecycle[]::new);
+ return switch (tupleLifecycles.length) {
+ case 0 ->
+ throw new IllegalStateException("Impossible state: None of the streamList (" + streamList + ") are active.");
+ case 1 -> tupleLifecycles[0];
+ default -> TupleLifecycle.aggregate(tupleLifecycles);
+ };
+ }
+
+ @SuppressWarnings("unchecked")
+ private static <Stream_, Tuple_ extends AbstractTuple> TupleLifecycle<Tuple_> getTupleLifecycle(Stream_ stream,
+ Map<Stream_, TupleLifecycle<? extends AbstractTuple>> tupleLifecycleMap) {
+ var tupleLifecycle = (TupleLifecycle<Tuple_>) tupleLifecycleMap.get(stream);
+ if (tupleLifecycle == null) {
+ throw new IllegalStateException("Impossible state: the stream (" + stream + ") hasn't built a node yet.");
+ }
+ return tupleLifecycle;
+ }
+
+ public int reserveTupleStoreIndex(Stream_ tupleSourceStream) {
+ return storeIndexMap.compute(tupleSourceStream, (k, index) -> {
+ if (index == null) {
+ return 0;
+ } else if (index < 0) {
+ throw new IllegalStateException("Impossible state: the tupleSourceStream (" + k
+ + ") is reserving a store after it has been extracted.");
+ } else {
+ return index + 1;
+ }
+ });
+ }
+
+ public int extractTupleStoreSize(Stream_ tupleSourceStream) {
+ Integer lastIndex = storeIndexMap.put(tupleSourceStream, Integer.MIN_VALUE); | Should it be zero instead of Integer.MIN_VALUE? |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -26,22 +26,23 @@ public void insert(A a) {
@Override
public void update(A a) {
- UniTuple<A> tuple = tupleMap.get(a);
+ var tuple = tupleMap.get(a);
if (tuple == null) { // The tuple was never inserted because it did not pass the filter.
insert(a);
} else if (filter.test(a)) {
- innerUpdate(a, tuple);
- } else {
- super.retract(a); // Call super.retract() to avoid testing the filter again.
+ updateExisting(a, tuple);
+ } else { // Tuple no longer passes the filter.
+ retract(a);
}
}
@Override
public void retract(A a) {
- if (!filter.test(a)) { // The tuple was never inserted because it did not pass the filter.
+ var tuple = tupleMap.remove(a); | Why we don't need to filter before removing? |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -26,22 +26,23 @@ public void insert(A a) {
@Override
public void update(A a) {
- UniTuple<A> tuple = tupleMap.get(a);
+ var tuple = tupleMap.get(a);
if (tuple == null) { // The tuple was never inserted because it did not pass the filter.
insert(a);
} else if (filter.test(a)) {
- innerUpdate(a, tuple);
- } else {
- super.retract(a); // Call super.retract() to avoid testing the filter again.
+ updateExisting(a, tuple);
+ } else { // Tuple no longer passes the filter.
+ retract(a);
}
}
@Override
public void retract(A a) {
- if (!filter.test(a)) { // The tuple was never inserted because it did not pass the filter.
+ var tuple = tupleMap.remove(a);
+ if (tuple == null) { // The tuple was never inserted because it did not pass the filter. | The comment is inconsistent |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -3,20 +3,21 @@
import ai.timefold.solver.core.impl.bavet.common.tuple.TupleLifecycle;
import ai.timefold.solver.core.impl.bavet.common.tuple.UniTuple;
-public final class ForEachIncludingUnassignedUniNode<A> extends AbstractForEachUniNode<A> {
+public sealed class ForEachUniNode<A> | Since I don't have deep knowledge of the ConstraintStream ecosystem, I'm missing comments on the node classes that briefly describe their roles. |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -29,23 +30,27 @@ public int layerCount() {
return layeredNodes.length;
}
- @SuppressWarnings("unchecked")
- public AbstractForEachUniNode<Object>[] getApplicableForEachNodes(Class<?> factClass) {
+ public Stream<AbstractForEachUniNode<?>> getForEachNodes() {
+ return declaredClassToNodeMap.values()
+ .stream()
+ .flatMap(List::stream);
+ }
+
+ public Stream<AbstractForEachUniNode<?>> getForEachNodes(Class<?> factClass) {
return declaredClassToNodeMap.entrySet()
.stream()
.filter(entry -> entry.getKey().isAssignableFrom(factClass))
.map(Map.Entry::getValue)
- .flatMap(List::stream)
- .toArray(AbstractForEachUniNode[]::new);
+ .flatMap(List::stream);
}
- public void propagate() {
+ public void settle() { | Propagate seems to be a common term used in CS. I'm unsure if the method name change is good idea. |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -134,4 +166,8 @@ public VariableDescriptorAwareScoreDirector<Solution_> getScoreDirector() {
return scoreDirector;
}
+ public void resetWorkingSolution(Solution_ workingSolution) { | Please add a comment about why we are adding an empty method |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -0,0 +1,46 @@
+package ai.timefold.solver.core.impl.move.streams.dataset.common.bridge;
+
+import java.util.Objects;
+
+import ai.timefold.solver.core.impl.bavet.common.TupleSource;
+import ai.timefold.solver.core.impl.move.streams.dataset.AbstractDataStream;
+import ai.timefold.solver.core.impl.move.streams.dataset.AbstractUniDataStream;
+import ai.timefold.solver.core.impl.move.streams.dataset.DefaultDataStreamFactory;
+import ai.timefold.solver.core.impl.move.streams.dataset.common.DataNodeBuildHelper;
+
+public final class AftBridgeUniDataStream<Solution_, A> | What is the meaning of Aft? |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -0,0 +1,46 @@
+package ai.timefold.solver.core.impl.move.streams.dataset.common.bridge;
+
+import java.util.Objects;
+
+import ai.timefold.solver.core.impl.bavet.common.TupleSource;
+import ai.timefold.solver.core.impl.move.streams.dataset.AbstractDataStream;
+import ai.timefold.solver.core.impl.move.streams.dataset.AbstractUniDataStream;
+import ai.timefold.solver.core.impl.move.streams.dataset.DefaultDataStreamFactory;
+import ai.timefold.solver.core.impl.move.streams.dataset.common.DataNodeBuildHelper;
+
+public final class AftBridgeUniDataStream<Solution_, A>
+ extends AbstractUniDataStream<Solution_, A>
+ implements TupleSource {
+
+ public AftBridgeUniDataStream(DefaultDataStreamFactory<Solution_> dataStreamFactory, AbstractDataStream<Solution_> parent) {
+ super(dataStreamFactory, parent);
+ }
+
+ @Override
+ public void buildNode(DataNodeBuildHelper<Solution_> buildHelper) {
+ // Do nothing. The parent stream builds everything.
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ AftBridgeUniDataStream<?, ?> that = (AftBridgeUniDataStream<?, ?>) o; | ```suggestion
var that = (AftBridgeUniDataStream<?, ?>) o;
``` |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -0,0 +1,76 @@
+package ai.timefold.solver.core.impl.move.streams.dataset;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import ai.timefold.solver.core.impl.bavet.common.BavetStream;
+import ai.timefold.solver.core.impl.bavet.common.TupleSource;
+import ai.timefold.solver.core.impl.move.streams.dataset.common.DataNodeBuildHelper;
+
+public abstract class AbstractDataStream<Solution_>
+ implements BavetStream {
+
+ protected final DefaultDataStreamFactory<Solution_> dataStreamFactory;
+ protected final AbstractDataStream<Solution_> parent;
+ protected final List<AbstractDataStream<Solution_>> childStreamList = new ArrayList<>(2);
+
+ protected AbstractDataStream(DefaultDataStreamFactory<Solution_> dataStreamFactory, AbstractDataStream<Solution_> parent) {
+ this.dataStreamFactory = dataStreamFactory;
+ this.parent = parent;
+ }
+
+ public final <Stream_ extends AbstractDataStream<Solution_>> Stream_ shareAndAddChild(Stream_ stream) {
+ return dataStreamFactory.share(stream, childStreamList::add);
+ }
+
+ // ************************************************************************
+ // Node creation
+ // ************************************************************************
+
+ public void collectActiveDataStreams(Set<AbstractDataStream<Solution_>> constraintStreamSet) {
+ if (parent == null) { // Maybe a join/ifExists/forEach forgot to override this?
+ throw new IllegalStateException("Impossible state: the stream (" + this + ") does not have a parent."); | Let's use `String::format` in all similar occurrences |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -0,0 +1,76 @@
+package ai.timefold.solver.core.impl.move.streams.dataset;
+
+import java.util.Collections;
+import java.util.IdentityHashMap;
+import java.util.Map;
+import java.util.Objects;
+
+import ai.timefold.solver.core.impl.bavet.AbstractSession;
+import ai.timefold.solver.core.impl.bavet.NodeNetwork;
+import ai.timefold.solver.core.impl.bavet.common.tuple.AbstractTuple;
+import ai.timefold.solver.core.impl.bavet.uni.ForEachFromSolutionUniNode;
+import ai.timefold.solver.core.impl.bavet.uni.ForEachStaticUniNode;
+import ai.timefold.solver.core.preview.api.move.SolutionView;
+
+public final class DatasetSession<Solution_> extends AbstractSession {
+
+ private final ForEachStaticUniNode<Object>[] effectiveClassToStaticNodeArray;
+ private final ForEachFromSolutionUniNode<Solution_, Object>[] effectiveClassToFromSolutionNodeArray;
+ private final Map<AbstractDataset<Solution_, ?>, DatasetInstance<Solution_, ?>> datasetInstanceMap =
+ new IdentityHashMap<>();
+
+ @SuppressWarnings("unchecked")
+ DatasetSession(NodeNetwork nodeNetwork) {
+ super(nodeNetwork);
+ var staticNodeSet = Collections.newSetFromMap(new IdentityHashMap<ForEachStaticUniNode<?>, Boolean>());
+ var fromSolutionNodeSet = Collections.newSetFromMap(new IdentityHashMap<ForEachFromSolutionUniNode<?, ?>, Boolean>());
+ nodeNetwork.getForEachNodes().forEach(node -> {
+ if (node instanceof ForEachStaticUniNode<?> forEachStaticUniNode) {
+ staticNodeSet.add(forEachStaticUniNode);
+ } else if (node instanceof ForEachFromSolutionUniNode<?, ?> forEachFromSolutionUniNode) {
+ fromSolutionNodeSet.add(forEachFromSolutionUniNode);
+ }
+ });
+ this.effectiveClassToStaticNodeArray =
+ staticNodeSet.isEmpty() ? null : staticNodeSet.toArray(ForEachStaticUniNode[]::new);
+ this.effectiveClassToFromSolutionNodeArray =
+ fromSolutionNodeSet.isEmpty() ? null : fromSolutionNodeSet.toArray(ForEachFromSolutionUniNode[]::new);
+ }
+
+ public void registerDatasetInstance(AbstractDataset<Solution_, ?> dataset, DatasetInstance<Solution_, ?> datasetInstance) {
+ var oldDatasetInstance = datasetInstanceMap.put(dataset, datasetInstance);
+ if (oldDatasetInstance != null) {
+ throw new IllegalStateException("The dataset (%s) has already been registered with session (%s)."
+ .formatted(dataset, this));
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public <Out_ extends AbstractTuple> DatasetInstance<Solution_, Out_> getInstance(AbstractDataset<Solution_, Out_> dataset) {
+ return (DatasetInstance<Solution_, Out_>) Objects.requireNonNull(datasetInstanceMap.get(dataset));
+ }
+
+ public void initialize() {
+ if (effectiveClassToStaticNodeArray == null) {
+ return;
+ }
+ for (var node : effectiveClassToStaticNodeArray) {
+ node.initialize();
+ }
+ }
+
+ public void updateWorkingSolution(SolutionView<Solution_> solutionView, Solution_ solution) {
+ if (effectiveClassToFromSolutionNodeArray == null) {
+ return;
+ }
+ for (var node : effectiveClassToFromSolutionNodeArray) {
+ node.read(solutionView, solution);
+ }
+ }
+
+ @Override
+ public void settle() { | Why are we overriding it? |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -0,0 +1,64 @@
+package ai.timefold.solver.core.impl.move.streams.dataset;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.function.Consumer;
+
+import ai.timefold.solver.core.impl.bavet.NodeNetwork;
+import ai.timefold.solver.core.impl.bavet.common.AbstractNodeBuildHelper;
+import ai.timefold.solver.core.impl.bavet.uni.AbstractForEachUniNode;
+import ai.timefold.solver.core.impl.move.streams.dataset.common.DataNodeBuildHelper;
+
+public final class DatasetSessionFactory<Solution_> {
+
+ private final DefaultDataStreamFactory<Solution_> dataStreamFactory;
+
+ public DatasetSessionFactory(DefaultDataStreamFactory<Solution_> dataStreamFactory) {
+ this.dataStreamFactory = dataStreamFactory;
+ }
+
+ public DatasetSession<Solution_> buildSession() {
+ var activeDataStreamSet = new LinkedHashSet<AbstractDataStream<Solution_>>();
+ var datasets = dataStreamFactory.getDatasets();
+ for (var dataset : datasets) {
+ dataset.collectActiveDataStreams(activeDataStreamSet); | I wonder if we should change the logic to return the list of active datasets. This way, we wouldn't need to pass activeDatasetStreamSet as a parameter. |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -0,0 +1,147 @@
+package ai.timefold.solver.core.impl.move.streams.dataset;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import ai.timefold.solver.core.api.score.stream.Joiners;
+import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
+import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.DataStreamFactory;
+import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.SolutionExtractor;
+import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.UniDataStream;
+
+import org.jspecify.annotations.NonNull;
+
+public final class DefaultDataStreamFactory<Solution_> implements DataStreamFactory<Solution_> {
+
+ private final SolutionDescriptor<Solution_> solutionDescriptor;
+ private final Map<AbstractDataStream<Solution_>, AbstractDataStream<Solution_>> sharingStreamMap = new HashMap<>(256);
+
+ public DefaultDataStreamFactory(SolutionDescriptor<Solution_> solutionDescriptor) {
+ this.solutionDescriptor = solutionDescriptor;
+ }
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ @Override
+ public <A> @NonNull UniDataStream<Solution_, A> forEach(@NonNull Class<A> sourceClass) {
+ assertValidForEachType(sourceClass);
+ var entityDescriptor = solutionDescriptor.findEntityDescriptor(sourceClass);
+ if (entityDescriptor == null) {
+ // Not genuine or shadow entity; no need for filtering.
+ return share(new ForEachDataStream<>(this, sourceClass));
+ }
+ var listVariableDescriptor = solutionDescriptor.getListVariableDescriptor();
+ if (listVariableDescriptor == null || !listVariableDescriptor.acceptsValueType(sourceClass)) {
+ // No applicable list variable; don't need to check inverse relationships.
+ return share(new ForEachDataStream<>(this, sourceClass, entityDescriptor.getHasNoNullVariablesPredicateBasicVar()));
+ }
+ var entityClass = listVariableDescriptor.getEntityDescriptor().getEntityClass();
+ if (entityClass == sourceClass) {
+ throw new IllegalStateException("Impossible state: entityClass (%s) and sourceClass (%s) are the same."
+ .formatted(entityClass.getCanonicalName(), sourceClass.getCanonicalName()));
+ }
+ var shadowDescriptor = listVariableDescriptor.getInverseRelationShadowVariableDescriptor();
+ if (shadowDescriptor == null) {
+ // The list variable element doesn't have the @InverseRelationShadowVariable annotation.
+ // We don't want the users to be forced to implement it in quickstarts,
+ // so we'll do this expensive thing instead.
+ return forEachIncludingUnassigned(sourceClass)
+ .ifExists((Class) entityClass,
+ Joiners.filtering(listVariableDescriptor.getInListPredicate()));
+ } else { // We have the inverse relation variable, so we can read its value directly.
+ return share(new ForEachDataStream<>(this, sourceClass, entityDescriptor.getHasNoNullVariablesPredicateListVar()));
+ }
+ }
+
+ public <A> UniDataStream<Solution_, A> forEachIncludingUnassigned(@NonNull Class<A> sourceClass) {
+ assertValidForEachType(sourceClass);
+ return share(new ForEachDataStream<>(this, sourceClass));
+ }
+
+ public <A> void assertValidForEachType(Class<A> fromType) {
+ SolutionDescriptor<Solution_> solutionDescriptor = getSolutionDescriptor();
+ Set<Class<?>> problemFactOrEntityClassSet = solutionDescriptor.getProblemFactOrEntityClassSet();
+ /*
+ * Need to support the following situations:
+ * 1/ FactType == FromType; querying for the declared type.
+ * 2/ FromType extends/implements FactType; querying for impl type where declared type is its interface.
+ * 3/ FromType super FactType; querying for interface where declared type is its implementation.
+ */
+ boolean hasMatchingType = problemFactOrEntityClassSet.stream()
+ .anyMatch(factType -> fromType.isAssignableFrom(factType) || factType.isAssignableFrom(fromType));
+ if (!hasMatchingType) {
+ List<String> canonicalClassNameList = problemFactOrEntityClassSet.stream()
+ .map(Class::getCanonicalName)
+ .sorted()
+ .toList();
+ throw new IllegalArgumentException("Cannot use class (" + fromType.getCanonicalName() | Let's use `String::format` |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -0,0 +1,52 @@
+package ai.timefold.solver.core.impl.move.streams.dataset;
+
+import java.util.Objects;
+import java.util.function.Predicate;
+
+import ai.timefold.solver.core.impl.bavet.common.tuple.TupleLifecycle;
+import ai.timefold.solver.core.impl.bavet.common.tuple.UniTuple;
+import ai.timefold.solver.core.impl.move.streams.dataset.common.DataNodeBuildHelper;
+
+final class FilterUniDataStream<Solution_, A>
+ extends AbstractUniDataStream<Solution_, A> {
+
+ private final Predicate<A> predicate;
+
+ public FilterUniDataStream(DefaultDataStreamFactory<Solution_> dataStreamFactory,
+ AbstractUniDataStream<Solution_, A> parent, Predicate<A> predicate) {
+ super(dataStreamFactory, parent);
+ this.predicate = predicate; | ```suggestion
this.predicate = Objects.requireNonNull(predicate, "The predicate (null) cannot be null.");
``` |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -0,0 +1,115 @@
+package ai.timefold.solver.core.impl.move.streams.dataset;
+
+import java.util.Collection;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Predicate;
+
+import ai.timefold.solver.core.impl.bavet.common.TupleSource;
+import ai.timefold.solver.core.impl.bavet.common.tuple.TupleLifecycle;
+import ai.timefold.solver.core.impl.bavet.common.tuple.UniTuple;
+import ai.timefold.solver.core.impl.bavet.uni.AbstractForEachUniNode;
+import ai.timefold.solver.core.impl.bavet.uni.ForEachExcludingUnassignedUniNode;
+import ai.timefold.solver.core.impl.bavet.uni.ForEachFromSolutionUniNode;
+import ai.timefold.solver.core.impl.bavet.uni.ForEachStaticUniNode;
+import ai.timefold.solver.core.impl.bavet.uni.ForEachUniNode;
+import ai.timefold.solver.core.impl.move.streams.dataset.common.DataNodeBuildHelper;
+import ai.timefold.solver.core.impl.move.streams.maybeapi.stream.SolutionExtractor;
+
+public final class ForEachDataStream<Solution_, A>
+ extends AbstractUniDataStream<Solution_, A>
+ implements TupleSource {
+
+ private final Class<A> forEachClass;
+ private final Predicate<A> filter;
+ private final SolutionExtractor<Solution_, A> extractor;
+ private final Collection<A> source;
+
+ public ForEachDataStream(DefaultDataStreamFactory<Solution_> dataStreamFactory, Class<A> forEachClass) {
+ this(dataStreamFactory, forEachClass, (Predicate<A>) null);
+ }
+
+ public ForEachDataStream(DefaultDataStreamFactory<Solution_> dataStreamFactory, Class<A> forEachClass,
+ Predicate<A> filter) {
+ super(dataStreamFactory, null);
+ this.forEachClass = forEachClass; | We are using `Objects::requireNonNull` in some places and in others not. |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -0,0 +1,112 @@
+package ai.timefold.solver.core.impl.move.streams.dataset;
+
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.BiPredicate;
+
+import ai.timefold.solver.core.impl.bavet.bi.joiner.DefaultBiJoiner;
+import ai.timefold.solver.core.impl.bavet.common.BavetAbstractConstraintStream;
+import ai.timefold.solver.core.impl.bavet.common.index.IndexerFactory;
+import ai.timefold.solver.core.impl.bavet.common.tuple.TupleLifecycle;
+import ai.timefold.solver.core.impl.bavet.common.tuple.UniTuple;
+import ai.timefold.solver.core.impl.bavet.uni.IndexedIfExistsUniNode;
+import ai.timefold.solver.core.impl.bavet.uni.UnindexedIfExistsUniNode;
+import ai.timefold.solver.core.impl.move.streams.dataset.common.BavetIfExistsDataStream;
+import ai.timefold.solver.core.impl.move.streams.dataset.common.DataNodeBuildHelper;
+import ai.timefold.solver.core.impl.move.streams.dataset.common.bridge.ForeBridgeUniDataStream;
+
+final class IfExistsUniDataStream<Solution_, A, B>
+ extends AbstractUniDataStream<Solution_, A>
+ implements BavetIfExistsDataStream<Solution_> {
+
+ private final AbstractUniDataStream<Solution_, A> parentA;
+ private final ForeBridgeUniDataStream<Solution_, B> parentBridgeB;
+ private final boolean shouldExist;
+ private final DefaultBiJoiner<A, B> joiner;
+ private final BiPredicate<A, B> filtering;
+
+ public IfExistsUniDataStream(DefaultDataStreamFactory<Solution_> dataStreamFactory,
+ AbstractUniDataStream<Solution_, A> parentA, ForeBridgeUniDataStream<Solution_, B> parentBridgeB,
+ boolean shouldExist, DefaultBiJoiner<A, B> joiner, BiPredicate<A, B> filtering) {
+ super(dataStreamFactory);
+ this.parentA = parentA;
+ this.parentBridgeB = parentBridgeB;
+ this.shouldExist = shouldExist;
+ this.joiner = joiner;
+ this.filtering = filtering;
+ }
+
+ @Override
+ public void collectActiveDataStreams(Set<AbstractDataStream<Solution_>> dataStreamSet) {
+ parentA.collectActiveDataStreams(dataStreamSet);
+ parentBridgeB.collectActiveDataStreams(dataStreamSet);
+ dataStreamSet.add(this);
+ }
+
+ @Override
+ public void buildNode(DataNodeBuildHelper<Solution_> buildHelper) {
+ TupleLifecycle<UniTuple<A>> downstream = buildHelper.getAggregatedTupleLifecycle(childStreamList);
+ var indexerFactory = new IndexerFactory<>(joiner);
+ var node = indexerFactory.hasJoiners() | I would use an if block instead of a ternary operator |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -0,0 +1,178 @@
+package ai.timefold.solver.core.impl.move.streams.generic;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
+import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningListVariableMetaModel;
+import ai.timefold.solver.core.preview.api.domain.metamodel.VariableMetaModel;
+import ai.timefold.solver.core.preview.api.move.MutableSolutionView;
+import ai.timefold.solver.core.preview.api.move.Rebaser;
+
+import org.jspecify.annotations.NonNull;
+
+/** | The class is very well-documented. I missed these types of comments in the other move classes and data stream classes. |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -0,0 +1,8 @@
+package ai.timefold.solver.core.impl.score.stream.bavet.common; | I wonder if these stream classes should be part of the package ` ai.timefold.solver.core.impl.bavet.common` |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -71,7 +71,8 @@ public <Stream_ extends BavetAbstractConstraintStream<Solution_>> Stream_ share(
* {@link BavetAbstractConstraintStream} implement equals/hashcode ignoring child streams.
* <p>
* {@link BavetConstraintSessionFactory#buildSession(Object, ConstraintMatchPolicy, boolean, Consumer)} needs this to happen
- * for all streams.
+ * for all | Please adjust the comment |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -0,0 +1,107 @@
+package ai.timefold.solver.core.impl.move.streams.dataset;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import ai.timefold.solver.core.impl.domain.solution.descriptor.DefaultPlanningListVariableMetaModel;
+import ai.timefold.solver.core.impl.domain.solution.descriptor.DefaultPlanningVariableMetaModel;
+import ai.timefold.solver.core.impl.testdata.domain.list.TestdataListEntity;
+import ai.timefold.solver.core.impl.testdata.domain.list.TestdataListSolution;
+import ai.timefold.solver.core.preview.api.domain.metamodel.ElementLocation;
+import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningListVariableMetaModel;
+import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningVariableMetaModel;
+import ai.timefold.solver.core.preview.api.move.SolutionView;
+
+import org.jspecify.annotations.NullMarked;
+import org.jspecify.annotations.Nullable;
+import org.junit.jupiter.api.Test;
+
+class UniDatasetStreamTest {
+
+ @Test
+ void forEach() {
+ var dataStreamFactory = new DefaultDataStreamFactory<>(TestdataListSolution.buildSolutionDescriptor());
+ var uniDataset = ((AbstractUniDataStream<TestdataListSolution, TestdataListEntity>) dataStreamFactory
+ .forEach(TestdataListEntity.class))
+ .createDataset();
+
+ var solution = TestdataListSolution.generateInitializedSolution(2, 2);
+ var datasetSession = createSession(dataStreamFactory, solution);
+ var uniDatasetInstance = datasetSession.getInstance(uniDataset);
+
+ var entity1 = solution.getEntityList().get(0);
+ var entity2 = solution.getEntityList().get(1);
+
+ assertThat(uniDatasetInstance.iterator())
+ .toIterable()
+ .map(t -> t.factA)
+ .containsExactly(entity1, entity2);
+
+ // Make incremental changes.
+ var entity3 = new TestdataListEntity("entity3");
+ datasetSession.insert(entity3);
+ datasetSession.retract(entity2);
+ datasetSession.settle();
+
+ assertThat(uniDatasetInstance.iterator())
+ .toIterable()
+ .map(t -> t.factA)
+ .containsExactly(entity1, entity3);
+ }
+
+ private DatasetSession<TestdataListSolution> createSession(DefaultDataStreamFactory<TestdataListSolution> dataStreamFactory,
+ TestdataListSolution solution) {
+ var datasetSessionFactory = new DatasetSessionFactory<>(dataStreamFactory);
+ var datasetSession = datasetSessionFactory.buildSession();
+ var solutionView = new TestdataListSolutionView(solution);
+ datasetSession.initialize();
+ datasetSession.updateWorkingSolution(solutionView, solution);
+
+ var solutionDescriptor = dataStreamFactory.getSolutionDescriptor();
+ solutionDescriptor.visitAll(solution, datasetSession::insert);
+
+ datasetSession.settle();
+ return datasetSession;
+ }
+
+ @NullMarked
+ private record TestdataListSolutionView(TestdataListSolution solution) implements SolutionView<TestdataListSolution> { | We might use this class in other places and will need to make it available to the different classes. |
timefold-solver | github_2023 | java | 1,349 | TimefoldAI | zepfred | @@ -0,0 +1,107 @@
+package ai.timefold.solver.core.impl.move.streams.dataset;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import ai.timefold.solver.core.impl.domain.solution.descriptor.DefaultPlanningListVariableMetaModel;
+import ai.timefold.solver.core.impl.domain.solution.descriptor.DefaultPlanningVariableMetaModel;
+import ai.timefold.solver.core.impl.testdata.domain.list.TestdataListEntity;
+import ai.timefold.solver.core.impl.testdata.domain.list.TestdataListSolution;
+import ai.timefold.solver.core.preview.api.domain.metamodel.ElementLocation;
+import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningListVariableMetaModel;
+import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningVariableMetaModel;
+import ai.timefold.solver.core.preview.api.move.SolutionView;
+
+import org.jspecify.annotations.NullMarked;
+import org.jspecify.annotations.Nullable;
+import org.junit.jupiter.api.Test;
+
+class UniDatasetStreamTest {
+
+ @Test
+ void forEach() { | Nice! |
timefold-solver | github_2023 | java | 1,454 | TimefoldAI | winklerm | @@ -500,6 +501,53 @@ void compareWithConstraintMatchesAndMatchAnalysis() {
});
}
+ @Test
+ void compareMatchCountsWithDifferentFetchPolicies() {
+ var constraintPackage = "constraintPackage";
+ var constraintName1 = "constraint1";
+ var constraintName2 = "constraint2";
+ var constraintName3 = "constraint3";
+ var constraintId1 = ConstraintRef.of(constraintPackage, constraintName1);
+ var constraintId2 = ConstraintRef.of(constraintPackage, constraintName2);
+ var constraintId3 = ConstraintRef.of(constraintPackage, constraintName3);
+
+ var constraintMatchTotal1 = new DefaultConstraintMatchTotal<>(constraintId1, SimpleScore.of(1));
+ addConstraintMatch(constraintMatchTotal1, SimpleScore.of(2), "A", "B", "C");
+ addConstraintMatch(constraintMatchTotal1, SimpleScore.of(4), "A", "B");
+ addConstraintMatch(constraintMatchTotal1, SimpleScore.of(6), "B", "C");
+ addConstraintMatch(constraintMatchTotal1, SimpleScore.of(8));
+ var constraintMatchTotal2 = new DefaultConstraintMatchTotal<>(constraintId2, SimpleScore.of(3));
+ addConstraintMatch(constraintMatchTotal2, SimpleScore.of(3), "B", "C", "D");
+ addConstraintMatch(constraintMatchTotal2, SimpleScore.of(6), "B", "C");
+ addConstraintMatch(constraintMatchTotal2, SimpleScore.of(9), "C", "D");
+ addConstraintMatch(constraintMatchTotal2, SimpleScore.of(12));
+ var emptyConstraintMatchTotal1 = new DefaultConstraintMatchTotal<>(constraintId3, SimpleScore.of(0));
+
+ var constraintAnalysisMap1 = Map.of(
+ constraintMatchTotal1.getConstraintRef(), getConstraintAnalysis(constraintMatchTotal1, FETCH_MATCH_COUNT),
+ constraintMatchTotal2.getConstraintRef(), getConstraintAnalysis(constraintMatchTotal2, FETCH_MATCH_COUNT),
+ emptyConstraintMatchTotal1.getConstraintRef(),
+ getConstraintAnalysis(emptyConstraintMatchTotal1, FETCH_MATCH_COUNT));
+ var scoreAnalysis1 = new ScoreAnalysis<>(SimpleScore.of(50), constraintAnalysisMap1);
+
+ var constraintAnalysisMap2 = Map.of(
+ constraintMatchTotal1.getConstraintRef(), getConstraintAnalysis(constraintMatchTotal1, FETCH_MATCH_COUNT), | Q: Should `constraintAnalysisMap2` use `FETCH_ALL` for all entries? Or is the mixing of policies intentional? |
timefold-solver | github_2023 | others | 1,437 | TimefoldAI | TomCools | @@ -27,7 +27,7 @@ Gradle::
--
[source,shell,subs=attributes+]
----
-curl https://timefold.ai/product/upgrade/upgrade-timefold.gradle > upgrade-timefold.gradle ; gradle -Dorg.gradle.jvmargs=-Xmx2G --init-script upgrade-timefold.gradle rewriteRun -DtimefoldSolverVersion={timefold-solver-version} ; rm upgrade-timefold.gradle
+curl https://raw.githubusercontent.com/TimefoldAI/timefold-solver/refs/tags/v{timefold-solver-version}/migration/upgrade-timefold.gradle > upgrade-timefold.gradle ; gradle -Dorg.gradle.jvmargs=-Xmx2G --init-script upgrade-timefold.gradle rewriteRun -DtimefoldSolverVersion={timefold-solver-version} ; rm upgrade-timefold.gradle | This doesn't work for me.
example gives 404, because `upgrade-timefold.gradle` doesn't exist?
https://raw.githubusercontent.com/TimefoldAI/timefold-solver/refs/tags/v1.19.0/migration/upgrade-timefold.gradle |
timefold-solver | github_2023 | others | 1,437 | TimefoldAI | TomCools | @@ -33,7 +33,7 @@ Gradle::
--
[source,shell,subs=attributes+]
----
-curl https://timefold.ai/product/upgrade/upgrade-timefold.gradle > upgrade-timefold.gradle ; gradle -Dorg.gradle.jvmargs=-Xmx2G --init-script upgrade-timefold.gradle rewriteRun -DtimefoldSolverVersion={timefold-solver-version} ; rm upgrade-timefold.gradle
+curl https://raw.githubusercontent.com/TimefoldAI/timefold-solver/refs/tags/v{timefold-solver-version}/migration/upgrade-timefold.gradle > upgrade-timefold.gradle ; gradle -Dorg.gradle.jvmargs=-Xmx2G --init-script upgrade-timefold.gradle rewriteRun -DtimefoldSolverVersion={timefold-solver-version} ; rm upgrade-timefold.gradle | Ditto other comment |
timefold-solver | github_2023 | others | 1,437 | TimefoldAI | TomCools | @@ -140,22 +140,51 @@ Some solver configurations use the `Random` instance a lot more than others.
For example, Simulated Annealing depends highly on random numbers, while Tabu Search only depends on it to deal with score ties.
The environment mode influences the seed of that `Random` instance.
-These are the environment modes:
+[#environmentModeReproducibility]
+=== Reproducibility
+For the environment mode to be reproducible,
+any two runs of the same dataset with the same solver configuration will must have the same result at every step. | ```suggestion
any two runs of the same dataset with the same solver configuration must have the same result at every step.
``` |
timefold-solver | github_2023 | others | 1,437 | TimefoldAI | TomCools | @@ -180,76 +209,78 @@ Any variable that changed between the "before move" solution and the "after move
Any variable that changed between the "after move" solution and "after undo move" solution without either a
`beforeVariableChanged` or `afterVariableChanged` would be reported here.
-This mode is <<environmentModeReproducible,reproducible>> (see the reproducible mode).
+This mode is <<environmentModeReproducibility,reproducible>> (see the reproducible mode).
It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode.
The `TRACKED_FULL_ASSERT` mode is by far the slowest mode,
because it clones solutions before and after each move.
+[#environmentModeFullAssert]
+==== `FULL_ASSERT`
+
+The `FULL_ASSERT` mode turns on all assertions (such as assert that the incremental score calculation is uncorrupted for each move) to fail-fast on a bug in a Move implementation, a constraint, the engine itself, ... | ```suggestion
The `FULL_ASSERT` mode turns on all assertions and will fail-fast on a bug in a Move implementation, a constraint, the engine itself, ...
```
I think the extra explainer is not needed and makes the sentence harder to read. |
timefold-solver | github_2023 | others | 1,437 | TimefoldAI | TomCools | @@ -180,76 +209,78 @@ Any variable that changed between the "before move" solution and the "after move
Any variable that changed between the "after move" solution and "after undo move" solution without either a
`beforeVariableChanged` or `afterVariableChanged` would be reported here.
-This mode is <<environmentModeReproducible,reproducible>> (see the reproducible mode).
+This mode is <<environmentModeReproducibility,reproducible>> (see the reproducible mode).
It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode.
The `TRACKED_FULL_ASSERT` mode is by far the slowest mode,
because it clones solutions before and after each move.
+[#environmentModeFullAssert]
+==== `FULL_ASSERT`
+
+The `FULL_ASSERT` mode turns on all assertions (such as assert that the incremental score calculation is uncorrupted for each move) to fail-fast on a bug in a Move implementation, a constraint, the engine itself, ...
+
+This mode is <<environmentModeReproducibility,reproducible>>.
+It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode. | ```suggestion
It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode, making the `FULL_ASSERT` mode very slow.
``` |
timefold-solver | github_2023 | others | 1,437 | TimefoldAI | TomCools | @@ -180,76 +209,78 @@ Any variable that changed between the "before move" solution and the "after move
Any variable that changed between the "after move" solution and "after undo move" solution without either a
`beforeVariableChanged` or `afterVariableChanged` would be reported here.
-This mode is <<environmentModeReproducible,reproducible>> (see the reproducible mode).
+This mode is <<environmentModeReproducibility,reproducible>> (see the reproducible mode).
It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode.
The `TRACKED_FULL_ASSERT` mode is by far the slowest mode,
because it clones solutions before and after each move.
+[#environmentModeFullAssert]
+==== `FULL_ASSERT`
+
+The `FULL_ASSERT` mode turns on all assertions (such as assert that the incremental score calculation is uncorrupted for each move) to fail-fast on a bug in a Move implementation, a constraint, the engine itself, ...
+
+This mode is <<environmentModeReproducibility,reproducible>>.
+It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode.
+
+The `FULL_ASSERT` mode is horribly slow, | Remove these 2 with the suggestions above. |
timefold-solver | github_2023 | others | 1,437 | TimefoldAI | TomCools | @@ -180,76 +209,78 @@ Any variable that changed between the "before move" solution and the "after move
Any variable that changed between the "after move" solution and "after undo move" solution without either a
`beforeVariableChanged` or `afterVariableChanged` would be reported here.
-This mode is <<environmentModeReproducible,reproducible>> (see the reproducible mode).
+This mode is <<environmentModeReproducibility,reproducible>> (see the reproducible mode).
It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode.
The `TRACKED_FULL_ASSERT` mode is by far the slowest mode,
because it clones solutions before and after each move.
+[#environmentModeFullAssert]
+==== `FULL_ASSERT`
+
+The `FULL_ASSERT` mode turns on all assertions (such as assert that the incremental score calculation is uncorrupted for each move) to fail-fast on a bug in a Move implementation, a constraint, the engine itself, ...
+
+This mode is <<environmentModeReproducibility,reproducible>>.
+It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode.
+
+The `FULL_ASSERT` mode is horribly slow,
+because it does not rely on incremental score calculation.
+
+
[#environmentModeNonIntrusiveFullAssert]
-=== `NON_INTRUSIVE_FULL_ASSERT`
+==== `NON_INTRUSIVE_FULL_ASSERT`
The `NON_INTRUSIVE_FULL_ASSERT` turns on several assertions to fail-fast on a bug in a Move implementation,
a constraint, the engine itself, ...
-This mode is <<environmentModeReproducible,reproducible>>.
+This mode is <<environmentModeReproducibility,reproducible>>.
It is non-intrusive because it does not call the method `calculateScore()` more frequently than a non-assert mode.
The `NON_INTRUSIVE_FULL_ASSERT` mode is horribly slow,
because it does not rely on incremental score calculation.
[#environmentModeStepAssert]
-=== `STEP_ASSERT`
+==== `STEP_ASSERT`
The `STEP_ASSERT` mode turns on most assertions (such as assert that an undoMove's score is the same as before the Move)
to fail-fast on a bug in a Move implementation, a constraint, the engine itself, ...
+This makes it slow.
-This mode is <<environmentModeReproducible,reproducible>>.
+This mode is <<environmentModeReproducibility,reproducible>>.
It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode.
-The `STEP_ASSERT` mode is slow.
-
-It is recommended to write a test case that does a short run of your planning problem with the `STEP_ASSERT` mode on.
+We recommend that you write a test case that does a short run of your planning problem with the `STEP_ASSERT` mode on. | Should this be a TIP to make it stand out?
|
timefold-solver | github_2023 | others | 1,437 | TimefoldAI | TomCools | @@ -180,76 +209,78 @@ Any variable that changed between the "before move" solution and the "after move
Any variable that changed between the "after move" solution and "after undo move" solution without either a
`beforeVariableChanged` or `afterVariableChanged` would be reported here.
-This mode is <<environmentModeReproducible,reproducible>> (see the reproducible mode).
+This mode is <<environmentModeReproducibility,reproducible>> (see the reproducible mode).
It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode.
The `TRACKED_FULL_ASSERT` mode is by far the slowest mode,
because it clones solutions before and after each move.
+[#environmentModeFullAssert]
+==== `FULL_ASSERT`
+
+The `FULL_ASSERT` mode turns on all assertions (such as assert that the incremental score calculation is uncorrupted for each move) to fail-fast on a bug in a Move implementation, a constraint, the engine itself, ...
+
+This mode is <<environmentModeReproducibility,reproducible>>.
+It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode.
+
+The `FULL_ASSERT` mode is horribly slow,
+because it does not rely on incremental score calculation.
+
+
[#environmentModeNonIntrusiveFullAssert]
-=== `NON_INTRUSIVE_FULL_ASSERT`
+==== `NON_INTRUSIVE_FULL_ASSERT`
The `NON_INTRUSIVE_FULL_ASSERT` turns on several assertions to fail-fast on a bug in a Move implementation, | Do we have a list of the assertions somewhere? Because "ALL" (FULL_ASSERT) and "several" (NONE_INTRUSIVE_FULL_ASSERT) isn't very telling.
Side note: having to say we only activate "several assertions" for NONE_INTRUSIVE_FULL_ASSERT is a bit weird. (But probably legacy?) |
timefold-solver | github_2023 | others | 1,437 | TimefoldAI | TomCools | @@ -180,76 +209,78 @@ Any variable that changed between the "before move" solution and the "after move
Any variable that changed between the "after move" solution and "after undo move" solution without either a
`beforeVariableChanged` or `afterVariableChanged` would be reported here.
-This mode is <<environmentModeReproducible,reproducible>> (see the reproducible mode).
+This mode is <<environmentModeReproducibility,reproducible>> (see the reproducible mode).
It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode.
The `TRACKED_FULL_ASSERT` mode is by far the slowest mode,
because it clones solutions before and after each move.
+[#environmentModeFullAssert]
+==== `FULL_ASSERT`
+
+The `FULL_ASSERT` mode turns on all assertions (such as assert that the incremental score calculation is uncorrupted for each move) to fail-fast on a bug in a Move implementation, a constraint, the engine itself, ...
+
+This mode is <<environmentModeReproducibility,reproducible>>.
+It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode.
+
+The `FULL_ASSERT` mode is horribly slow,
+because it does not rely on incremental score calculation.
+
+
[#environmentModeNonIntrusiveFullAssert]
-=== `NON_INTRUSIVE_FULL_ASSERT`
+==== `NON_INTRUSIVE_FULL_ASSERT`
The `NON_INTRUSIVE_FULL_ASSERT` turns on several assertions to fail-fast on a bug in a Move implementation,
a constraint, the engine itself, ...
-This mode is <<environmentModeReproducible,reproducible>>.
+This mode is <<environmentModeReproducibility,reproducible>>.
It is non-intrusive because it does not call the method `calculateScore()` more frequently than a non-assert mode.
The `NON_INTRUSIVE_FULL_ASSERT` mode is horribly slow,
because it does not rely on incremental score calculation.
[#environmentModeStepAssert]
-=== `STEP_ASSERT`
+==== `STEP_ASSERT`
The `STEP_ASSERT` mode turns on most assertions (such as assert that an undoMove's score is the same as before the Move)
to fail-fast on a bug in a Move implementation, a constraint, the engine itself, ...
+This makes it slow.
-This mode is <<environmentModeReproducible,reproducible>>.
+This mode is <<environmentModeReproducibility,reproducible>>.
It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode.
-The `STEP_ASSERT` mode is slow.
-
-It is recommended to write a test case that does a short run of your planning problem with the `STEP_ASSERT` mode on.
+We recommend that you write a test case that does a short run of your planning problem with the `STEP_ASSERT` mode on.
[#environmentModePhaseAssert]
-=== `PHASE_ASSERT` (default)
+==== `PHASE_ASSERT` (default)
The `PHASE_ASSERT` is the default mode because it is recommended during development.
-In this mode, two runs in the same Timefold Solver version will execute the same code in the same order.
-**Those two runs will have the same result at every step**, except if the note below applies.
-This enables you to reproduce bugs consistently.
-It also allows you to benchmark certain refactorings (such as a score constraint performance optimization) fairly across runs.
+This mode is <<environmentModeReproducibility,reproducible>>
+and is negligibly slower than the `NO_ASSERT` mode.
+However, it gives you the benefit of quickly checking for score corruptions.
+If you can guarantee that your code is and will remain bug-free,
+you can switch to the `NO_ASSERT` mode for a marginal performance gain.
-[NOTE]
-====
-Despite the reproducible mode, your application might still not be fully reproducible because of:
+In practice, this mode uses the default, fixed <<randomNumberGenerator,random seed>> if no seed is specified, | Since Seeds aren't really mentioned clearly before, I wouldn't introduce the concept here. |
timefold-solver | github_2023 | others | 1,437 | TimefoldAI | TomCools | @@ -180,76 +209,78 @@ Any variable that changed between the "before move" solution and the "after move
Any variable that changed between the "after move" solution and "after undo move" solution without either a
`beforeVariableChanged` or `afterVariableChanged` would be reported here.
-This mode is <<environmentModeReproducible,reproducible>> (see the reproducible mode).
+This mode is <<environmentModeReproducibility,reproducible>> (see the reproducible mode).
It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode.
The `TRACKED_FULL_ASSERT` mode is by far the slowest mode,
because it clones solutions before and after each move.
+[#environmentModeFullAssert]
+==== `FULL_ASSERT`
+
+The `FULL_ASSERT` mode turns on all assertions (such as assert that the incremental score calculation is uncorrupted for each move) to fail-fast on a bug in a Move implementation, a constraint, the engine itself, ...
+
+This mode is <<environmentModeReproducibility,reproducible>>.
+It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode.
+
+The `FULL_ASSERT` mode is horribly slow,
+because it does not rely on incremental score calculation.
+
+
[#environmentModeNonIntrusiveFullAssert]
-=== `NON_INTRUSIVE_FULL_ASSERT`
+==== `NON_INTRUSIVE_FULL_ASSERT`
The `NON_INTRUSIVE_FULL_ASSERT` turns on several assertions to fail-fast on a bug in a Move implementation,
a constraint, the engine itself, ...
-This mode is <<environmentModeReproducible,reproducible>>.
+This mode is <<environmentModeReproducibility,reproducible>>.
It is non-intrusive because it does not call the method `calculateScore()` more frequently than a non-assert mode.
The `NON_INTRUSIVE_FULL_ASSERT` mode is horribly slow,
because it does not rely on incremental score calculation.
[#environmentModeStepAssert]
-=== `STEP_ASSERT`
+==== `STEP_ASSERT`
The `STEP_ASSERT` mode turns on most assertions (such as assert that an undoMove's score is the same as before the Move)
to fail-fast on a bug in a Move implementation, a constraint, the engine itself, ...
+This makes it slow.
-This mode is <<environmentModeReproducible,reproducible>>.
+This mode is <<environmentModeReproducibility,reproducible>>.
It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode.
-The `STEP_ASSERT` mode is slow.
-
-It is recommended to write a test case that does a short run of your planning problem with the `STEP_ASSERT` mode on.
+We recommend that you write a test case that does a short run of your planning problem with the `STEP_ASSERT` mode on.
[#environmentModePhaseAssert]
-=== `PHASE_ASSERT` (default)
+==== `PHASE_ASSERT` (default)
The `PHASE_ASSERT` is the default mode because it is recommended during development.
-In this mode, two runs in the same Timefold Solver version will execute the same code in the same order.
-**Those two runs will have the same result at every step**, except if the note below applies.
-This enables you to reproduce bugs consistently.
-It also allows you to benchmark certain refactorings (such as a score constraint performance optimization) fairly across runs.
+This mode is <<environmentModeReproducibility,reproducible>>
+and is negligibly slower than the `NO_ASSERT` mode.
+However, it gives you the benefit of quickly checking for score corruptions.
+If you can guarantee that your code is and will remain bug-free,
+you can switch to the `NO_ASSERT` mode for a marginal performance gain.
-[NOTE]
-====
-Despite the reproducible mode, your application might still not be fully reproducible because of:
+In practice, this mode uses the default, fixed <<randomNumberGenerator,random seed>> if no seed is specified,
+and it also disables certain concurrency optimizations, such as work stealing. | I am a bit surprised, if it is only "negligibly slower", I would not expect it to disable concurrency optimizations (that sounds bigger than just negligible to the untrained eye). |
timefold-solver | github_2023 | java | 1,431 | TimefoldAI | Christopher-Chianelli | @@ -297,6 +297,10 @@ public TerminationConfig withTerminationClass(Class<? extends Termination> termi
return this;
}
+ public @NonNull TerminationConfig withDiminishedReturnsConfig() { | My understanding is this method is to use Diminished Returns with the default configuration? Maybe `withDefaultDiminishedReturnsConfig()`? `withDiminishedReturnsConfig()` looks odd to me without an argument. |
timefold-solver | github_2023 | java | 1,431 | TimefoldAI | Christopher-Chianelli | @@ -88,18 +92,32 @@ public boolean isAssertShadowVariablesAreNotStaleAfterStep() {
@Override
public void solvingStarted(SolverScope<Solution_> solverScope) {
- phaseTermination.solvingStarted(solverScope);
phaseLifecycleSupport.fireSolvingStarted(solverScope);
}
@Override
public void solvingEnded(SolverScope<Solution_> solverScope) {
- phaseTermination.solvingEnded(solverScope);
phaseLifecycleSupport.fireSolvingEnded(solverScope);
}
@Override
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
+ if (!solver.isTerminationSameAsSolverTermination(phaseTermination)) {
+ // Only fail if the user put the inapplicable termination on the phase, not on the solver.
+ // On the solver level, inapplicable phase terminations are skipped.
+ // Otherwise you would only be able to configure a global phase-level termination on the solver
+ // if it was applicable to all phases.
+ var unsupportedTerminationList = phaseTermination instanceof UniversalTermination<Solution_> universalTermination
+ ? universalTermination.getPhasesTerminationsInapplicableTo(phaseScope)
+ : Collections.emptyList();
+ if (!unsupportedTerminationList.isEmpty()) { | Can we fail fast when the solver is being built? This will fail during solving. |
timefold-solver | github_2023 | java | 1,431 | TimefoldAI | Christopher-Chianelli | @@ -40,26 +41,30 @@ public abstract class AbstractSolver<Solution_> implements Solver<Solution_> {
protected final BestSolutionRecaller<Solution_> bestSolutionRecaller;
// Note that the DefaultSolver.basicPlumbingTermination is a component of this termination.
// Called "solverTermination" to clearly distinguish from "phaseTermination" inside AbstractPhase.
- protected final Termination<Solution_> solverTermination;
+ protected final UniversalTermination<Solution_> solverTermination; | Maybe rename field to `universalTermination`? Since there is a class called `SolverTermination` now. |
timefold-solver | github_2023 | java | 1,431 | TimefoldAI | Christopher-Chianelli | @@ -3,89 +3,110 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import java.util.Objects;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
+import org.jspecify.annotations.NullMarked;
+
/**
* Abstract superclass that combines multiple {@link Termination}s.
*
* @see AndCompositeTermination
* @see OrCompositeTermination
*/
-public abstract sealed class AbstractCompositeTermination<Solution_>
- extends AbstractTermination<Solution_>
+@NullMarked
+abstract sealed class AbstractCompositeTermination<Solution_>
+ extends AbstractUniversalTermination<Solution_>
permits AndCompositeTermination, OrCompositeTermination {
protected final List<Termination<Solution_>> terminationList;
+ protected final List<PhaseTermination<Solution_>> phaseTerminationList;
+ protected final List<SolverTermination<Solution_>> solverTerminationList;
protected AbstractCompositeTermination(List<Termination<Solution_>> terminationList) {
- this.terminationList = terminationList;
+ this.terminationList = Objects.requireNonNull(terminationList);
+ this.phaseTerminationList = terminationList.stream()
+ .filter(PhaseTermination.class::isInstance)
+ .map(t -> (PhaseTermination<Solution_>) t)
+ .toList();
+ this.solverTerminationList = terminationList.stream()
+ .filter(SolverTermination.class::isInstance)
+ .map(t -> (SolverTermination<Solution_>) t)
+ .toList();
}
+ @SafeVarargs
public AbstractCompositeTermination(Termination<Solution_>... terminations) {
this(Arrays.asList(terminations));
}
- // ************************************************************************
- // Lifecycle methods
- // ************************************************************************
-
@Override
- public void solvingStarted(SolverScope<Solution_> solverScope) {
- for (Termination<Solution_> termination : terminationList) {
+ public final void solvingStarted(SolverScope<Solution_> solverScope) {
+ for (var termination : solverTerminationList) {
termination.solvingStarted(solverScope);
}
}
@Override
- public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
- for (Termination<Solution_> termination : terminationList) {
+ public final void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
+ for (var termination : phaseTerminationList) {
termination.phaseStarted(phaseScope);
}
}
@Override
- public void stepStarted(AbstractStepScope<Solution_> stepScope) {
- for (Termination<Solution_> termination : terminationList) {
+ public final void stepStarted(AbstractStepScope<Solution_> stepScope) {
+ for (var termination : phaseTerminationList) { | The `step` methods do not get called for the solver terminations? How does the solver terminations get updated then? |
timefold-solver | github_2023 | java | 1,431 | TimefoldAI | Christopher-Chianelli | @@ -3,89 +3,110 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import java.util.Objects;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
+import org.jspecify.annotations.NullMarked;
+
/**
* Abstract superclass that combines multiple {@link Termination}s.
*
* @see AndCompositeTermination
* @see OrCompositeTermination
*/
-public abstract sealed class AbstractCompositeTermination<Solution_>
- extends AbstractTermination<Solution_>
+@NullMarked
+abstract sealed class AbstractCompositeTermination<Solution_>
+ extends AbstractUniversalTermination<Solution_>
permits AndCompositeTermination, OrCompositeTermination {
protected final List<Termination<Solution_>> terminationList;
+ protected final List<PhaseTermination<Solution_>> phaseTerminationList;
+ protected final List<SolverTermination<Solution_>> solverTerminationList;
protected AbstractCompositeTermination(List<Termination<Solution_>> terminationList) {
- this.terminationList = terminationList;
+ this.terminationList = Objects.requireNonNull(terminationList);
+ this.phaseTerminationList = terminationList.stream() | What happens to universal terminations? Do they get put in both lists? |
timefold-solver | github_2023 | java | 1,431 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,132 @@
+package ai.timefold.solver.core.impl.solver;
+
+import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore;
+import ai.timefold.solver.core.api.solver.SolverFactory;
+import ai.timefold.solver.core.config.constructionheuristic.ConstructionHeuristicPhaseConfig;
+import ai.timefold.solver.core.config.solver.SolverConfig;
+import ai.timefold.solver.core.config.solver.termination.DiminishedReturnsTerminationConfig;
+import ai.timefold.solver.core.config.solver.termination.TerminationConfig;
+import ai.timefold.solver.core.impl.testdata.domain.TestdataEasyScoreCalculator;
+import ai.timefold.solver.core.impl.testdata.domain.TestdataEntity;
+import ai.timefold.solver.core.impl.testdata.domain.TestdataSolution;
+
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class DefaultSolverTerminationTest {
+
+ @Test
+ void stepCountTerminationAtSolverLevel() {
+ var solverConfig = new SolverConfig()
+ .withSolutionClass(TestdataSolution.class)
+ .withEntityClasses(TestdataEntity.class)
+ .withEasyScoreCalculatorClass(TestdataEasyScoreCalculator.class)
+ .withPhases(new ConstructionHeuristicPhaseConfig())
+ .withTerminationConfig(new TerminationConfig()
+ .withStepCountLimit(1));
+ var solution = TestdataSolution.generateSolution(2, 2);
+ solution.getEntityList().forEach(entity -> entity.setValue(null)); // Uninitialize.
+ var solver = SolverFactory.<TestdataSolution> create(solverConfig)
+ .buildSolver();
+ var bestSolution = solver.solve(solution);
+ // 2 entities means 2 steps, but the step count limit is 1.
+ // Therefore the best solution is uninitialized.
+ Assertions.assertThat(bestSolution.getScore()).isEqualTo(SimpleScore.ofUninitialized(-1, 0));
+ }
+
+ @Test
+ void stepCountTerminationAtPhaseLevel() {
+ var solverConfig = new SolverConfig()
+ .withSolutionClass(TestdataSolution.class)
+ .withEntityClasses(TestdataEntity.class)
+ .withEasyScoreCalculatorClass(TestdataEasyScoreCalculator.class)
+ .withPhases(new ConstructionHeuristicPhaseConfig()
+ .withTerminationConfig(new TerminationConfig()
+ .withStepCountLimit(1)));
+ var solution = TestdataSolution.generateSolution(2, 2);
+ solution.getEntityList().forEach(entity -> entity.setValue(null)); // Uninitialize.
+ var solver = SolverFactory.<TestdataSolution> create(solverConfig)
+ .buildSolver();
+ var bestSolution = solver.solve(solution);
+ // 2 entities means 2 steps, but the step count limit is 1.
+ // Therefore the best solution is uninitialized.
+ Assertions.assertThat(bestSolution.getScore()).isEqualTo(SimpleScore.ofUninitialized(-1, 0));
+ }
+
+ @Test
+ void diminishedReturnsTerminationAtSolverLevel() {
+ var solverConfig = new SolverConfig()
+ .withSolutionClass(TestdataSolution.class)
+ .withEntityClasses(TestdataEntity.class)
+ .withEasyScoreCalculatorClass(TestdataEasyScoreCalculator.class)
+ .withPhases(new ConstructionHeuristicPhaseConfig())
+ .withTerminationConfig(new TerminationConfig()
+ .withDiminishedReturnsConfig(new DiminishedReturnsTerminationConfig()));
+ var solution = TestdataSolution.generateSolution(2, 2);
+ solution.getEntityList().forEach(entity -> entity.setValue(null)); // Uninitialize.
+ var solver = SolverFactory.<TestdataSolution> create(solverConfig)
+ .buildSolver();
+ var bestSolution = solver.solve(solution);
+ // 2 entities means 2 steps, but the step count limit is 1.
+ // Therefore the best solution is uninitialized. | Outdated comment; no step count termination is set. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.