Skip to content

Commit

Permalink
feat: Add support for tags with OpenAI Instrumentation (#63)
Browse files Browse the repository at this point in the history
  • Loading branch information
Granipouss authored Apr 26, 2024
1 parent 25ed5a9 commit f18453a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
2 changes: 2 additions & 0 deletions literalai/instrumentation/openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ def init_generation(generation_type: "GenerationType", kwargs):
tools=tools,
settings=settings,
messages=messages,
tags=kwargs.get("literal_tags"),
)

elif generation_type == GenerationType.COMPLETION:
Expand All @@ -156,6 +157,7 @@ def init_generation(generation_type: "GenerationType", kwargs):
model=model,
settings=settings,
prompt=kwargs.get("prompt"),
tags=kwargs.get("literal_tags"),
)

def update_step_after(
Expand Down
21 changes: 21 additions & 0 deletions literalai/wrappers.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,21 @@ class AfterContext(TypedDict):
start: float


def remove_literal_args(kargs):
'''Remove argument prefixed with "literal_" from kwargs and return them in a separate dict'''
largs = {}
for key in list(kargs.keys()):
if key.startswith("literal_"):
value = kargs.pop(key)
largs[key] = value
return largs

def restore_literal_args(kargs, largs):
'''Reverse the effect of remove_literal_args by merging the literal arguments into kwargs'''
for key in list(largs.keys()):
kargs[key] = largs[key]


def sync_wrapper(before_func=None, after_func=None):
def decorator(original_func):
@wraps(original_func)
Expand All @@ -31,6 +46,8 @@ def wrapped(*args, **kwargs):
# If a before_func is provided, call it with the shared context.
if before_func:
before_func(context, *args, **kwargs)
# Remove literal arguments before calling the original function
literal_args = remove_literal_args(kwargs)
context["start"] = time.time()
try:
result = original_func(*args, **kwargs)
Expand All @@ -44,6 +61,7 @@ def wrapped(*args, **kwargs):
raise e
# If an after_func is provided, call it with the result and the shared context.
if after_func:
restore_literal_args(kwargs, literal_args)
result = after_func(result, context, *args, **kwargs)

return result
Expand All @@ -62,6 +80,8 @@ async def wrapped(*args, **kwargs):
if before_func:
await before_func(context, *args, **kwargs)

# Remove literal arguments before calling the original function
literal_args = remove_literal_args(kwargs)
context["start"] = time.time()
try:
result = await original_func(*args, **kwargs)
Expand All @@ -76,6 +96,7 @@ async def wrapped(*args, **kwargs):

# If an after_func is provided, call it with the result and the shared context.
if after_func:
restore_literal_args(kwargs, literal_args)
result = await after_func(result, context, *args, **kwargs)

return result
Expand Down

0 comments on commit f18453a

Please sign in to comment.