When the Responses API path is selected for newer OpenAI models
(gpt-5.x, o1, o3, o4) and an extra kwarg of `max_completion_tokens`
flows in (typically from `get_token_limit_kwargs(model, n)`), the
OpenAI SDK raises `TypeError` from `responses.create()` before any
HTTP request leaves the client.
`_should_fallback_from_responses_error()` only catches HTTP errors
that carry a `status_code`, so the call is never retried via Chat
Completions; the user just sees a stack trace. The bug exists on
both OpenAICompatProvider and AzureOpenAIProvider, in the chat and
chat_stream paths (4 sites total).
Add `adapt_chat_kwargs_to_responses()` that translates the alias to
`max_output_tokens` and is used at all four merge sites. The helper:
- preserves the existing `None`-drop semantics of the previous
dict-comprehension merge,
- only applies the alias when `max_output_tokens` is not explicitly
set by the caller,
- does not mutate the input.
Closes#437.
get_llm_config() prefers the resolver path over .env, so the env var
was silently ignored. Apply it as an override regardless of which path
produced the config.
- Read LLM_REASONING_EFFORT from environment in config.py
- Pass config.reasoning_effort to chat_with_retry/chat_stream_with_retry
in both complete() and stream() (was previously dropped)
- Set to "low"/"medium"/"high" to enable thinking, leave empty to use
automatic detection based on reasoning_model_patterns
- Swap reasoning_content/reasoning fallback order in _parse() to match
the precedence used when extracting reasoning_content (per Copilot review)
- Add reasoning_content → content fallback in _parse_chunks() for both
provider_core and tutorbot providers
- Fix streaming path in factory.py: when only reasoning chunks are
emitted (no direct content), fall back to response.content so
downstream consumers receive non-empty responses
- Harden idea_agent against non-dict JSON payloads
DeepSeek models (v4-flash, reasoner, etc.) return the actual response in the
reasoning_content field while leaving content empty when thinking mode is
enabled. The _parse() method only fell back to m.reasoning (DashScope-style),
causing "LLM returned empty response" errors.
Also fix idea_agent to handle LLM responses that are JSON arrays instead of
objects with an "ideas" key.
Register Gemini as a first-class embedding provider with endpoint/env defaults, expose it in start_tour embedding selection, and add regression coverage for runtime resolution and wizard options
When TutorBot is connected to IM channels (e.g. Feishu, WeChat),
users can send images and other multimedia messages. These messages
are stored with content as an array of content-part objects rather
than a plain string. The frontend assumes content is always a string,
causing React Error #31 (Objects are not valid as a React child)
and rendering the chat page unusable.
Changes:
- Add normalizeMessageContent() utility to safely convert array/object
content to displayable strings
- Fix BotChatPage history parsing to handle non-string content
- Fix UnifiedChatContext hydrateMessages for non-string content
- Fix last_message display with truncation and type safety in
SessionList and HistorySessionPicker
- Normalize content to string and strip reasoning_content in backend
get_bot_history and get_recent_active_bots
Embedding endpoint URLs are now transparent end-to-end: Settings shows the
exact URL DeepTutor will POST to, legacy `/v1`-style bases are migrated to
full `/embeddings` / `/api/embed` URLs, the embedding client rejects
known-provider misconfigurations early, and OpenRouter routes through the
same exact-URL HTTP adapter as other providers.
LlamaIndex RAG now refreshes embedding state before initialize/search/add,
validates persisted vectors before retrieval, and reports invalid indexes
with `needs_reindex: true` instead of raw NumPy/`NoneType` errors.
Memory refresh strips `<think>` / `<thinking>` blocks from reasoning-model
output before writing PROFILE.md / SUMMARY.md, and existing memory files
self-repair on read.
Also fixes a Deep Solve runtime regression where `MainSolver` still passed
a stale `attachments` keyword to `SolverAgent.process()`.
Adds release notes (assets/releases/ver1-3-2.md) and updates README.
Made-with: Cursor
- Add nvidia_nim provider to the registry (is_gateway, detect_by_key_prefix=nvapi-,
detect_by_base_keyword=api.nvidia.com, default_api_base=https://integrate.api.nvidia.com/v1)
- Add supports_stream_options field to ProviderSpec (defaults True, preserves existing
provider behavior)
- Set supports_stream_options=False for nvidia_nim — NVIDIA NIM silently hangs when
stream_options={"include_usage": True} is sent, so we omit it for this provider
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Stability release after v1.3.0 covering safer RAG/KB routing, stronger
embedding validation, more reliable Docker/TutorBot restarts, Web UX
fixes, and Windows/encoding hardening. See assets/releases/ver1-3-1.md
for the full notes.
Made-with: Cursor
Generalises #368: adds an explicit per-model `send_dimensions` opt-in
exposed as a Settings UI toggle and an EMBEDDING_SEND_DIMENSIONS env var.
Tri-state semantics:
true -> always send (user knows their provider supports it)
false -> never send (e.g. Qwen text-embedding-v4 via litellm gateway
which returns HTTP 400 when `dimensions` is sent)
unset -> fall back to the text-embedding-3* heuristic from #368
Backend:
- Adapter base accepts `send_dimensions`; OpenAI-compatible adapter
decides via `_should_send_dimensions(model)` (replaces the hardcoded
startswith check from #368).
- ResolvedEmbeddingConfig / EmbeddingConfig carry the flag through.
- EnvStore reads/writes EMBEDDING_SEND_DIMENSIONS, dropping the line
entirely when empty so legacy `.env` files keep the Auto behaviour.
- ModelCatalogService syncs the flag from .env back into the catalog.
Frontend:
- Settings page shows a "Send dimensions" checkbox next to Dimension,
with an instant CSS-only info tooltip (replaces native `title` to
avoid the browser's ~1s delay). Disabling the toggle greys out the
Dimension input.
- New models default to send_dimensions=true.
- en/zh i18n strings added.
Tests (46 new cases, including the unit tests #368 marked added but
did not actually ship):
- adapter `_should_send_dimensions` tri-state + parametrized non-3 family
- httpx-mocked payload assertions for all four combinations
- runtime resolver: catalog wins over env, garbage values -> None
- env_store helpers + render_from_catalog + write skip-empty round-trip
- EmbeddingClient propagates the flag to the adapter config dict
Made-with: Cursor
The embedding adapter's retry mechanism was missing httpx.ConnectError,
causing immediate failure instead of retry when network connectivity
issues occur (e.g., TLS handshake failures, proxy connection issues).
This fix ensures that transient connection errors are retried with
exponential backoff, improving reliability during knowledge base
initialization.
Rebased onto dev (post-#348) and resolved two UI conflicts (`web/app/(workspace)/chat/[[...sessionId]]/page.tsx` drops the now-dead `replaySnapshot` helper; `web/components/chat/home/ChatMessages.tsx` switches the last-assistant action button from the old `RotateCcw`/Retry to `RefreshCcw`/Regenerate). Smoke tests green (199 passed) and all required checks pass.
Merging: adds a `regenerate` capability wired through CLI (`/regenerate` · `/retry`), WebSocket (`type: "regenerate"`), and Web UI (per-message Regenerate button). Backend rolls back the trailing assistant via `SQLiteSessionStore.delete_message`, reuses `start_turn` through `_persist_user_message=False` / `_regenerate=True`, skips `memory_service.refresh_from_turn` on regeneration, and surfaces non-fatal `regenerate_busy` / `nothing_to_regenerate` errors. Also includes empty-response diagnostics in `_stage_responding`. 18 new tests.
Rebased onto latest dev (post-#352) to pull in the lazy loguru import in `deeptutor/tutorbot/channels/manager.py`, which was the root cause of the smoke-test failures (unrelated to this PR's own diff).
Merging: adds per-stage `max_tokens` and `temperature` knobs under `capabilities.chat` in `agents.yaml`, bumps the `responding`/`answer_now` defaults from 1800 → 8000 to fix mid-sentence truncation on long answers, and keeps safe fallbacks in `_ChatLimits.from_config` for legacy configs. 10 new unit tests covering loader resolution and dataclass coercion.
Fixes#344
Gemma models served through LM Studio (and similar local inference
servers) reject response_format={\"type\": \"json_object\"}, returning a
400 error: \"'response_format.type' must be 'json_schema' or 'text'\".
Add supports_response_format: False to the existing 'gemma' MODEL_OVERRIDES
entry so these models are excluded from the json_object path. The
existing extract_json_object utilities in the visualize and math-animator
agents already parse JSON from plain text responses, so all callers
continue to work without further changes.
Co-authored-by: octo-patch <octo-patch@users.noreply.github.com>
Fixes#346
When an embedding provider returns null for a chunk's embedding vector,
the None value gets stored in the vector index and causes a TypeError
in LlamaIndex's similarity computation (np.dot with NoneType).
Two-layer fix:
1. _extract_embeddings_from_response: use 'or []' instead of
get(key, default) so explicit None values are caught.
2. CustomEmbedding._get_text_embeddings: validate the batch result
and replace any None vectors with zero vectors.
Co-authored-by: kagura-agent <kagura-agent@users.noreply.github.com>
Resolved conflicts in:
- deeptutor/agents/notebook/summarize_agent.py
Kept the YAML-driven record_hints lookup from dev (covers chat,
co_writer, guided_learning, default), instead of the inline
dict from guide2.0 which only had chat + co_writer.
- deeptutor/capabilities/visualize.py
Kept dev's load_answer_now_prompts(...) path so the answer-now
fast path stays prompt-externalised under
deeptutor/agents/visualize/prompts/{en,zh}/answer_now.yaml.
- deeptutor/services/prompt/manager.py
Merged the MODULES list: dropped 'guide' (deleted by guide2.0),
added 'book' from guide2.0, and kept dev's 'notebook',
'visualize', 'chat' modules.
Made-with: Cursor
- Move inline LLM prompts out of capabilities/agents into versioned
prompt YAMLs under each agent's prompts/{en,zh}/:
- notebook: analysis_agent, summarize_agent
- question/research/solve/visualize: answer_now
- Slim down capability modules (_answer_now, deep_question,
deep_research, deep_solve, visualize) to load prompts via the
prompt manager instead of hard-coding strings
- Update services/prompt/manager.py to support the new prompt paths
- Refresh web config panels (quiz, research, visualize, math-animator)
and shared types to align with the new capability options
- Update Mermaid, ChatMessages, TracePanels and settings page,
plus en/zh locales for the new copy
Made-with: Cursor
* TutorBot Channels tab is now schema-driven across every built-in & plugin channel
(GET /api/v1/tutorbot/channels/schema), with per-field secret reveal toggles.
* Channel secrets are masked end-to-end; raw values only surface via the explicit
?include_secrets=true edit-form route. PATCH validates ChannelsConfig at the API
boundary and returns 422 on bad payloads. reload_channels is serialised by an
asyncio.Lock and records last_reload_error for the UI.
* Collapsed services/rag/ to a single LlamaIndex pipeline: removed ~2.6k lines of
unused components/* + pipeline.py + types.py + utils/ + parsers/. rag_provider
is now a stub; legacy values silently coerce to llamaindex.
* Centralised file routing into services/rag/file_routing.py (FileTypeRouter /
DocumentType / FileClassification); dropped per-provider extension helpers.
* Defensive RAG/KB consistency: deep_solve / deep_research strip rag/kb when no
KB is attached; SolveToolRuntime + ResearchPipeline + DecomposeAgent
short-circuit instead of falling back to non-existent default KBs (DE-all,
ai_textbook).
* Externalised AgenticChatPipeline prompts into agentic_chat.yaml (zh + en).
* Added Thai README (#337).
* New test modules: file_routing, knowledge_base_config, channel_schema,
channel_secrets, rag_consistency, research_pipeline_rag.
Full notes: assets/releases/ver1-1-2.md
Made-with: Cursor
Closes#227. Auth is disabled by default (AUTH_ENABLED=false) so
localhost usage is unaffected. Set AUTH_ENABLED=true +
NEXT_PUBLIC_AUTH_ENABLED=true to require login when hosting publicly.
Backend
- New deeptutor/services/auth.py: bcrypt password hashing, JWT
create/decode, multi-user JSON store with role + created_at schema,
auto-migration of old flat-hash format, first-user → admin bootstrap
- New deeptutor/api/routers/auth.py: require_auth / require_admin
FastAPI dependencies; public endpoints /login /logout /status
/register /is_first_user; admin-only /users /users/{u}/role
- deeptutor/api/main.py: Depends(require_auth) applied to all 14
protected routers
- deeptutor/api/routers/unified_ws.py: cookie-based JWT check before
ws.accept() when AUTH_ENABLED
- Added bcrypt>=4.0.0 and python-jose[cryptography]>=3.3.0 to
requirements/server.txt and pyproject.toml extras
Frontend
- web/middleware.ts: route protection; /login and /register are public
- web/lib/api.ts: apiFetch wrapper — credentials:include + 401→login
- web/lib/auth.ts: login/logout/fetchAuthStatus + register() +
checkIsFirstUser()
- web/lib/admin-api.ts: listUsers / deleteUser / setUserRole
- web/lib/session-api.ts: credentials:include on all fetches;
expectJson redirects to /login on 401 instead of throwing
- web/app/(auth)/login/page.tsx: auto-redirects to /register when no
users exist; shows success banner after registration
- web/app/(auth)/register/page.tsx: new registration page with
first-user admin notice and password confirmation
- web/app/(admin)/admin/users/page.tsx: admin dashboard — user table
with role toggle and delete; guards against self-demotion/deletion
- AdminLink and LogoutButton hidden when AUTH_ENABLED=false
- .env.example and README.md updated with auth vars and setup guide
Made-with: Cursor
- Promote "Answer now" to a universal escape hatch via answer_now_context;
orchestrator re-routes any capability to chat._stage_answer_now.
- Co-Writer: draggable split + persistent ratio + line-anchored
bidirectional scroll sync using a hidden mirror for wrap-aware editor y.
- SaveToNotebookModal: optional message-selection mode with quick presets;
rebuild transcript / userQuery from the selected subset.
- Adopt the real notebook API (/api/v1/notebook/*) across Knowledge tab,
guide notebook picker, and save-to-notebook flow; new typed helpers in
web/lib/notebook-api.ts (listNotebooks/getNotebook/createNotebook/...).
- Extract CollapsibleConfigSection; unify Quiz / Math Animator / Visualize
/ Deep Research panels behind one collapsed-summary header.
- Replace streaming spinner with a dedicated Stop button; persistent
composer header; mask-gradient on messages container.
- TutorBotManager: public load/save/merge API; atomic write via temp +
Path.replace; merge_bot_config with explicit-clear semantics; new
tests/services/tutorbot/test_manager_config.py.
- MarkdownRenderer: trackSourceLines passes data-source-line through;
RichCodeBlock skips Prism for unlabeled/plaintext fences; mermaid
detection includes flow/seq/sequence editor.md fences.
- UI/theme: deeper foregrounds + warmer borders for light/Snow themes;
/guide migrated off hardcoded slate/indigo to design tokens;
HistorySessionPicker themed and timestamp-seconds bug fixed.
- Filter system messages out of UnifiedChatContext.hydrateMessages and
ChatMessageList so backend grounding context never renders as a bubble.
- Bug fixes (already merged earlier in dev):
* tutorbot config wipe on restart (#332)
* selective_access_log middleware unpack crash (#334/#335)
* 15 npm security vulnerabilities — jspdf/next/mermaid (#330)
- Drive-by: remove "// README" typo from .env.example_CN.
- Add v1.1.1 release notes and update README.
Made-with: Cursor
The Settings → LLM diagnostic hardcoded max_tokens=200. Reasoning-capable
models (minimax-m2, o1, Gemini thinking) spend most of that budget on
internal thinking tokens and return empty visible content, which the
probe then reports as "LLM returned an empty response" even though the
API call succeeded.
Read the budget from LLM_TEST_MAX_TOKENS with a 1024 default (falls back
on non-numeric values). Documented in .env.example and plumbed through
docker-compose.yml.