Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:AI QL Tuui createCompletion

From Leeroopedia
Knowledge Sources
Domains LLM, Streaming, MCP, Sampling
Last Updated 2026-10-24 00:00 GMT

Overview

Concrete tool for building OpenAI-compatible chat completion requests, streaming LLM responses via SSE, and incrementally parsing content, reasoning, and tool calls, provided by the tuui Electron application.

Description

The createCompletion function is the core chat engine. It builds the request from the chatbot config (URL, model, headers with JWT token refresh), the agent's system prompt and selected MCP tools, sends a streaming fetch to the LLM API, and reads the response body incrementally. The read function splits SSE lines, parseJson/parseChoice extract deltas, parseMixedContent separates reasoning (think tags) from content, and parseTool merges incremental tool_call fragments. An AbortController is stored for cancellation. The sampling parameter path enables MCP sampling requests.

Usage

Import createCompletion when sending a chat message to the LLM. Import isEmptyTools when checking whether the assistant's response contains actionable tool calls. Use the sampling parameter when handling MCP server-initiated sampling requests.

Code Reference

Source Location

  • Repository: tuui
  • File: src/renderer/composables/chatCompletions.ts

Signature

export type ChatProcessResult = 'aborted' | 'error' | 'done'

export const createCompletion: (
  session: SessionEntry,
  sampling?: SamplingRequestParams
) => Promise<ChatProcessResult>

export const isEmptyTools: (tools: any) => boolean

// Internal (not exported):
async function read(
  reader: ReadableStreamDefaultReader<Uint8Array>,
  sessionId: string,
  target: AssistantMessage,
  buffer: string,
  stream: boolean
): Promise<void>

function parseJson(content: string, target: AssistantMessage): void
function parseChoice(choice: AssistantMessage | string, target: AssistantMessage): void
function parseMixedContent(chunk: string, target: AssistantMessage): void
function parseTool(tools: ToolCall[] | undefined, target: AssistantMessage): void

Import

import { createCompletion, isEmptyTools, type ChatProcessResult } from '@/renderer/composables/chatCompletions'

I/O Contract

Inputs

Name Type Required Description
session SessionEntry Yes Chat session with id and messages array
sampling SamplingRequestParams No MCP sampling params (messages, systemPrompt, temperature, maxTokens)
chatbotConfig ChatbotConfig Yes (from store) LLM provider config (url, model, apiKey, stream, etc.)

Outputs

Name Type Description
return ChatProcessResult 'done' if completed, 'aborted' if cancelled, 'error' on failure
side effect session.messages AssistantMessage pushed with content, reasoning_content, tool_calls
side effect messageStore.generating AbortController stored under session.id

Usage Examples

Send a Chat Completion Request

import { createCompletion } from '@/renderer/composables/chatCompletions'

// session has messages array from the message store
const result = await createCompletion(session)
if (result === 'done') {
  // Check if the assistant wants to call tools
  const lastMessage = session.messages.at(-1)
  if (!isEmptyTools(lastMessage.tool_calls)) {
    console.log('Tools requested:', lastMessage.tool_calls)
  }
}

Handle MCP Sampling Request

import { createCompletion } from '@/renderer/composables/chatCompletions'

// sampling comes from MCP server via IPC
const result = await createCompletion(
  session,
  {
    messages: [{ role: 'user', content: [{ type: 'text', text: 'Hello' }] }],
    systemPrompt: 'You are a helpful assistant.',
    temperature: 0.7,
    maxTokens: 1000
  }
)
// The assistant message from the LLM response is sent back as SamplingResponse

Parse Incremental Tool Calls

// parseTool merges streaming tool_call fragments:
// First chunk: { id: 'call_1', function: { name: 'read', arguments: '' } }
// Next chunk:  { id: 'call_1', function: { name: null, arguments: '{"path":' } }
// Next chunk:  { id: null, function: { name: null, arguments: ' "/tmp"}' } }
// Final tool_calls[0].function.arguments = '{"path": "/tmp"}'

Related Pages

Implements Principle

Uses Heuristic

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment