AI

Python

TypeScript

Langfuse

LLMOps

tech

Introduction

Hello, I'm Hayashizaki (@u_hyszk) from the AI team at AI Shift.

After introducing an AI agent, have you ever reached the stage of "it's time to evaluate and improve," only to find that there was no platform in place to collect execution histories for evaluation? Or have you ever wanted to collect execution histories but didn't know how, so it got deprioritized?

In this article, we introduce the mechanism created by our FDEs (Forward Deployed Engineers), who develop a wide variety of AI agents and applications for customers adopting AI Worker, in order to record and make use of execution histories.

トレーシング基盤Tracing Platform

Background and Challenges

Let me explain why we undertook this development, based on the background of our product "AI Worker Platform" and how FDEs work, along with the challenges involved.

AI Worker Platform and FDEs

At AI Shift, we offer a product called "AI Worker Platform" as an integrated platform for AI-ifying entire business processes.

https://www.aiworker.jp/ai-solution

Compared to our existing product "AI Worker VoiceAgent",

  • The business domains it handles (back-office operations, sales support, data analysis, etc.) are extremely broad and require deep understanding
  • The individual system integrations required (internal systems, external APIs, databases, etc.) are complex

These are the kinds of challenges we face. Solving them is difficult through simply providing a SaaS product alone.

そこで弊社では、FDE職 を新設[1]し、お客様の業務に徹底的に向き合ったソリューションの提供を目指してきました。AI ShiftのFDEは、お客様の業務に深く入り込み、技術でAI x DXを成功に導くことをミッションに以下のような業務を担っています。

  • Analyzing customers' business processes and identifying challenges
  • Planning AI adoption and technical design
  • Implementing integrations with AI Worker Platform and external systems
  • Post-deployment operational support and effectiveness measurement
  • Providing feedback to the product team

Recently, in order to maximize the value delivered to customers, FDEs increasingly implement solutions individually, not just using AI Worker Platform. AI Shift's FDEs make full use of generative AI to automate nearly all development process tasks, allowing them to focus on addressing customer challenges.

https://note.com/ai_shift/n/nef90228fdf99 https://note.com/ai_shift/n/ncf695f3565c6

Collecting Execution Histories for Evaluation and Improvement

One of the AI team's missions is to figure out how to maintain the output quality of AI agents and demonstrate cost-effectiveness to customers while FDEs develop a wide variety of AI agents and applications. In this article, we focus on the "collecting execution histories" part, which is a prerequisite for evaluation and improvement.

To evaluate and improve an AI agent after its introduction, execution histories of how the agent behaved are required. Many LLM engineering platforms such as Langfuse and Arize Phoenix collect data called telemetry using OpenTelemetry, a framework for achieving observability. The key terms are as follows.

  • Telemetry: Data emitted from a system and its operations. In addition to traces (described below), it consists of metrics, which are measurements of availability and performance, and logs, which are timestamped text records.
  • Trace: A record of the entire processing of a single request, structured as a tree.
  • Span: A single unit of work or operation within a trace.

To collect telemetry, you need to perform "instrumentation", which involves embedding code into the target application to output telemetry data.

Toward Easy and Reliable Collection of Execution Histories

Collecting execution histories is essential for evaluating and improving AI agents. If execution histories are collected early on, it can be expected that requirements gathering for evaluation will proceed smoothly.

On the other hand, for FDEs who should focus on solving customer challenges, instrumentation is often deprioritized. This is because applications work normally even without instrumentation, so it's not urgent, and deciding how to implement instrumentation each time is burdensome.

Against this background, we determined that we needed to systematize the method of collecting execution histories in order to:

  • Eliminate missed collection of execution histories in built applications
  • Standardize the collection method
  • Improve the FDE development experience and allow them to focus on solving customer challenges

we decided we needed to systematize a way to collect execution history for that purpose.

A Tracing Platform to Support FDE Development

The overall architecture of the system we built is as follows.

トレーシング基盤Tracing platform (repeated)

We had developers use the LLM Gateway when calling LLMs, so that telemetry is collected at the infrastructure level. For data containing business-specific meaning that cannot be collected by the LLM Gateway alone, we perform manual instrumentation using an SDK and Skills. The collected telemetry is aggregated in an OpenTelemetry Collector, after which only the telemetry related to LLM calls is sent to Langfuse, our LLM engineering platform.

Automatic Telemetry Emission via LLM Gateway

We made it so that LLM Gateway is used when calling LLMs. This LLM Gateway records inputs, outputs, model names, token counts, and more, and automatically emits telemetry to the OpenTelemetry Collector. After that, only the telemetry related to LLM calls is sent to Langfuse.

In this way, by performing collection at the infrastructure level with the LLM Gateway, it becomes possible to automatically collect telemetry data without leaving the decision of whether to instrument up to the FDE.

This time, we use Agent Router (formerly Envoy AI Gateway) as the LLM Gateway. Agent Router supports tracing via OpenTelemetry, which can be enabled by specifying environment variables. An example configuration with Docker Compose is shown below.

services:
  aigw:
    image: docker.io/envoyproxy/ai-gateway-cli:v1.1.0
    command: run
    ports:
      - 127.0.0.1:1985:1975
    environment:
      OPENAI_API_KEY: ${OPENAI_API_KEY:-}
      OTEL_SERVICE_NAME: aigw
      OTEL_TRACES_EXPORTER: otlp
      OTEL_METRICS_EXPORTER: none
      OTEL_LOGS_EXPORTER: none
      OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318
      OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
      AI_GATEWAY_TRACING_SEMCONV: openinference
    depends_on:
      - otel-collector

Challenges of Instrumentation with the LLM Gateway

While telemetry collection via the LLM Gateway is convenient, it has the challenge that data requiring business-level semantic context cannot be collected at the application level. Specifically, the following kinds of data cannot be collected:

  • Headers indicating the flow of processing within the application (traceparent)
  • Data representing the purpose of LLM usage, such as search, tools, or ranking
  • Metadata and tags representing users and sessions

Regarding the first point, because the application does not perform context propagation, the LLM Gateway regenerates a new trace each time, resulting in the problem that an independent trace of depth 1 is generated for each LLM call. In complex use cases, this makes data analysis and evaluation difficult.

As for data requiring business-level semantic context, it is inherently difficult to collect it at the LLM Gateway, so we decided to also use manual instrumentation with the SDK and Skill.

Manual Instrumentation with the Tracing SDK and Skill

With the goal of adding business-level semantic context to the traces created by the LLM Gateway, we developed a dedicated Tracing SDK. The scope of this SDK is as follows:

  • Integration with the LLM Gateway
  • Structuring and standardizing traces with business-level semantics
  • Attaching and propagating data representing the purpose of LLM usage
  • Attaching and propagating metadata and tags such as user and session identifiers

Instrumentation of the LLM calls themselves is out of scope, since the LLM Gateway handles that. By having instrumentation done through this SDK, it becomes possible to collect high-quality data that is easy to use for analysis and evaluation.

Examples of using the SDK in Python and TypeScript are shown below.

+from ais_tracing import tracer

@app.post("/review")
async def review(body: dict) -> dict:
+   with tracer.trace(
+       "review",
+       input={"question": body["question"]},
+       user_id=body["user_id"],
+       session_id=body["session_id"],
+   ) as root:
        answer = await ask_gateway(body["question"], docs)
+       root.update(output={"answer": answer})
        return {"answer": answer, "observation_id": root.observation_id}
import { serve } from '@hono/node-server'
import { Hono } from 'hono'
+import { tracer } from '@ais/tracing'

const app = new Hono()

app.post('/review', async (c) => {
  const { question, sessionId } = await c.req.json()

+ return tracer.trace(
+   'review',
+   { input: { question }, userId: c.get('userId'), sessionId },
+   async (root) => {
      const gw = await fetch(`${process.env.GATEWAY_URL}/v1/chat/completions`, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ model: 'gpt-4o-mini', messages: buildMessages(question, docs) }),
      })
      const answer = (await gw.json()).choices[0].message.content
+     root.update({ output: { answer } })
      return c.json({ answer, observationId: root.observationId })
    },
  )
})

serve({ fetch: app.fetch, port: 8080 })

Furthermore, to reduce the development burden on FDEs, we created a Skill for AI agents to perform instrumentation with the Tracing SDK. By using this Skill, instrumentation can be delegated to coding AI, greatly reducing the implementation burden.

By building this kind of systematization,

  • the LLM Gateway eliminates collection gaps
  • the SDK and Skill standardize instrumentation
  • the SDK and Skill improve the FDE development experience

and thus the series of objectives is achieved.

Usage Example

Here we introduce what kind of data can actually be obtained by using this system. The following images show the actual Langfuse screen.

As a demo, we created an AI agent that searches FAQs and answers questions. The input query goes through a simple LLM-based guardrail, and the output is evaluated using LLM-as-a-Judge.

Langfuseの画面Langfuse screen

You can see that the LLM calls are collected in a cleanly structured form. Also, because metadata and other information were attached via the SDK, user and session information, as well as the purpose for which the LLM was called (guardrails, evaluation, etc.), are also visualized.

Langfuseの画面Langfuse screen (details)

By collecting data in such an organized form, it becomes easier to leverage it for subsequent agent evaluation and data analysis. Even if instrumentation with the SDK is accidentally omitted, the LLM calls are still recorded by the LLM Gateway, so minimal data analysis and evaluation requirements can still be defined.

Conclusion

In this article, we introduced the system we built for customers adopting AI Workers, designed to help FDEs who develop a wide variety of AI agents and applications record and leverage execution histories.

コーディングAIが普及して開発が高速化・多様化した現代において、実行履歴の収集を含むLLMOps・AgentOpsを実践していくことがますます困難になっていると感じています。直近ではLoglassさんも近い発表をされており[2]、弊社のみならず共通の課題であると考えている次第です。

We hope this serves as a useful reference if you run into difficulties with agent evaluation or execution history collection! Thank you for reading👻

AI Shift Tech Blog