This tutorial demonstrates an example Atlas Stream Processing pipeline that asks an LLM to flag unusual temperature and power readings from streaming solar-device data. The pipeline groups readings into 30-second windows to reduce API calls and stores the analysis in Atlas.
이 작업에 관한 정보
This tutorial creates a pipeline that monitors a fleet of solar devices. For each 30-second window, the pipeline sends the LLM a JSON array with one entry per device. Each entry contains the device's maximum temperature, its average, median, maximum, and minimum power readings, and its reading count. The LLM returns an anomalies array with the device_id, reason, and severity of each unusual device, plus a snark remark about the fleet's performance. If nothing is unusual, the LLM returns an empty anomalies array.
This tutorial uses OpenAI. The messages and response_format payload fields and the apiResults.choices[0].message.content response path are specific to OpenAI. To use another provider, adapt the API endpoint, authentication header, request payload, and response fields for that provider.
LLM 제공업체의 사용량 제한을 준수하기 위해 이 튜토리얼에서는 입력 문서를 `$hoppingWindow` 단계로 그룹화합니다. 파이프라인은 문서별로 API를 호출하는 대신 창별로 한 번씩 호출합니다.
The pipeline calls the gpt-6-luna model. To use another model, replace the model value in the $https stage. The model must support JSON mode, which the response_format: { type: "json_object" } field requests. JSON mode requires the prompt to contain the word JSON, so keep that word if you modify the system prompt.
시스템 프롬프트는 입력 필드를 설명하고 고정된 출력 형식을 정의합니다. 이 형식은 파이프라인이 Atlas에 기록하는 문서의 형태를 실행 간에 일관되게 유지합니다.
The pipeline's $https stage sets config: { parseJsonStrings: true }. This setting parses JSON strings in the API response into objects, so apiResults.choices[0].message.content returns as an object instead of a JSON string.
전제 조건
이 튜토리얼을 완료하려면 다음이 필요합니다.
Atlas 클러스터와 데이터베이스 사용자가 필요합니다. 이러한 항목을 생성하려면 Atlas 스트림 처리 시작하기를 참조하십시오.
A
sample_stream_solarsample connection in your connection registry. To add a sample connection, see Add an Atlas Stream Processing Connection.선택한 LLM 제공업체의 API 키입니다.
절차
Atlas 연결을 생성합니다.
In the Atlas UI, click Stream Processing in the sidebar, click Manage for your stream processing workspace, and select the Connection Registry tab.
+ Add Connection 버튼을 클릭합니다.
Connection Type 드롭다운 메뉴에서 Atlas Database 을 선택합니다.
Provide a Connection Name. This tutorial uses an Atlas connection named
AtlasConnection.From the dropdown menu, select the Atlas Cluster that stores the LLM responses.
Add connection를 클릭합니다.
LLM 제공업체에 HTTPS 연결을 생성하세요.
From the Connection Registry tab of your stream processing workspace, click the + Add Connection button.
Connection Type 드롭다운 메뉴에서 HTTPS 을 선택합니다.
Provide a Connection Name. This tutorial uses an HTTPS connection named
OpenAI.Populate the URL input field with the URL of your LLM API. This tutorial uses the OpenAI chat completions endpoint:
https://api.openai.com/v1/chat/completionsAPI 키를 사용하여 요청을 인증하는 헤더를 추가하세요. OpenAI의 경우 다음과 같은 헤더를 추가하십시오.
키:
Authorization값:
Bearer <your-api-key>
헤더 형식은 제공업체에 따라 다릅니다.
Create Connection를 클릭합니다.
Atlas 스트림 처리 파이프라인을 정의하십시오.
You can define the pipeline in mongosh after connecting to your stream processing workspace with your connection string.
Atlas 스트림 처리 파이프라인에서 데이터를 스트리밍할 소스를 정의합니다.
let source = { $source: { connectionName: "sample_stream_solar" }}Create a
$hoppingWindowstage in your pipeline to group multiple documents, which reduces the number of calls you make to the API.This example creates two
$groupstages in this pipeline stage:The first
$groupstage groups incoming documents bydevice_idand calculates the values shown below for each group.The second
$groupstage combines the resulting document for each device into a single array stored in a field calledallDocuments.
let hoppingWindow = { $hoppingWindow: { interval: { size: 30, unit: "second" }, hopSize: { size: 30, unit: "second" }, pipeline: [ { $group: { _id: "$device_id", max_temp: { $max: "$obs.temp" }, avg_watts: { $avg: "$obs.watts" }, median_watts: { $median: { input: "$obs.watts", method: "approximate" } }, max_watts: { $max: "$obs.watts" }, min_watts: { $min: "$obs.watts" }, count: { $count: {} } } }, { $group: { _id: { $meta: "stream.window.start" }, allDocuments: { $push: "$$CURRENT" } } } ] }}Prepare your data for LLM ingestion. The following stage filters out the
_idfield that the$hoppingWindowstage generates and defines a field calledpromptthat contains the array of grouped documents:let buildPrompt = { $project: { _id: 0, prompt: "$allDocuments" }}Convert the
promptarray into a string to send to the LLM. Thebodyfield of the $function expression must contain a function definition with named parameters:let stringifyPrompt = { $project: { prompt: { $function: { body: "function (prompt) { return JSON.stringify(prompt); }", args: ["$prompt"], lang: "js" } } }}Send the prompt to the LLM API in the
payloadof the HTTPS request:let llmAPICall = { $https: { connectionName: "OpenAI", method: "POST", as: "apiResults", config: { parseJsonStrings: true }, payload: [ { $project: { model: "gpt-6-luna", response_format: { type: "json_object" }, messages: [ { role: "system", content: "You are monitoring a fleet of solar devices. The user message is a JSON array with one entry per device for a 30-second window. Each entry has _id (the device_id), max_temp, avg_watts, median_watts, max_watts, min_watts, and count (the number of readings in the window). Identify devices whose output or temperature is unusual compared with the rest of the fleet in this window. Return JSON in this format: {\"anomalies\": [{\"device_id\": string, \"reason\": string, \"severity\": \"low\" | \"medium\" | \"high\"}], \"snark\": string}. Return an empty anomalies array if nothing is unusual. The snark field must always be present: one short, snarky remark about the fleet's performance in this window." }, { role: "user", content: "$prompt" } ] } } ] }}이전 단계에서는 다음과 같습니다.
This tutorial uses the
gpt-6-lunamodel. To use another model, replace themodelvalue. The model must support JSON mode, which theresponse_format: { type: "json_object" }field requests. JSON mode requires the prompt to contain the wordJSON, so keep that word if you modify the system prompt.시스템 프롬프트는 입력 필드를 설명하고 고정된 출력 형식을 정의하므로 파이프라인이 Atlas에 기록하는 문서의 형태는 실행 간에 일관성을 유지합니다.
The
config: { parseJsonStrings: true }setting parses JSON strings in the API response into objects, soapiResults.choices[0].message.contentreturns as an object instead of a JSON string.
LLM 응답을 Atlas 클러스터에 기록하세요.
let writeToAtlas = { $merge: { into: { connectionName: "AtlasConnection", db: "streamTutorialOutput", coll: "llm_tutorial_output" } }}After pasting each of the preceding snippets into
mongosh, paste the following snippet to combine all the stages you defined into a single Atlas Stream Processing pipeline definition:let processor = [ source, hoppingWindow, buildPrompt, stringifyPrompt, llmAPICall, writeToAtlas];
데드 레터 큐를 사용하여 스트림 프로세서를 생성하세요.
HTTPS 요청 실패와 같이 처리에 실패한 문서가 삭제되는 대신 오류 세부 정보와 함께 컬렉션에 기록되도록 데드 레터 큐 (DLQ)를 정의합니다.
let options = { dlq: { connectionName: "AtlasConnection", db: "streamTutorialOutput", coll: "llm_tutorial_dlq" }}파이프라인과 DLQ를 사용하여 스트림 프로세서를 생성하세요.
sp.createStreamProcessor("llm_stream", processor, options);
파이프라인을 검증합니다.
Run the following commands against the cluster that the AtlasConnection connection uses. To connect, see Connect to a Cluster via mongosh.
After a 30-second window completes, query the output collection:
db.getSiblingDB("streamTutorialOutput").llm_tutorial_output.findOne()In the returned document, verify that the
apiResults.choices[0].message.contentfield is an object, which confirms that the pipeline parsed and stored the LLM's JSON response. The object'sanomaliesarray contains the analysis result. An unusual device has adevice_id,reason, andseverity. An empty array means the LLM found no anomaly in that window. Also verify that thesnarkstring is present. The system prompt requires this field, so its presence confirms that the response follows the requested format.
출력 문서가 나타나지 않으면 데드 레터 큐에서 실패한 요청을 조회하십시오.
db.getSiblingDB("streamTutorialOutput").llm_tutorial_dlq.findOne()