Query the knowledge base with QUESTION.
(ctx, question, save, raw)
| 1100 | ) |
| 1101 | @click.pass_context |
| 1102 | def query(ctx, question, save, raw): |
| 1103 | """Query the knowledge base with QUESTION.""" |
| 1104 | kb_dir = _find_kb_dir(ctx.obj.get("kb_dir_override")) |
| 1105 | if kb_dir is None: |
| 1106 | click.echo("No knowledge base found. Run `openkb init` first.") |
| 1107 | return |
| 1108 | |
| 1109 | from openkb.agent.query import run_query |
| 1110 | |
| 1111 | openkb_dir = kb_dir / ".openkb" |
| 1112 | config = load_config(openkb_dir / "config.yaml") |
| 1113 | _setup_llm_key(kb_dir) |
| 1114 | model: str = config.get("model", DEFAULT_CONFIG["model"]) |
| 1115 | |
| 1116 | stream = _stream_to_tty() |
| 1117 | try: |
| 1118 | answer = asyncio.run(run_query(question, kb_dir, model, stream=stream, raw=raw)) |
| 1119 | if not stream and answer: |
| 1120 | click.echo(answer) |
| 1121 | except Exception as exc: |
| 1122 | click.echo(f"[ERROR] Query failed: {exc}") |
| 1123 | return |
| 1124 | |
| 1125 | append_log(kb_dir / "wiki", "query", question) |
| 1126 | |
| 1127 | if save and answer: |
| 1128 | import re |
| 1129 | from openkb.lint import list_existing_wiki_targets, strip_ghost_wikilinks |
| 1130 | |
| 1131 | slug = re.sub(r"[^a-z0-9]+", "-", question.lower()).strip("-")[:60] |
| 1132 | explore_dir = kb_dir / "wiki" / "explorations" |
| 1133 | explore_dir.mkdir(parents=True, exist_ok=True) |
| 1134 | explore_path = explore_dir / f"{slug}.md" |
| 1135 | # Strip ghost wikilinks the agent may have emitted to non-existent |
| 1136 | # concept/summary pages — the schema_md in the agent's instructions |
| 1137 | # encourages [[wikilinks]] but the agent's view of "which pages |
| 1138 | # exist" can drift from disk reality. |
| 1139 | known = list_existing_wiki_targets(kb_dir / "wiki") |
| 1140 | cleaned_answer, _ = strip_ghost_wikilinks(answer, known) |
| 1141 | explore_path.write_text( |
| 1142 | f'---\nquery: "{question}"\n---\n\n{cleaned_answer}\n', |
| 1143 | encoding="utf-8", |
| 1144 | ) |
| 1145 | click.echo(f"\nSaved to {explore_path}") |
| 1146 | |
| 1147 | |
| 1148 | def _cleanup_pageindex( |
nothing calls this directly
no test coverage detected