constexpress=require('express')constapp=express()functionmyAgentMiddleware(req,res,next){consterr=...// user application logic
// the span for this function is finished when `next` is called
next(err)}myAgentMiddleware=llmobs.wrap({kind:'agent'},myAgentMiddleware)app.use(myAgentMiddleware)
constexpress=require('express')constapp=express()functionmyAgentMiddleware(req,res){// the `next` callback is not being used here
returnllmobs.trace({kind:'agent',name:'myAgentMiddleware'},()=>{returnres.status(200).send('Hello World!')})}app.use(myAgentMiddleware)
try{LLMObsSpanworkflowSpan=LLMObs.startWorkflowSpan("my-workflow-span-name","ml-app-override","session-141");// user logic// interact with started span}finally{workflowSpan.finish();}
オプション - 文字列 操作が属する ML アプリケーションの名前。詳細については、複数のアプリケーションのトレースを参照してください。
例
fromddtrace.llmobsimportLLMObsfromddtrace.llmobs.decoratorsimportllm@llm(model_name="claude",name="invoke_llm",model_provider="anthropic")defllm_call(prompt):completion=...# user application logic to invoke LLMLLMObs.annotate(input_data=[{"role":"user","content":prompt}],output_data=[{"role":"assistant","content":completion}],metrics={"input_tokens":4,"output_tokens":6,"total_tokens":10},)returncompletion
オプション - 文字列 操作が属する ML アプリケーションの名前。詳細については、複数のアプリケーションのトレースを参照してください。
例
functionllmCall(prompt){constcompletion=...// user application logic to invoke LLM
llmobs.annotate({inputData:[{role:"user",content:prompt}],outputData:[{role:"assistant",content:completion}],metrics:{input_tokens:4,output_tokens:6,total_tokens:10}})returncompletion}llmCall=llmobs.wrap({kind:'llm',name:'invokeLLM',modelName:'claude',modelProvider:'anthropic'},llmCall)
importdatadog.trace.api.llmobs.LLMObs;publicclassMyJavaClass{publicStringinvokeModel(){LLMObsSpanllmSpan=LLMObs.startLLMSpan("my-llm-span-name","my-llm-model","my-company","maybe-ml-app-override","session-141");Stringinference=...// user application logic to invoke LLMllmSpan.annotateIO(...);// record the input and outputllmSpan.setMetrics(Map.of("input_tokens",617,"output_tokens",338,"total_tokens",955));llmSpan.finish();returninference;}}
importdatadog.trace.api.llmobs.LLMObs;publicclassMyJavaClass{publicStringexecuteWorkflow(){LLMObsSpanworkflowSpan=LLMObs.startWorkflowSpan("my-workflow-span-name",null,"session-141");StringworkflowResult=workflowFn();// user application logicworkflowSpan.annotateIO(...);// record the input and outputworkflowSpan.finish();returnworkflowResult;}}
オプション - 文字列 操作が属する ML アプリケーションの名前。詳細については、複数のアプリケーションのトレースを参照してください。
例
fromddtrace.llmobs.decoratorsimportembedding@embedding(model_name="text-embedding-3",model_provider="openai")defperform_embedding():...# user application logicreturn
オプション - 文字列 操作が属する ML アプリケーションの名前。詳細については、複数のアプリケーションのトレースを参照してください。
例
functionperformEmbedding(){...// user application logic
return}performEmbedding=llmobs.wrap({kind:'embedding',modelName:'text-embedding-3',modelProvider:'openai'},performEmbedding)
オプション - 文字列 操作が属する ML アプリケーションの名前。詳細については、複数のアプリケーションのトレースを参照してください。
例
fromddtrace.llmobs.decoratorsimportretrieval@retrievaldefget_relevant_docs(question):context_documents=...# user application logicLLMObs.annotate(input_data=question,output_data=[{"id":doc.id,"score":doc.score,"text":doc.text,"name":doc.name}fordocincontext_documents])return
functiongetRelevantDocs(question){constcontextDocuments=...// user application logic
llmobs.annotate({inputData:question,outputData:contextDocuments.map(doc=>({id:doc.id,score:doc.score,text:doc.text,name:doc.name}))})return}getRelevantDocs=llmobs.wrap({kind:'retrieval'},getRelevantDocs)
fromddtrace.llmobs.decoratorsimporttask,workflow@workflowdefextract_data(document):preprocess_document(document)...# performs data extraction on the documentreturn@taskdefpreprocess_document(document):...# preprocesses a document for data extractionreturn
functionpreprocessDocument(document){...// preprocesses a document for data extraction
return}preprocessDocument=llmobs.wrap({kind:'task'},preprocessDocument)functionextractData(document){preprocessDocument(document)...// performs data extraction on the document
return}extractData=llmobs.wrap({kind:'workflow'},extractData)
importdatadog.trace.api.llmobs.LLMObs;importdatadog.trace.api.llmobs.LLMObsSpan;publicclassMyJavaClass{publicvoidpreprocessDocument(Stringdocument){LLMObsSpantaskSpan=LLMObs.startTaskSpan("preprocessDocument",null,"session-141");...// preprocess document for data extractiontaskSpan.annotateIO(...);// record the input and outputtaskSpan.finish();}publicStringextractData(Stringdocument){LLMObsSpanworkflowSpan=LLMObs.startWorkflowSpan("extractData",null,"session-141");preprocessDocument(document);...// perform data extraction on the documentworkflowSpan.annotateIO(...);// record the input and outputworkflowSpan.finish();}}
fromddtrace.llmobsimportLLMObsfromddtrace.llmobs.decoratorsimportembedding,llm,retrieval,workflow@llm(model_name="model_name",model_provider="model_provider")defllm_call(prompt):resp=...# llm call hereLLMObs.annotate(span=None,input_data=[{"role":"user","content":"Hello world!"}],output_data=[{"role":"assistant","content":"How can I help?"}],metadata={"temperature":0,"max_tokens":200},metrics={"input_tokens":4,"output_tokens":6,"total_tokens":10},tags={"host":"host_name"},)returnresp@workflowdefextract_data(document):resp=llm_call(document)LLMObs.annotate(input_data=document,output_data=resp,tags={"host":"host_name"},)returnresp@embedding(model_name="text-embedding-3",model_provider="openai")defperform_embedding():...# user application logicLLMObs.annotate(span=None,input_data={"text":"Hello world!"},output_data=[0.0023064255,-0.009327292,...],metrics={"input_tokens":4},tags={"host":"host_name"},)return@retrieval(name="get_relevant_docs")defsimilarity_search():...# user application logicLLMObs.annotate(span=None,input_data="Hello world!",output_data=[{"text":"Hello world is ...","name":"Hello, World! program","id":"document_id","score":0.9893}],tags={"host":"host_name"},)return@llm(model_name="gpt-realtime",model_provider="openai")defvoice_turn(user_audio_bytes):importbase64resp=...# multimodal (audio) llm call hereLLMObs.annotate(span=None,input_data=[{"role":"user","content":"Hey, how are you?",# transcript of the input audio"audio_parts":[{"mime_type":"audio/wav","content":base64.b64encode(user_audio_bytes).decode("utf-8")}],}],output_data=[{"role":"assistant","content":"Hey! I'm doing great, thanks for asking. How about you?","audio_parts":[{"mime_type":"audio/wav","content":base64.b64encode(resp.audio_bytes).decode("utf-8")}],}],)returnresp@llm(model_name="gpt-4o",model_provider="openai")defdescribe_image(image_bytes):importbase64resp=...# multimodal (vision) llm call hereLLMObs.annotate(span=None,input_data=[{"role":"user","content":"What is in this image?","image_parts":[{"mime_type":"image/png","content":base64.b64encode(image_bytes).decode("utf-8")}],}],output_data=[{"role":"assistant","content":"The image shows a golden retriever puppy."}],)returnresp
functionllmCall(prompt){constcompletion=...// user application logic to invoke LLM
llmobs.annotate({inputData:[{role:"user",content:"Hello world!"}],outputData:[{role:"assistant",content:"How can I help?"}],metadata:{temperature:0,max_tokens:200},metrics:{input_tokens:4,output_tokens:6,total_tokens:10},tags:{host:"host_name"}})returncompletion}llmCall=llmobs.wrap({kind:'llm',modelName:'modelName',modelProvider:'modelProvider'},llmCall)functionextractData(document){constresp=llmCall(document)llmobs.annotate({inputData:document,outputData:resp,tags:{host:"host_name"}})returnresp}extractData=llmobs.wrap({kind:'workflow'},extractData)functionperformEmbedding(){...// user application logic
llmobs.annotate(undefined,{// this can be set to undefined or left out entirely
inputData:{text:"Hello world!"},outputData:[0.0023064255,-0.009327292,...],metrics:{input_tokens:4},tags:{host:"host_name"}})}performEmbedding=llmobs.wrap({kind:'embedding',modelName:'text-embedding-3',modelProvider:'openai'},performEmbedding)functionsimilaritySearch(){...// user application logic
llmobs.annotate(undefined,{inputData:"Hello world!",outputData:[{text:"Hello world is ...",name:"Hello, World! program",id:"document_id",score:0.9893}],tags:{host:"host_name"}})return}similaritySearch=llmobs.wrap({kind:'retrieval',name:'getRelevantDocs'},similaritySearch)functionvoiceTurn(userAudioBytes){constresp=...// multimodal (audio) llm call here
llmobs.annotate({inputData:[{role:"user",content:"Hey, how are you?",// transcript of the input audio
audioParts:[{mimeType:"audio/wav",content:userAudioBytes.toString("base64")}]}],outputData:[{role:"assistant",content:"Hey! I'm doing great, thanks for asking. How about you?",audioParts:[{mimeType:"audio/wav",content:resp.audioBuffer.toString("base64")}]}]})returnresp}voiceTurn=llmobs.wrap({kind:'llm',modelName:'gpt-audio',modelProvider:'openai'},voiceTurn)functiondescribeImage(imageBytes){constresp=...// multimodal (vision) llm call here
llmobs.annotate({inputData:[{role:"user",content:"What is in this image?",imageParts:[{mimeType:"image/png",content:imageBytes.toString("base64")}]}],outputData:[{role:"assistant",content:"The image shows a golden retriever puppy."}]})returnresp}describeImage=llmobs.wrap({kind:'llm',modelName:'gpt-4o',modelProvider:'openai'},describeImage)
importdatadog.trace.api.llmobs.LLMObs;publicclassMyJavaClass{publicStringinvokeChat(StringuserInput){LLMObsSpanllmSpan=LLMObs.startLLMSpan("my-llm-span-name","my-llm-model","my-company","maybe-ml-app-override","session-141");StringsystemMessage="You are a helpful assistant";ResponsechatResponse=...// user application logic to invoke LLMllmSpan.annotateIO(Arrays.asList(LLMObs.LLMMessage.from("user",userInput),LLMObs.LLMMessage.from("system",systemMessage)),Arrays.asList(LLMObs.LLMMessage.from(chatResponse.role,chatResponse.content)));llmSpan.finish();returnchatResponse;}}
importdatadog.trace.api.llmobs.LLMObs;publicclassMyJavaClass{publicStringinvokeChat(StringuserInput){LLMObsSpanllmSpan=LLMObs.startLLMSpan("my-llm-span-name","my-llm-model","my-company","maybe-ml-app-override","session-141");StringchatResponse=...// user application logic to invoke LLMllmSpan.setMetrics(Map.of("input_tokens",617,"output_tokens",338,"time_per_output_token",0.1773));llmSpan.setMetric("total_tokens",955);llmSpan.setMetric("time_to_first_token",0.23);llmSpan.finish();returnchatResponse;}}
importdatadog.trace.api.llmobs.LLMObs;publicclassMyJavaClass{publicStringinvokeChat(StringuserInput){LLMObsSpanllmSpan=LLMObs.startLLMSpan("my-llm-span-name","my-llm-model","my-company","maybe-ml-app-override","session-141");StringchatResponse=...// user application logic to invoke LLMllmSpan.setTags(Map.of("chat_source","web","users_in_chat",3));llmSpan.setTag("is_premium_user",true);llmSpan.finish();returnchatResponse;}}
importdatadog.trace.api.llmobs.LLMObs;publicclassMyJavaClass{publicStringinvokeChat(StringuserInput){LLMObsSpanllmSpan=LLMObs.startLLMSpan("my-llm-span-name","my-llm-model","my-company","maybe-ml-app-override","session-141");StringchatResponse="N/A";try{chatResponse=...// user application logic to invoke LLM}catch(Exceptione){llmSpan.addThrowable(e);thrownewRuntimeException(e);}finally{llmSpan.finish();}returnchatResponse;}}
importdatadog.trace.api.llmobs.LLMObs;publicclassMyJavaClass{publicStringinvokeChat(StringuserInput){LLMObsSpanllmSpan=LLMObs.startLLMSpan("my-llm-span-name","my-llm-model","my-company","maybe-ml-app-override","session-141");llmSpan.setMetadata(Map.of("temperature",0.5,"is_premium_member",true,"class","e1"));StringchatResponse=...// user application logic to invoke LLMreturnchatResponse;}}
fromddtrace.llmobsimportLLMObsfromddtrace.llmobs.decoratorsimportworkflow@workflowdefrag_workflow(user_question):context_str=retrieve_documents(user_question).join(" ")withLLMObs.annotation_context(prompt=Prompt(id="chatbot_prompt",version="1.0.0",template="Please answer the question using the provided context: {{question}}\n\nContext:\n{{context}}",variables={"question":user_question,"context":context_str,}),tags={"retrieval_strategy":"semantic_similarity"},name="augmented_generation"):completion=openai_client.chat.completions.create(...)returncompletion.choices[0].message.content
fromddtrace.llmobsimportLLMObsdefanswer_question(text):# Attach prompt metadata to the upcoming LLM span using LLMObs.annotation_context()withLLMObs.annotation_context(prompt={"id":"translation-template","version":"1.0.0","chat_template":[{"role":"user","content":"Translate to {{lang}}: {{text}}"}],"variables":{"lang":"fr","text":text},"tags":{"team":"nlp"}}):# Example provider call (replace with your client)completion=openai_client.chat.completions.create(model="gpt-4o",messages=[{"role":"user","content":f"Translate to fr: {text}"}])returncompletion
# "translation_template" will be used to identify the template in Datadogtranslation_template=PromptTemplate.from_template("Translate {text} to {language}")chain=translation_template|llm
template(string | List[Message]): プレースホルダーを含むテンプレート文字列 (例: "Translate {{text}} to {{lang}}"). Alternatively, a list of { "role": "<role>", "content": "<template string with placeholders>" } オブジェクトのリスト。
const{llmobs}=require('dd-trace');functionanswerQuestion(text){// Attach prompt metadata to the upcoming LLM span using LLMObs.annotation_context()
returnllmobs.annotationContext({prompt:{id:"translation-template",version:"1.0.0",chat_template:[{"role":"user","content":"Translate to {{lang}}: {{text}}"}],variables:{"lang":"fr","text":text},tags:{"team":"nlp"}}},()=>{// Example provider call (replace with your client)
returnopenaiClient.chat.completions.create({model:"gpt-4o",messages:[{"role":"user","content":f"Translate to fr: {text}"}]});});}
functionllmCall(prompt){constresp=...// llm call here
llmobs.annotate({metrics:{input_tokens:50,output_tokens:120,total_tokens:170},tags:{team:'nlp',customer_tier:'enterprise',host:'host_name'},costTags:['team','customer_tier']})returnresp}llmCall=llmobs.wrap({kind:'llm',modelName:'gpt-5.1',modelProvider:'openai'},llmCall)
fromddtrace.llmobsimportLLMObsfromddtrace.llmobs.decoratorsimportllm@llm(model_name="claude",name="invoke_llm",model_provider="anthropic")defllm_call():completion=...# user application logic to invoke LLMspan_context=LLMObs.export_span(span=None)returncompletion
functionllmCall(){constcompletion=...// user application logic to invoke LLM
constspanContext=llmobs.exportSpan()returncompletion}llmCall=llmobs.wrap({kind:'llm',name:'invokeLLM',modelName:'claude',modelProvider:'anthropic'},llmCall)
fromddtrace.llmobsimportLLMObsfromddtrace.llmobs.decoratorsimportllm@llm(model_name="claude",name="invoke_llm",model_provider="anthropic")defllm_call():completion=...# user application logic to invoke LLM# joining an evaluation to a span via a tag key-value pairmsg_id=get_msg_id()LLMObs.annotate(tags={'msg_id':msg_id})LLMObs.submit_evaluation(span_with_tag_value={"tag_key":"msg_id","tag_value":msg_id},ml_app="chatbot",label="harmfulness",metric_type="score",value=10,tags={"evaluation_provider":"ragas"},assessment="fail",reasoning="Malicious intent was detected in the user instructions.",metadata={"details":["jailbreak","SQL injection"]})# joining an evaluation to a span via span ID and trace IDspan_context=LLMObs.export_span(span=None)LLMObs.submit_evaluation(span_context=span_context,ml_app="chatbot",label="harmfulness",metric_type="score",value=10,tags={"evaluation_provider":"ragas"},assessment="fail",reasoning="Malicious intent was detected in the user instructions.",metadata={"details":["jailbreak","SQL injection"]})returncompletion
functionllmCall(){constcompletion=...// user application logic to invoke LLM
constspanContext=llmobs.exportSpan()llmobs.submitEvaluation(spanContext,{label:"harmfulness",metricType:"score",value:10,tags:{evaluationProvider:"ragas"}})returncompletion}llmCall=llmobs.wrap({kind:'llm',name:'invokeLLM',modelName:'claude',modelProvider:'anthropic'},llmCall)
importdatadog.trace.api.llmobs.LLMObs;publicclassMyJavaClass{publicStringinvokeChat(StringuserInput){LLMObsSpanllmSpan=LLMObs.startLLMSpan("my-llm-span-name","my-llm-model","my-company","maybe-ml-app-override","session-141");StringchatResponse="N/A";try{chatResponse=...// user application logic to invoke LLM}catch(Exceptione){llmSpan.addThrowable(e);thrownewRuntimeException(e);}finally{llmSpan.finish();// submit evaluationsLLMObs.SubmitEvaluation(llmSpan,"toxicity","toxic",Map.of("language","english"));LLMObs.SubmitEvaluation(llmSpan,"f1-similarity",0.02,Map.of("provider","f1-calculator"));}returnchatResponse;}}
エンドユーザーフィードバックの送信
エンドユーザーフィードバックは、LLM アプリケーションのユーザーからの入力 (高評価や低評価、ユーザーがエージェントの変更を受け入れたかどうか、自由記述のコメントなど) を収集します。評価とは異なり、フィードバックには送信者の ID が含まれ、スパン、トレース、セッション、または顧客定義のエンティティを対象にすることができます。詳細については、エンドユーザーフィードバックを参照してください。
fromddtrace.llmobsimportLLMObsfromddtrace.llmobs.decoratorsimportllm@llm(model_name="claude",name="invoke_llm",model_provider="anthropic")defllm_call():completion=...# user application logic to invoke LLMspan_context=LLMObs.export_span(span=None)# submitting feedback for a traceLLMObs.submit_feedback(label="thumbs",metric_type="categorical",value="down",submitter={"id":"user-123","type":"user"},trace_id=span_context["trace_id"],assessment="fail",)# connecting the span to a customer-defined entityLLMObs.annotate(tags={"feedback_join_key":"incident-123"})# submitting feedback for that entityLLMObs.submit_feedback(label="user_comment",metric_type="text",value="The investigation missed the customer impact.",submitter={"id":"user-123","type":"user"},feedback_join_key="incident-123",)returncompletion
functionllmCall(){constcompletion=...// user application logic to invoke LLM
constspanContext=llmobs.exportSpan()// submitting feedback for a trace
llmobs.submitFeedback({label:'thumbs',metricType:'boolean',value:true,submitter:{id:'user-123',type:'user'},traceId:spanContext.traceId,assessment:'pass'})// connecting the span to a customer-defined entity
llmobs.annotate({tags:{feedback_join_key:'incident-123'}})// submitting feedback for that entity
llmobs.submitFeedback({label:'user_comment',metricType:'text',value:'This answer was helpful.',submitter:{id:'user-123',type:'user'},feedbackJoinKey:'incident-123'})returncompletion}llmCall=llmobs.wrap({kind:'llm',name:'invokeLLM',modelName:'claude',modelProvider:'anthropic'},llmCall)
importdatadog.trace.api.llmobs.LLMObs;publicclassMyJavaClass{publicStringinvokeChat(StringuserInput){LLMObsSpanllmSpan=LLMObs.startLLMSpan("my-llm-span-name","my-llm-model","my-company","maybe-ml-app-override","session-141");StringchatResponse="N/A";try{chatResponse=...// user application logic to invoke LLM}catch(Exceptione){llmSpan.addThrowable(e);thrownewRuntimeException(e);}finally{// connecting the span to a customer-defined entityllmSpan.setTag("feedback_join_key","incident-123");llmSpan.finish();// submitting feedback for a traceLLMObs.submitFeedback(LLMObs.Feedback.builder().traceId(llmSpan.getTraceId().toString()).label("thumbs").booleanValue(true).submitter("user-123","end_user").assessment(LLMObs.Feedback.Assessment.PASS).reasoning("answered the question").build());// submitting feedback for that entityLLMObs.submitFeedback(LLMObs.Feedback.builder().feedbackJoinKey("incident-123").label("user_comment").textValue("The answer missed the customer impact.").submitter("user-123","end_user").assessment(LLMObs.Feedback.Assessment.FAIL).build());}returnchatResponse;}}
fromddtrace.llmobsimportLLMObsfromddtrace.llmobsimportLLMObsSpandefredact_processor(span:LLMObsSpan)->LLMObsSpan:ifspan.get_tag("no_output")=="true":formessageinspan.output:message["content"]=""returnspan# If using LLMObs.enable()LLMObs.enable(...span_processor=redact_processor,)# else when using `ddtrace-run`LLMObs.register_processor(redact_processor)withLLMObs.llm("invoke_llm_with_no_output"):LLMObs.annotate(tags={"no_output":"true"})
fromddtrace.llmobsimportLLMObsfromddtrace.llmobsimportLLMObsSpandefredact_processor(span:LLMObsSpan)->LLMObsSpan:ifspan.get_tag("no_input")=="true":formessageinspan.input:message["content"]=""returnspanLLMObs.register_processor(redact_processor)defcall_openai():withLLMObs.annotation_context(tags={"no_input":"true"}):# make call to openai...
例: スパンの出力を防ぐ
fromddtrace.llmobsimportLLMObsfromddtrace.llmobsimportLLMObsSpanfromtypingimportOptionaldeffilter_processor(span:LLMObsSpan)->Optional[LLMObsSpan]:# Skip spans that are marked as internal or contain sensitive dataifspan.get_tag("internal")=="true"orspan.get_tag("sensitive")=="true":returnNone# This span will not be emitted# Process and return the span normallyreturnspanLLMObs.register_processor(filter_processor)# This span will be filtered out and not sent to DatadogwithLLMObs.workflow("internal_workflow"):LLMObs.annotate(tags={"internal":"true"})# ... workflow logic
const{llmobs}=require('dd-trace');functionredactProcessor(span){if(span.getTag("no_input")=="true"){for(constmessageofspan.input){message.content="";}}returnspan;}llmobs.registerProcessor(redactProcessor);asyncfunctioncallOpenai(){awaitllmobs.annotationContext({tags:{no_input:"true"}},async()=>{// make call to openai
});}
例: スパンの出力を防ぐ
consttracer=require('dd-trace').init({llmobs:{mlApp:"<YOUR_ML_APP_NAME>"}})constllmobs=tracer.llmobsfunctionfilterProcessor(span){// Skip spans that are marked as internal or contain sensitive data
if(span.getTag("internal")==="true"||span.getTag("sensitive")==="true"){returnnull// This span will not be emitted
}// Process and return the span normally
returnspan}llmobs.registerProcessor(filterProcessor)// This span will be filtered out and not sent to Datadog
functioninternalWorkflow(){returnllmobs.trace({kind:'workflow',name:'internalWorkflow'},(span)=>{llmobs.annotate({tags:{internal:"true"}})// ... workflow logic
})}
新しいトレースのルートスパンを開始する場合や新しいプロセスでスパンを開始する場合は、sessionId 引数に基盤となるユーザーセッションの文字列 ID を指定します。
importdatadog.trace.api.llmobs.LLMObs;publicclassMyJavaClass{publicStringprocessChat(intuserID){LLMObsSpanworkflowSpan=LLMObs.startWorkflowSpan("incoming-chat",null,"session-"+System.currentTimeMillis()+"-"+userID);StringchatResponse=answerChat();// user application logicworkflowSpan.annotateIO(...);// record the input and outputworkflowSpan.finish();returnchatResponse;}}
fromddtrace.llmobsimportLLMObsdefserver_process_request(request):LLMObs.activate_distributed_headers(request.headers)withLLMObs.task(name="process_request")asspan:pass# arbitrary server work
fromddtrace.llmobsimportLLMObsdefprocess_message():withLLMObs.workflow(name="process_message",session_id="<SESSION_ID>",ml_app="<ML_APP>")asworkflow_span:...# user application logicreturn
fromddtrace.llmobsimportLLMObsdefprocess_message():workflow_span=LLMObs.workflow(name="process_message")...# user application logicseparate_task(workflow_span)returndefseparate_task(workflow_span):...# user application logicworkflow_span.finish()return
fromddtrace.llmobs.decoratorsimportworkflow@workflow(name="process_message",ml_app="<NON_DEFAULT_ML_APP_NAME>")defprocess_message():...# user application logicreturn
functionprocessMessage(){returnllmobs.trace({kind:'workflow',name:'processMessage',sessionId:'<SESSION_ID>',mlApp:'<ML_APP>'},workflowSpan=>{...// user application logic
return})}
コールバックを使用する例
functionprocessMessage(){returnllmobs.trace({kind:'workflow',name:'processMessage',sessionId:'<SESSION_ID>',mlApp:'<ML_APP>'},(workflowSpan,cb)=>{...// user application logic
letmaybeError=...cb(maybeError)// the span will finish here, and tag the error if it is not null or undefined
return})}
この関数の戻り値の型は、トレースする関数の戻り値の型と一致します。
functionprocessMessage(){constresult=llmobs.trace({kind:'workflow',name:'processMessage',sessionId:'<SESSION_ID>',mlApp:'<ML_APP>'},workflowSpan=>{...// user application logic
return'hello world'})console.log(result)// 'hello world'
returnresult}
functionprocessMessage(){...// user application logic
return}processMessage=llmobs.wrap({kind:'workflow',name:'processMessage',mlApp:'<NON_DEFAULT_ML_APP_NAME>'},processMessage)