import openai
import langsmith as ls
from langsmith.wrappers import wrap_openai
client = openai.Client()
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
]
# 함수를 데코레이팅할 때 메타데이터와 태그를 **정적으로** 설정할 수 있습니다
# 태그와 메타데이터가 포함된 @traceable 데코레이터 사용
# @traceable이 작동하려면 LANGSMITH_TRACING 환경 변수가 설정되어 있어야 합니다
@ls.traceable(
run_type="llm",
name="OpenAI Call Decorator",
tags=["my-tag"],
metadata={"my-key": "my-value"}
)
def call_openai(
messages: list[dict], model: str = "gpt-4o-mini"
) -> str:
# 부모 실행에 메타데이터를 동적으로 설정할 수도 있습니다:
rt = ls.get_current_run_tree()
rt.metadata["some-conditional-key"] = "some-val"
rt.tags.extend(["another-tag"])
return client.chat.completions.create(
model=model,
messages=messages,
).choices[0].message.content
call_openai(
messages,
# 함수를 호출할 때 **호출 시점**에 추가하려면
# langsmith_extra 매개변수를 사용합니다
langsmith_extra={"tags": ["my-other-tag"], "metadata": {"my-other-key": "my-value"}}
)
# 또는 컨텍스트 매니저를 사용할 수 있습니다
with ls.trace(
name="OpenAI Call Trace",
run_type="llm",
inputs={"messages": messages},
tags=["my-tag"],
metadata={"my-key": "my-value"},
) as rt:
chat_completion = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
)
rt.metadata["some-conditional-key"] = "some-val"
rt.end(outputs={"output": chat_completion})
# 래핑된 클라이언트에서도 동일한 기법을 사용할 수 있습니다
patched_client = wrap_openai(
client, tracing_extra={"metadata": {"my-key": "my-value"}, "tags": ["a-tag"]}
)
chat_completion = patched_client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
langsmith_extra={
"tags": ["my-other-tag"],
"metadata": {"my-other-key": "my-value"},
},
)