Coverage for app / router / app / knowledge / setup.py: 96%
387 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2Generative knowledge setup.
4A sibling of skillsets/setup.py and toolkits/setup.py, scoped to the
5knowledge side of the platform: describe what an agent needs to know, and
6get back a proposed **repository** — the unit agents actually integrate —
7together with the **sources** that belong in it, built on real material.
9POST /app/knowledge/generate — open a ``running`` run and start
10 it in the background (``services/knowledge/generation_job.py``): plan
11 web searches, run them, check what they found, then design the
12 repository on those candidates. Returns at once (202).
13GET /app/knowledge/generate/{id} — where the run is, and once it is
14 ``proposed``, its proposal for review in the frontend wizard.
15POST /app/knowledge/create-from-config — persist a reviewed proposal in a
16 single transaction: repository, sources and junction rows. A website
17 source keeps its checked URLs and starts crawling once committed; a
18 file source's documents are imported from their links in the
19 background (``services/knowledge/imports.py``).
21Finding sources for knowledge that exists or was already proposed runs the
22same discovery (flow ``source_discovery``) and assigns what it finds to the
23given sources instead of designing new ones:
25POST /app/knowledge/discover — for sources not yet created (the
26 agent wizard's proposed website and file sources);
27POST /app/knowledge/{id}/discover — for an existing source ("Find
28 sources" on its page);
29GET /app/knowledge/discover/{id} — where it is, then what it found;
30POST /app/knowledge/{id}/discover/{run}/apply — give an existing source the
31 links the person kept, and crawl or import them.
33Three constraints shape this flow.
35**An address is never a model's.** Discovery finds and checks what is on
36the web; the design chooses among the candidates by index, and svc-core maps
37them back to its own copy (``knowledge/candidates.py``). A connection string
38or an API endpoint is never proposed at all — those sources stay stubs. The
39review is editable, and a person may add their own links: re-validated here
40as a hand-made source's are.
42**It runs in the background.** Searching and checking take longer than a
43request may (svc-bff and Cloudflare cut long ones), so the person polls a
44run that records its stage; the proposal is kept on the run, so a reload or
45another tab comes back to it.
47**The repository is optional.** ``want_repository=False`` is the Sources
48entry point in the frontend: loose sources, no grouping. The run is still
49recorded, and the created sources are still tagged with it; there is simply
50no repository to point ``target_resource_id`` at, so it names the first
51source instead.
52"""
54import logging
55from typing import Any, Literal
56from uuid import UUID, uuid4
58from fastapi import APIRouter, Depends, HTTPException, status
59from pydantic import BaseModel, Field, field_validator, model_validator
60from sqlalchemy.exc import IntegrityError
61from sqlalchemy.orm import Session
63from app.db.postgres.crud_schemas import Schema
64from app.db.postgres.enums import GenerationEnum, HistoryEnum
65from app.db.postgres.models import (
66 GenerationRun,
67 Knowledge,
68 KnowledgeRepository,
69 RepositoryKnowledge,
70 User,
71)
72from app.dependency.base import get_db
73from app.dependency.resource_access import (
74 verify_change_here,
75 verify_resource_access,
76 verify_resource_read,
77)
78from app.dependency.user.context import get_current_user
79from app.dependency.workspace import owner_for, request_workspace
80from app.router.app.agents.setup import (
81 GenerationModelInfo,
82 _resolve_generation_model,
83)
84from app.router.app.repositories.router import _with_members
85from app.services.knowledge import repositories
86from app.services.knowledge.repositories import (
87 CategoryConflict,
88 repository_children_snapshot,
89 require_one_category,
90)
91from app.services import appearance
92from app.services import generation as generation_service
93from app.services import history as history_service
94from app.services.ai_client import AIServiceError
95from app.services.knowledge import generation_job, source_links, source_types
96from app.services.knowledge.candidates import Candidate
97from app.services.workspace import in_scope
98from app.util import knowledge_categories
99from app.util.knowledge_categories import KnowledgeCategory
100from app.util.time import aware_utcnow, utc_isoformat
102logger = logging.getLogger(__name__)
104knowledge_setup_router = APIRouter(prefix="/knowledge", tags=["App - Knowledge Setup"])
106#: The source types a generated source may claim live in
107#: ``app.services.knowledge.source_types`` — shared with agent setup, and sent
108#: to svc-ai with their descriptions. Anything else is clamped to the default.
109DEFAULT_SOURCE_TYPE = source_types.DEFAULT_SOURCE_TYPE
111#: Cap on how many sources one invocation may propose (the job's).
112MAX_PROPOSED_KNOWLEDGE = generation_job.MAX_PROPOSED_KNOWLEDGE
115def _source_type(value: Any) -> str:
116 return source_types.clamp(value)
119# ---------------------------------------------------------------------------
120# Request / response models
121# ---------------------------------------------------------------------------
124#: The shortest description a generation is asked from.
125MIN_DESCRIPTION = 20
128class GenerateKnowledgeRequest(BaseModel):
129 #: What the knowledge is for. Optional with ``from_turns``, whose
130 #: questions describe it; anything written here is added to them.
131 problem_description: str = Field(default="", max_length=4000)
132 #: The caller's own answers in this workspace whose questions the
133 #: knowledge is for (a recommendation's "Generate from these questions",
134 #: ``services/knowledge/recommendations``). svc-core composes the
135 #: description from their words as the retrieval record kept them.
136 from_turns: list[UUID] = Field(default_factory=list, max_length=20)
137 ai_model_id: UUID | None = None
138 #: False asks for sources alone — the Sources entry point in fe-core.
139 want_repository: bool = True
140 #: What kind of knowledge to find (``app/util/knowledge_categories.py``):
141 #: what discovery looks for, which existing sources may join it, and the
142 #: kind of the repository created.
143 category: KnowledgeCategory = knowledge_categories.DEFAULT
145 @model_validator(mode="after")
146 def _described(self) -> "GenerateKnowledgeRequest":
147 if (
148 not self.from_turns
149 and len(self.problem_description.strip()) < MIN_DESCRIPTION
150 ):
151 raise ValueError(
152 f"Describe what the knowledge is for in {MIN_DESCRIPTION} "
153 "characters or more."
154 )
155 return self
158class ProposedKnowledgeInfo(BaseModel):
159 """A proposed source: what it holds, and — for a website or a file
160 source — the checked links it was given (``knowledge/candidates.py``)."""
162 name: str
163 description: str = ""
164 source_type: str = DEFAULT_SOURCE_TYPE
165 #: A website source's pages and feeds, crawled and kept current.
166 pages: list[Candidate] = []
167 #: A file source's documents, downloaded and kept.
168 documents: list[Candidate] = []
169 #: A website source's crawl scope and cadence; None for the defaults.
170 scope: str | None = None
171 refresh: str | None = None
173 @field_validator("source_type")
174 @classmethod
175 def _validate_source_type(cls, v: str) -> str:
176 return _source_type(v)
179class KnowledgeGenerationProposal(BaseModel):
180 #: Empty when the caller asked for sources without a repository.
181 repository_name: str = ""
182 repository_description: str = ""
183 #: The kind of knowledge it was asked for: the repository's category.
184 category: KnowledgeCategory = knowledge_categories.DEFAULT
185 icon: str = appearance.DEFAULT_REPOSITORY_ICON
186 accent: str = appearance.DEFAULT_ACCENT
187 reasoning: str = ""
188 selected_knowledge: list[Schema.Knowledge.Read] = []
189 proposed_knowledge: list[ProposedKnowledgeInfo] = []
190 #: Everything discovery found and checked, the chosen and the rest — the
191 #: review offers what no source took ("Also found").
192 candidates: list[Candidate] = []
193 warnings: list[str] = []
194 model: GenerationModelInfo
195 # Echoed back on create-from-config; see app.services.generation.
196 generation_id: UUID
199class KnowledgeGenerationStarted(BaseModel):
200 generation_id: UUID
201 status: GenerationEnum.Status
202 stage: str
205class KnowledgeGenerationStatus(BaseModel):
206 """Where a background knowledge generation is."""
208 generation_id: UUID
209 status: GenerationEnum.Status
210 #: queued | planning | searching | checking | designing | done | failed
211 stage: str | None = None
212 #: Counts so far — searches planned, results found, candidates usable.
213 progress: dict = {}
214 #: Once ``proposed`` (or ``applied``): what to review.
215 proposal: KnowledgeGenerationProposal | None = None
216 #: Once ``failed``: why, safe to show.
217 error: str | None = None
220class NewKnowledgeInput(source_links.SourceLinks):
221 """A source to create. A website source may bring the URLs it crawls,
222 and a file source the documents it imports — each the person's to
223 review, add to or remove, and validated as a hand-made source's are
224 (``knowledge/source_links.py``). A database's or an API's connection
225 details are never taken here."""
227 name: str
228 description: str = ""
229 source_type: str = DEFAULT_SOURCE_TYPE
231 @field_validator("source_type")
232 @classmethod
233 def _validate_source_type(cls, v: str) -> str:
234 return _source_type(v)
236 @model_validator(mode="after")
237 def _only_what_the_type_holds(self) -> "NewKnowledgeInput":
238 self.only_for(self.source_type)
239 return self
242class CreateKnowledgeFromConfigRequest(BaseModel):
243 #: Empty (or omitted) creates the sources without grouping them.
244 repository_name: str = ""
245 repository_description: str = ""
246 icon: str = appearance.DEFAULT_REPOSITORY_ICON
247 accent: str = appearance.DEFAULT_ACCENT
248 #: What kind of knowledge the repository holds.
249 repository_category: KnowledgeCategory = knowledge_categories.DEFAULT
250 existing_knowledge_ids: list[UUID] = []
251 new_knowledge: list[NewKnowledgeInput] = []
252 generation_id: UUID | None = None
254 @field_validator("icon")
255 @classmethod
256 def _validate_icon(cls, v: str) -> str:
257 return appearance.repository_icon(v)
259 @field_validator("accent")
260 @classmethod
261 def _validate_accent(cls, v: str) -> str:
262 return appearance.accent(v)
265class CreateKnowledgeFromConfigResponse(BaseModel):
266 #: Null when the request created loose sources with no repository.
267 repository: Schema.KnowledgeRepository.ReadWithMembers | None = None
268 created_knowledge_ids: list[UUID] = []
269 #: The website sources whose first crawl started.
270 crawls_started: list[UUID] = []
271 #: How many documents are being imported into the file sources.
272 imports_queued: int = 0
275# ---------------------------------------------------------------------------
276# Generate — in the background
277# ---------------------------------------------------------------------------
279#: What a person reads about a run whose worker went with a restart.
280STOPPED = "The generation stopped reporting — the service restarted. Generate again."
283def _running_run(db: Session, current_user: User) -> GenerationRun | None:
284 """This person's knowledge generation still working in this workspace,
285 if any — one at a time."""
286 query = db.query(GenerationRun).filter(
287 GenerationRun.flow == GenerationEnum.Flow.knowledge_setup,
288 GenerationRun.status == GenerationEnum.Status.running,
289 GenerationRun.actor_user_id == current_user.id,
290 )
291 ws = request_workspace(db, current_user)
292 if ws is not None:
293 query = query.filter(ws.made_here(GenerationRun))
294 return next(
295 (run for run in query.all() if not generation_service.is_stale(run)), None
296 )
299@knowledge_setup_router.post(
300 "/generate",
301 response_model=KnowledgeGenerationStarted,
302 status_code=status.HTTP_202_ACCEPTED,
303)
304def generate_knowledge(
305 body: GenerateKnowledgeRequest,
306 db: Session = Depends(get_db),
307 current_user: User = Depends(get_current_user),
308):
309 """Start designing a repository and its sources (creates nothing yet).
311 Returns at once: the work runs in the background, and ``GET
312 /knowledge/generate/{id}`` says where it is. A second generation while
313 one is running is a 409 naming it, so another tab picks it up rather
314 than paying twice. With ``from_turns`` the description is composed from
315 those questions — the caller's own here only, else a 422.
316 """
317 if body.from_turns:
318 from app.services.knowledge import recommendations
320 try:
321 described = recommendations.describe_from_turns(
322 db,
323 request_workspace(db, current_user),
324 current_user,
325 body.from_turns,
326 body.problem_description,
327 )
328 except recommendations.UnknownTurns as exc:
329 raise HTTPException(
330 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)
331 ) from exc
332 body = body.model_copy(update={"problem_description": described})
333 try:
334 model_info = _resolve_generation_model(body.ai_model_id)
335 except AIServiceError as exc:
336 logger.error("Could not resolve a knowledge generation model: %s", exc)
337 run = generation_service.start(
338 db,
339 flow=GenerationEnum.Flow.knowledge_setup,
340 actor=current_user,
341 arguments=body.model_dump(),
342 )
343 generation_service.fail(db, run, error=str(exc))
344 db.commit()
345 raise HTTPException(
346 status_code=status.HTTP_502_BAD_GATEWAY,
347 detail="No model is available to design the knowledge.",
348 ) from exc
350 running = _running_run(db, current_user)
351 if running is not None:
352 raise HTTPException(
353 status_code=status.HTTP_409_CONFLICT,
354 detail={
355 "message": "A knowledge generation is already running.",
356 "generation_id": str(running.id),
357 },
358 )
360 run = generation_service.start(
361 db,
362 flow=GenerationEnum.Flow.knowledge_setup,
363 actor=current_user,
364 arguments=body.model_dump(),
365 model_info=model_info,
366 status=GenerationEnum.Status.running,
367 progress={
368 "stage": generation_job.Stage.queued.value,
369 "updated_at": utc_isoformat(aware_utcnow()),
370 },
371 )
372 db.commit()
373 generation_job.submit(run.id)
374 return KnowledgeGenerationStarted(
375 generation_id=run.id,
376 status=run.status,
377 stage=generation_job.Stage.queued.value,
378 )
381def _proposal(db: Session, run: GenerationRun) -> KnowledgeGenerationProposal | None:
382 """The run's stored proposal, its selected sources read again — scoped to
383 the run's workspace, so a stored id never reaches another's."""
384 stored = run.proposal if isinstance(run.proposal, dict) else None
385 if stored is None:
386 return None
387 ids = []
388 for raw in stored.get("selected_knowledge_ids") or []:
389 try:
390 ids.append(UUID(str(raw)))
391 except ValueError:
392 continue
393 selected: list[Knowledge] = []
394 if ids:
395 ws = generation_service.made_in(db, run)
396 query = db.query(Knowledge).filter(Knowledge.id.in_(ids))
397 if ws is not None:
398 query = query.filter(in_scope(Knowledge, ws, system=False))
399 selected = query.all()
400 return KnowledgeGenerationProposal(
401 **{
402 k: v
403 for k, v in stored.items()
404 if k not in {"selected_knowledge_ids", "model"}
405 },
406 selected_knowledge=[
407 Schema.Knowledge.Read.model_validate(k, from_attributes=True)
408 for k in selected
409 ],
410 warnings=list(run.warnings or []),
411 model=GenerationModelInfo(**(stored.get("model") or {})),
412 generation_id=run.id,
413 )
416@knowledge_setup_router.get(
417 "/generate/{generation_id}", response_model=KnowledgeGenerationStatus
418)
419def knowledge_generation_status(
420 generation_id: UUID,
421 db: Session = Depends(get_db),
422 current_user: User = Depends(get_current_user),
423):
424 """Where the caller's knowledge generation is, and once it has one, its
425 proposal. Only the person who started it reads it (404 otherwise)."""
426 run = _own_run(db, generation_id, current_user, GenerationEnum.Flow.knowledge_setup)
427 _settle_stale(db, run)
428 return KnowledgeGenerationStatus(
429 **_where(run),
430 proposal=_proposal(db, run) if _has_proposal(run) else None,
431 )
434def _own_run(
435 db: Session, generation_id: UUID, user: User, flow: GenerationEnum.Flow
436) -> GenerationRun:
437 """The caller's run of ``flow``; 404 for anyone else's, or another flow's."""
438 run = db.get(GenerationRun, generation_id)
439 if run is None or run.flow != flow or run.actor_user_id != user.id:
440 raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
441 return run
444def _settle_stale(db: Session, run: GenerationRun) -> None:
445 """A run that stopped reporting went with its worker: failed, saying so."""
446 if generation_service.is_stale(run):
447 generation_service.fail(db, run, error="stale: no progress reported")
448 generation_service.record_progress(run, "failed", message=STOPPED)
449 db.commit()
452def _has_proposal(run: GenerationRun) -> bool:
453 return run.status in (
454 GenerationEnum.Status.proposed,
455 GenerationEnum.Status.applied,
456 )
459def _where(run: GenerationRun) -> dict:
460 """A background run's status fields: its stage, its counts, and a safe
461 reason once it failed."""
462 progress = dict(run.progress or {})
463 failed = run.status == GenerationEnum.Status.failed
464 return {
465 "generation_id": run.id,
466 "status": run.status,
467 "stage": progress.get("stage"),
468 "progress": {
469 k: v for k, v in progress.items() if k not in {"stage", "message"}
470 },
471 "error": (progress.get("message") or generation_job.UNEXPECTED)
472 if failed
473 else None,
474 }
477# ---------------------------------------------------------------------------
478# Create from a reviewed proposal
479# ---------------------------------------------------------------------------
482@knowledge_setup_router.post(
483 "/create-from-config",
484 response_model=CreateKnowledgeFromConfigResponse,
485 status_code=status.HTTP_201_CREATED,
486)
487def create_knowledge_from_config(
488 body: CreateKnowledgeFromConfigRequest,
489 db: Session = Depends(get_db),
490 current_user: User = Depends(get_current_user),
491):
492 """Persist a reviewed knowledge generation proposal atomically; then
493 start each website source's first crawl and each file source's imports."""
494 repository_name = body.repository_name.strip()
495 if not repository_name and not body.new_knowledge:
496 raise HTTPException(
497 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
498 detail=(
499 "Nothing to create — include at least one new source, or a "
500 "repository name to group the selected ones under."
501 ),
502 )
504 # Verify referenced existing resources up front (outside the write path).
505 existing_knowledge: list[Knowledge] = []
506 for knowledge_id in body.existing_knowledge_ids:
507 kb = db.get(Knowledge, knowledge_id)
508 if not kb:
509 raise HTTPException(
510 status_code=status.HTTP_404_NOT_FOUND,
511 detail=f"Knowledge base {knowledge_id} not found",
512 )
513 verify_resource_access(kb, current_user, db)
514 existing_knowledge.append(kb)
516 if not repository_name and body.existing_knowledge_ids:
517 raise HTTPException(
518 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
519 detail=(
520 "Existing knowledge bases can only be included when a "
521 "repository groups them — they already exist on their own."
522 ),
523 )
524 try:
525 require_one_category(
526 db,
527 body.repository_category,
528 [kb.id for kb in existing_knowledge],
529 viewer=current_user,
530 )
531 except CategoryConflict as conflict:
532 raise conflict.http() from None
534 # A website source's config, validated as a hand-made one is.
535 configs: list[dict] = []
536 for k in body.new_knowledge:
537 try:
538 configs.append(
539 source_links.config_for(
540 k.source_type, k, category=body.repository_category
541 )
542 )
543 except ValueError as exc:
544 raise HTTPException(
545 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
546 detail=f"'{k.name}': {exc}",
547 ) from exc
549 run = generation_service.resolve(db, body.generation_id, current_user)
550 if run is not None and run.status != GenerationEnum.Status.proposed:
551 # Still running, already applied or failed: nothing to apply.
552 run = None
554 repository: KnowledgeRepository | None = None
555 imported: list[Any] = []
556 try:
557 new_knowledge_rows = [
558 Knowledge(
559 id=uuid4(),
560 name=k.name,
561 description=k.description,
562 source_type=k.source_type,
563 source_config=config,
564 **owner_for(db, current_user, model=Knowledge),
565 )
566 for k, config in zip(body.new_knowledge, configs)
567 ]
568 created_rows: list[Any] = [*new_knowledge_rows]
570 if repository_name:
571 repository = KnowledgeRepository(
572 id=uuid4(),
573 name=repository_name,
574 description=body.repository_description,
575 icon=body.icon,
576 accent=body.accent,
577 category=body.repository_category.value,
578 **owner_for(db, current_user, model=KnowledgeRepository),
579 )
580 created_rows.insert(0, repository)
582 generation_service.stamp(created_rows, run)
583 # stamp() only sets the flag when there is a run to point at; this
584 # endpoint only ever persists generated output, so the flag holds
585 # even for a client that did not echo an id back.
586 for row in created_rows:
587 row.is_ai_generated = True
588 db.add_all(created_rows)
589 db.flush()
591 # Each file source's documents, as rows importing from their links;
592 # downloaded once this commits.
593 documents_of: dict[Any, list[Any]] = {}
594 for kb, k in zip(new_knowledge_rows, body.new_knowledge):
595 docs, _ = source_links.import_placeholders(db, kb, k, existing=False)
596 documents_of[kb.id] = docs
597 imported.extend(docs)
599 if repository is not None:
600 member_ids = {kb.id for kb in existing_knowledge} | {
601 k.id for k in new_knowledge_rows
602 }
603 for knowledge_id in member_ids:
604 db.add(
605 RepositoryKnowledge(
606 repository_id=repository.id, knowledge_id=knowledge_id
607 )
608 )
610 # Same "build then add_all" shape as skillset create-from-config: the
611 # created version is the first entry in each resource's audit trail,
612 # and inherits generation_id from the row it documents.
613 versions = [
614 history_service.build_version(
615 db,
616 resource_type=HistoryEnum.ResourceType.knowledge,
617 model=Knowledge,
618 resource=kb,
619 action=HistoryEnum.Action.created,
620 actor=current_user,
621 children_resolver=lambda kb_id=kb.id: source_links.documents_snapshot(
622 documents_of.get(kb_id, [])
623 ),
624 )
625 for kb in new_knowledge_rows
626 ]
627 if repository is not None:
628 repository_id = repository.id
629 versions.insert(
630 0,
631 history_service.build_version(
632 db,
633 resource_type=HistoryEnum.ResourceType.knowledge_repository,
634 model=KnowledgeRepository,
635 resource=repository,
636 action=HistoryEnum.Action.created,
637 actor=current_user,
638 children_resolver=lambda: repository_children_snapshot(
639 db, repository_id
640 ),
641 ),
642 )
643 db.add_all(versions)
645 # A sources-only run has no repository to name, so it points at the
646 # first source it created rather than losing the link entirely.
647 if repository is not None:
648 generation_service.apply(
649 db,
650 run,
651 target_resource_type=HistoryEnum.ResourceType.knowledge_repository,
652 target_resource_id=repository.id,
653 )
654 elif new_knowledge_rows:
655 generation_service.apply(
656 db,
657 run,
658 target_resource_type=HistoryEnum.ResourceType.knowledge,
659 target_resource_id=new_knowledge_rows[0].id,
660 )
662 db.commit()
663 except IntegrityError:
664 db.rollback()
665 raise HTTPException(
666 status_code=status.HTTP_409_CONFLICT,
667 detail=(
668 "A resource with a conflicting name already exists "
669 f"(repository '{repository_name}' or one of the new sources). "
670 "Rename it and try again."
671 ),
672 )
673 except Exception:
674 db.rollback()
675 logger.exception("Failed to create knowledge from generated config")
676 raise
678 # Once committed: the first crawls and the downloads.
679 crawls = source_links.start(db, new_knowledge_rows, imported, current_user)
681 if repository is not None:
682 db.refresh(repository)
683 return CreateKnowledgeFromConfigResponse(
684 repository=_with_members(db, repository) if repository is not None else None,
685 created_knowledge_ids=[k.id for k in new_knowledge_rows],
686 crawls_started=crawls,
687 imports_queued=len(imported),
688 )
691# ---------------------------------------------------------------------------
692# Find sources — for knowledge that exists or was already proposed
693# ---------------------------------------------------------------------------
695#: The most sources one search fills: an agent proposal's.
696MAX_SOURCES_TO_FILL = 12
697#: The most searches one person runs at once.
698MAX_RUNNING_SEARCHES = 3
701class SourceToFill(BaseModel):
702 """A source to find material for, as the agent wizard holds it."""
704 #: The caller's own name for it (its index in the proposal), echoed on
705 #: the result.
706 key: str = Field(min_length=1, max_length=64)
707 name: str = Field(min_length=1, max_length=255)
708 description: str = Field(default="", max_length=2000)
709 #: Only these take links: a website source crawls pages, a file source
710 #: imports documents.
711 source_type: Literal["web", "file"]
714class FindSourcesRequest(BaseModel):
715 sources: list[SourceToFill] = Field(min_length=1, max_length=MAX_SOURCES_TO_FILL)
716 #: What the knowledge is for. The agent generation's own description is
717 #: used instead when ``for_generation_id`` names one.
718 context: str = Field(default="", max_length=4000)
719 #: The caller's agent setup run whose proposed sources these are.
720 for_generation_id: UUID | None = None
721 ai_model_id: UUID | None = None
723 @field_validator("sources")
724 @classmethod
725 def _keys_differ(cls, sources: list[SourceToFill]) -> list[SourceToFill]:
726 if len({s.key for s in sources}) != len(sources):
727 raise ValueError("each source needs its own key")
728 return sources
731class FoundSource(BaseModel):
732 """A source with what the search found for it."""
734 key: str
735 name: str
736 source_type: str
737 pages: list[Candidate] = []
738 documents: list[Candidate] = []
739 scope: str | None = None
740 refresh: str | None = None
743class FoundSources(BaseModel):
744 sources: list[FoundSource] = []
745 #: Everything the search found and checked, the assigned and the rest.
746 candidates: list[Candidate] = []
747 warnings: list[str] = []
748 model: GenerationModelInfo
749 generation_id: UUID
752class FindSourcesStatus(BaseModel):
753 generation_id: UUID
754 status: GenerationEnum.Status
755 stage: str | None = None
756 progress: dict = {}
757 proposal: FoundSources | None = None
758 error: str | None = None
761class ApplyFoundSourcesRequest(source_links.SourceLinks):
762 """The links the person kept for an existing source."""
765class ApplyFoundSourcesResponse(BaseModel):
766 crawl_started: bool = False
767 imports_queued: int = 0
768 #: Links not imported, with why (one the source already holds).
769 skipped: list[dict] = []
772def _subject_running(
773 db: Session, user: User, subject: str | None
774) -> GenerationRun | None:
775 """The caller's live search for the same thing, if any."""
776 if subject is None:
777 return None
778 for run in _running_searches(db, user):
779 if (run.arguments or {}).get("subject") == subject:
780 return run
781 return None
784def _running_searches(db: Session, user: User) -> list[GenerationRun]:
785 return [
786 run
787 for run in db.query(GenerationRun)
788 .filter(
789 GenerationRun.flow == GenerationEnum.Flow.source_discovery,
790 GenerationRun.status == GenerationEnum.Status.running,
791 GenerationRun.actor_user_id == user.id,
792 )
793 .all()
794 if not generation_service.is_stale(run)
795 ]
798def _start_search(
799 db: Session,
800 user: User,
801 *,
802 sources: list[dict],
803 context: str,
804 subject: str | None,
805 ai_model_id: UUID | None,
806) -> KnowledgeGenerationStarted:
807 """Open a ``running`` source discovery and start it. A 409 names the
808 caller's live search for the same thing; a 429 says too many run."""
809 running = _subject_running(db, user, subject)
810 if running is not None:
811 raise HTTPException(
812 status_code=status.HTTP_409_CONFLICT,
813 detail={
814 "message": "Sources are already being found for this.",
815 "generation_id": str(running.id),
816 },
817 )
818 if len(_running_searches(db, user)) >= MAX_RUNNING_SEARCHES:
819 raise HTTPException(
820 status_code=status.HTTP_429_TOO_MANY_REQUESTS,
821 detail="Too many searches are running. Wait for one to finish.",
822 )
823 try:
824 model_info = _resolve_generation_model(ai_model_id)
825 except AIServiceError as exc:
826 logger.error("Could not resolve a source discovery model: %s", exc)
827 raise HTTPException(
828 status_code=status.HTTP_502_BAD_GATEWAY,
829 detail="No model is available to find sources.",
830 ) from exc
831 run = generation_service.start(
832 db,
833 flow=GenerationEnum.Flow.source_discovery,
834 actor=user,
835 arguments={"sources": sources, "context": context, "subject": subject},
836 model_info=model_info,
837 status=GenerationEnum.Status.running,
838 progress={
839 "stage": generation_job.Stage.queued.value,
840 "updated_at": utc_isoformat(aware_utcnow()),
841 },
842 )
843 db.commit()
844 generation_job.submit(run.id)
845 return KnowledgeGenerationStarted(
846 generation_id=run.id,
847 status=run.status,
848 stage=generation_job.Stage.queued.value,
849 )
852@knowledge_setup_router.post(
853 "/discover",
854 response_model=KnowledgeGenerationStarted,
855 status_code=status.HTTP_202_ACCEPTED,
856)
857def find_sources(
858 body: FindSourcesRequest,
859 db: Session = Depends(get_db),
860 current_user: User = Depends(get_current_user),
861):
862 """Find real material for sources not yet created — the agent wizard's
863 proposed website and file sources. In the background, as knowledge
864 generation is; ``GET /knowledge/discover/{id}`` says where it is."""
865 context = body.context
866 subject = None
867 model_id = body.ai_model_id
868 if body.for_generation_id is not None:
869 agent_run = generation_service.resolve(db, body.for_generation_id, current_user)
870 if agent_run is None or agent_run.flow != GenerationEnum.Flow.agent_setup:
871 raise HTTPException(
872 status_code=status.HTTP_404_NOT_FOUND,
873 detail="That agent generation was not found.",
874 )
875 context = str((agent_run.arguments or {}).get("problem_description") or context)
876 subject = f"generation:{agent_run.id}"
877 model_id = model_id or agent_run.ai_model_id
878 return _start_search(
879 db,
880 current_user,
881 sources=[s.model_dump() for s in body.sources],
882 context=context,
883 subject=subject,
884 ai_model_id=model_id,
885 )
888def _changeable_source(db: Session, knowledge_id: UUID, user: User) -> Knowledge:
889 """A website or file source the caller may change here."""
890 knowledge = db.get(Knowledge, knowledge_id)
891 if knowledge is None:
892 raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
893 verify_resource_read(knowledge, user, db)
894 verify_change_here(knowledge, user, db)
895 if knowledge.source_type not in source_links.LINKED_TYPES:
896 raise HTTPException(
897 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
898 detail="Only a website or a file source takes links.",
899 )
900 return knowledge
903@knowledge_setup_router.post(
904 "/{knowledge_id}/discover",
905 response_model=KnowledgeGenerationStarted,
906 status_code=status.HTTP_202_ACCEPTED,
907)
908def find_sources_for(
909 knowledge_id: UUID,
910 db: Session = Depends(get_db),
911 current_user: User = Depends(get_current_user),
912):
913 """Find real material for an existing website or file source, from its
914 name and description ("Find sources" on its page). Applied with
915 ``POST /knowledge/{id}/discover/{generation_id}/apply`` once reviewed."""
916 knowledge = _changeable_source(db, knowledge_id, current_user)
917 return _start_search(
918 db,
919 current_user,
920 sources=[
921 {
922 "key": str(knowledge.id),
923 "name": knowledge.name,
924 "description": (knowledge.description or "")[:2000],
925 "source_type": knowledge.source_type,
926 }
927 ],
928 context=knowledge.description or knowledge.name,
929 subject=f"knowledge:{knowledge.id}",
930 ai_model_id=None,
931 )
934@knowledge_setup_router.get(
935 "/discover/{generation_id}", response_model=FindSourcesStatus
936)
937def find_sources_status(
938 generation_id: UUID,
939 db: Session = Depends(get_db),
940 current_user: User = Depends(get_current_user),
941):
942 """Where the caller's search is, and once it is done, each source with
943 what was found for it. Only the person who started it reads it."""
944 run = _own_run(
945 db, generation_id, current_user, GenerationEnum.Flow.source_discovery
946 )
947 _settle_stale(db, run)
948 stored = run.proposal if isinstance(run.proposal, dict) else None
949 found = None
950 if stored is not None and _has_proposal(run):
951 found = FoundSources(
952 sources=stored.get("sources") or [],
953 candidates=stored.get("candidates") or [],
954 warnings=list(run.warnings or []),
955 model=GenerationModelInfo(**(stored.get("model") or {})),
956 generation_id=run.id,
957 )
958 return FindSourcesStatus(**_where(run), proposal=found)
961@knowledge_setup_router.post(
962 "/{knowledge_id}/discover/{generation_id}/apply",
963 response_model=ApplyFoundSourcesResponse,
964)
965def apply_found_sources(
966 knowledge_id: UUID,
967 generation_id: UUID,
968 body: ApplyFoundSourcesRequest,
969 db: Session = Depends(get_db),
970 current_user: User = Depends(get_current_user),
971):
972 """Give an existing source the links the person kept from its search —
973 validated as a hand-made source's are — and start its crawl or its
974 downloads. Its edit history names the search."""
975 knowledge = _changeable_source(db, knowledge_id, current_user)
976 run = _own_run(
977 db, generation_id, current_user, GenerationEnum.Flow.source_discovery
978 )
979 if (run.arguments or {}).get("subject") != f"knowledge:{knowledge.id}":
980 raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
981 if run.status != GenerationEnum.Status.proposed:
982 raise HTTPException(
983 status_code=status.HTTP_409_CONFLICT,
984 detail="This search has no results to add, or they were added already.",
985 )
986 links = body.only_for(knowledge.source_type)
987 if links.empty:
988 raise HTTPException(
989 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
990 detail="Choose at least one link to add.",
991 )
993 previous = knowledge.source_config or {}
994 imported: list[Any] = []
995 skipped: list[dict] = []
996 if knowledge.source_type == source_links.WEB:
997 try:
998 knowledge.source_config = source_links.merged_config(
999 previous,
1000 links,
1001 # An empty source is set up for the kind of knowledge it is.
1002 category=repositories.categories_of(db, [knowledge.id]).get(
1003 knowledge.id
1004 ),
1005 )
1006 except ValueError as exc:
1007 raise HTTPException(
1008 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)
1009 ) from exc
1010 else:
1011 imported, skipped = source_links.import_placeholders(
1012 db, knowledge, links, existing=True
1013 )
1014 db.flush()
1016 from app.router.app.knowledge.router import knowledge_children_snapshot
1018 history_service.record_version(
1019 db,
1020 resource_type=HistoryEnum.ResourceType.knowledge,
1021 model=Knowledge,
1022 resource=knowledge,
1023 action=HistoryEnum.Action.updated,
1024 actor=current_user,
1025 children_resolver=lambda: knowledge_children_snapshot(db, knowledge.id),
1026 generation=run,
1027 )
1028 generation_service.apply(
1029 db,
1030 run,
1031 target_resource_type=HistoryEnum.ResourceType.knowledge,
1032 target_resource_id=knowledge.id,
1033 )
1034 db.commit()
1036 from app.services.knowledge import web_crawl
1038 # Once committed: a crawl of the new pages, or the downloads.
1039 crawls = source_links.start(
1040 db,
1041 [knowledge] if knowledge.source_config != previous else [],
1042 imported,
1043 current_user,
1044 trigger=web_crawl.Trigger.updated,
1045 )
1046 return ApplyFoundSourcesResponse(
1047 crawl_started=bool(crawls), imports_queued=len(imported), skipped=skipped
1048 )