Skip to content

Commit

Permalink
Catch all exceptions with re-raise
Browse files Browse the repository at this point in the history
  • Loading branch information
thatnerdjosh committed May 22, 2024
1 parent 8bb0eac commit 65290c1
Showing 1 changed file with 35 additions and 44 deletions.
79 changes: 35 additions & 44 deletions lunary/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@

event_queue_ctx = ContextVar("event_queue_ctx")
event_queue_ctx.set(EventQueue())
queue = event_queue_ctx.get()
queue = event_queue_ctx.get()

provider = TracerProvider()
trace.set_tracer_provider(provider)
Expand Down Expand Up @@ -85,14 +85,14 @@ def track_event(
):
try:
config = get_config()
app_id = app_id or config.app_id
app_id = app_id or config.app_id

if not app_id:
return warnings.warn("LUNARY_PUBLIC_KEY is not set, not sending events")

run_ctx.set(run_id) # done before run_id transformation because the context will be used to pass the id in track_event, so run_id will be transformed again
parent_run_id = get_parent_run_id(parent_run_id, run_type, app_id=app_id, run_id=run_id, is_openai=is_openai)
run_id = str(create_uuid_from_string(str(run_id) + str(app_id))) # We need to generate a UUID that is unique by run_id / project_id pair in case of multiple concurrent callback handler use
run_ctx.set(run_id) # done before run_id transformation because the context will be used to pass the id in track_event, so run_id will be transformed again
parent_run_id = get_parent_run_id(parent_run_id, run_type, app_id=app_id, run_id=run_id, is_openai=is_openai)
run_id = str(create_uuid_from_string(str(run_id) + str(app_id))) # We need to generate a UUID that is unique by run_id / project_id pair in case of multiple concurrent callback handler use

event = {
"event": event_name,
Expand All @@ -103,7 +103,7 @@ def track_event(
"tags": tags or tags_ctx.get(),
"threadTags": thread_tags,
"runId": run_id,
"parentRunId": parent_run_id,
"parentRunId": parent_run_id,
"timestamp": timestamp or datetime.now(timezone.utc).isoformat(),
"message": message,
"input": input,
Expand All @@ -127,13 +127,10 @@ def track_event(
if config.verbose:
event_copy = clean_nones(copy.deepcopy(event))
logger.info(f"\nAdd event: {jsonpickle.encode(event_copy, unpicklable=False, indent=4)}\n")

except Exception as e:
logger.exception("Error in `track_event`", e)




def handle_internal_error(e):
logger.info("Error: ", e)

Expand Down Expand Up @@ -631,7 +628,7 @@ def decorator(fn):
import requests
from langchain_core.agents import AgentFinish
from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.messages import BaseMessage, BaseMessageChunk
from langchain_core.messages import BaseMessage, BaseMessageChunk
from langchain_core.documents import Document
from langchain_core.outputs import LLMResult
from langchain_core.load import dumps
Expand Down Expand Up @@ -694,7 +691,7 @@ def identify(user_id: str, user_props: Any = None) -> UserContextManager:
def _serialize(data: Any):
if not data:
return None

if hasattr(data, 'messages'):
return _serialize(data.messages)
if isinstance(data, BaseMessage) or isinstance(data, BaseMessageChunk):
Expand All @@ -719,7 +716,7 @@ def _parse_input(raw_input: Any) -> Any:

return serialized



def _parse_output(raw_output: dict) -> Any:
serialized = _serialize(raw_output)
Expand Down Expand Up @@ -820,8 +817,8 @@ def __init__(

except ImportError:
logger.warning(
"""To use the Lunary callback handler you need to
have the `lunary` Python package installed. Please install it
"""To use the Lunary callback handler you need to
have the `lunary` Python package installed. Please install it
with `pip install lunary`"""
)
self.__has_valid_config = False
Expand All @@ -839,15 +836,15 @@ def __init__(
self.__has_valid_config = True


self.__app_id = app_id or config.app_id
self.__app_id = app_id or config.app_id
if self.__app_id is None:
logger.warning(
"""app_id must be provided either as an argument or
"""app_id must be provided either as an argument or
as an environment variable"""
)
self.__has_valid_config = False
self.queue = queue

self.queue = queue

if self.__has_valid_config is False:
return None
Expand Down Expand Up @@ -986,7 +983,7 @@ def on_chat_model_start(
user_props=user_props,
app_id=self.__app_id,
callback_queue=self.queue,
runtime="langchain-py"
runtime="langchain-py"
)
except Exception as e:
logger.exception(f"An error occurred in `on_chat_model_start`: {e}")
Expand Down Expand Up @@ -1028,7 +1025,7 @@ def on_llm_end(
},
app_id=self.__app_id,
callback_queue=self.queue,
runtime="langchain-py"
runtime="langchain-py"
)
except Exception as e:
logger.exception(f"An error occurred in `on_llm_end`: {e}")
Expand Down Expand Up @@ -1075,7 +1072,7 @@ def on_tool_start(
user_props=user_props,
app_id=self.__app_id,
callback_queue=self.queue,
runtime="langchain-py"
runtime="langchain-py"
)
except Exception as e:
logger.exception(f"An error occurred in `on_tool_start`: {e}")
Expand All @@ -1101,7 +1098,7 @@ def on_tool_end(
output=output,
app_id=self.__app_id,
callback_queue=self.queue,
runtime="langchain-py"
runtime="langchain-py"
)
except Exception as e:
logger.exception(f"An error occurred in `on_tool_end`: {e}")
Expand Down Expand Up @@ -1388,7 +1385,7 @@ def on_retriever_error(
logger.exception(f"An error occurred in `on_retriever_error`: {e}")

except Exception as e:
# Do not raise error for users that do not have Langchain installed
# Do not raise error for users that do not have Langchain installed
pass


Expand All @@ -1414,7 +1411,7 @@ def track_feedback(run_id: str, feedback: Dict[str, Any]):
def get_raw_template(slug: str, app_id: str | None = None, api_url: str | None = None):
config = get_config()
token = app_id or config.app_id
api_url = api_url or config.api_url
api_url = api_url or config.api_url

global templateCache
now = time.time() * 1000
Expand All @@ -1428,8 +1425,8 @@ def get_raw_template(slug: str, app_id: str | None = None, api_url: str | None
'Content-Type': 'application/json'
}

response = requests.get(f"{api_url}/v1/template_versions/latest?slug={slug}",
headers=headers,
response = requests.get(f"{api_url}/v1/template_versions/latest?slug={slug}",
headers=headers,
verify=config.ssl_verify)
if not response.ok:
logger.exception(f"Error fetching template: {response.status_code} - {response.text}")
Expand All @@ -1441,7 +1438,7 @@ def get_raw_template(slug: str, app_id: str | None = None, api_url: str | None
async def get_raw_template_async(slug: str, app_id: str | None = None, api_url: str | None = None):
config = get_config()
token = app_id or config.app_id
api_url = api_url or config.api_url
api_url = api_url or config.api_url


global templateCache
Expand Down Expand Up @@ -1498,16 +1495,13 @@ def render_template(slug: str, data = {}):
message["content"] = chevron.render(message["content"], data)
messages.append(message)
result = {
"messages": messages,
"messages": messages,
"extra_headers": extra_headers,
**extra
}

return result

except TemplateNotFoundError as e:
logger.error(e)
raise
except Exception as e:
logger.exception(f"Error rendering template {e}")
raise
Expand Down Expand Up @@ -1583,7 +1577,7 @@ def replace_double_braces(text):

messages = []

# Return array of messages:
# Return array of messages:
# [
# ("system", "You are a helpful AI bot. Your name is {name}."),
# ("human", "Hello, how are you doing?"),
Expand All @@ -1596,9 +1590,9 @@ def replace_double_braces(text):
template = ChatPromptTemplate.from_messages(messages)

return template
except TemplateNotFoundError as e:
logger.error(e)

except Exception as e:
logger.exception(f"Error rendering template {e}")
raise

async def get_langchain_template_async(slug):
Expand Down Expand Up @@ -1643,9 +1637,6 @@ def replace_double_braces(text):

return template

except TemplateNotFoundError as e:
logger.error(e)
raise
except Exception as e:
logger.exception(f"Error fetching template: {e}")
raise
Expand All @@ -1660,8 +1651,8 @@ def __init__(self, d=None):

def get_dataset(slug: str, app_id: str | None = None, api_url: str | None = None):
config = get_config()
token = app_id or config.app_id
api_url = api_url or config.api_url
token = app_id or config.app_id
api_url = api_url or config.api_url

try:
url = f"{api_url}/v1/datasets/{slug}"
Expand All @@ -1675,7 +1666,7 @@ def get_dataset(slug: str, app_id: str | None = None, api_url: str | None = None
dataset = humps.decamelize(dataset)
items_data = dataset.get('items', [])
items = [DatasetItem(d=item) for item in items_data]

return items
else:
raise Exception(f"Status code: {response.status_code}")
Expand All @@ -1686,8 +1677,8 @@ def get_dataset(slug: str, app_id: str | None = None, api_url: str | None = None

def evaluate(checklist, input, output, ideal_output=None, context=None, model=None, duration=None, tags=None, app_id=None, api_url=None):
config = get_config()
token = app_id or config.app_id
api_url = api_url or config.api_url
token = app_id or config.app_id
api_url = api_url or config.api_url

try:
url = f"{api_url}/v1/evaluations/run"
Expand Down

0 comments on commit 65290c1

Please sign in to comment.