对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

从流处理管道调用 LLM

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.

要完成本教程,您需要:

1
  1. In the Atlas UI, click Stream Processing in the sidebar, click Manage for your stream processing workspace, and select the Connection Registry tab.

  2. 单击 + Add Connection 按钮。

  3. 从Connection Type下拉菜单中选择Atlas Database 。

  4. Provide a Connection Name. This tutorial uses an Atlas connection named AtlasConnection.

  5. From the dropdown menu, select the Atlas Cluster that stores the LLM responses.

  6. 单击 Add connection(连接)。

2
  1. From the Connection Registry tab of your stream processing workspace, click the + Add Connection button.

  2. 从Connection Type下拉菜单中选择HTTPS 。

  3. Provide a Connection Name. This tutorial uses an HTTPS connection named OpenAI.

  4. 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/completions
  5. 添加一个用于使用 API 密钥验证请求的请求头。对于 OpenAI,请添加以下请求头:

    • 关键: Authorization

    • 值: Bearer <your-api-key>

    不同提供商的邮件头格式各不相同。

  6. 单击 Create Connection(连接)。

3

You can define the pipeline in mongosh after connecting to your stream processing workspace with your connection string.

  1. 在 Atlas 流处理管道中,定义要从中流式传输数据的源:

    let source = { $source: { connectionName: "sample_stream_solar" }}
  2. Create a $hoppingWindow stage in your pipeline to group multiple documents, which reduces the number of calls you make to the API.

    This example creates two $group stages in this pipeline stage:

    • The first $group stage groups incoming documents by device_id and calculates the values shown below for each group.

    • The second $group stage combines the resulting document for each device into a single array stored in a field called allDocuments.

    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" } } } ] }}
  3. Prepare your data for LLM ingestion. The following stage filters out the _id field that the $hoppingWindow stage generates and defines a field called prompt that contains the array of grouped documents:

    let buildPrompt = { $project: { _id: 0, prompt: "$allDocuments" }}
  4. Convert the prompt array into a string to send to the LLM. The body field 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" } } }}
  5. Send the prompt to the LLM API in the payload of 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-luna model. To use another model, replace the model value. 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 config: { parseJsonStrings: true } 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.

  6. 将 LLM 响应写入 Atlas 集群:

    let writeToAtlas = { $merge: { into: { connectionName: "AtlasConnection", db: "streamTutorialOutput", coll: "llm_tutorial_output" } }}
  7. 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];
4
  1. 定义一个死信队列(DLQ),以便将处理失败的文档(例如失败的 HTTPS 请求)连同错误详细信息一起写入集合,而不是直接丢弃:

    let options = { dlq: { connectionName: "AtlasConnection", db: "streamTutorialOutput", coll: "llm_tutorial_dlq" }}
  2. 使用管道和死信队列创建流处理器:

    sp.createStreamProcessor("llm_stream", processor, options);
5
sp.llm_stream.start();
6

Run the following commands against the cluster that the AtlasConnection connection uses. To connect, see Connect to a Cluster via mongosh.

  1. After a 30-second window completes, query the output collection:

    db.getSiblingDB("streamTutorialOutput").llm_tutorial_output.findOne()
  2. In the returned document, verify that the apiResults.choices[0].message.content field is an object, which confirms that the pipeline parsed and stored the LLM's JSON response. The object's anomalies array contains the analysis result. An unusual device has a device_id, reason, and severity. An empty array means the LLM found no anomaly in that window. Also verify that the snark string 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()