# Welcome to Miso What Miso builds from your archive, and where to start. Miso turns your archive into products your readers/customers can use, and into new value for your business. You integrate your content **once**. You can then switch on answers, search, recommendations, summaries, tagging, and more, from the same catalog. Miso is built for publishers, media companies, foundations, and retailers. Articles, video, a product catalog, a database of profiles — if your readers search it, Miso can answer from it. Your content stays yours, and it stays private to your brand. ```mermaid %%{init: {'theme':'base','themeVariables':{ 'fontFamily':'IBM Plex Sans, ui-sans-serif, system-ui','fontSize':'14px', 'lineColor':'#9aa3c0','clusterBkg':'transparent','clusterBorder':'#d3d8e8', 'titleColor':'#8b93ad' },'flowchart':{'curve':'basis','nodeSpacing':22,'rankSpacing':70,'padding':14}}}%% flowchart LR subgraph SRC["WHAT YOU SEND"] direction TB ART["`Articles video · transcripts`"] CAT["`Product catalog listings · prices`"] DAT["`Databases lists · profiles`"] end MISO(["`**Miso** index · atomize`"]) subgraph INSIGHT["WHAT YOU LEARN — DOJO"] direction TB ASKED["What readers ask"] INTENT["What they intend next"] PERF["How your answers perform"] end subgraph OUT["WHAT YOUR READERS GET"] direction TB ANS["Answers"] SRCH["Search & Explore"] REC["Recommendation"] SUM["Summaries"] AGENT["AI agents"] end ART --> MISO CAT --> MISO DAT --> MISO MISO --- ANS MISO --- SRCH MISO --- REC MISO --- SUM MISO --- AGENT MISO --- ASKED MISO --- INTENT MISO --- PERF classDef src fill:#f6f7fa,stroke:#c9cfe0,color:#454c69 classDef hub fill:#3148be,stroke:#3148be,color:#ffffff,stroke-width:0px classDef outbox fill:#f4effc,stroke:#cdbcf0,color:#40277a classDef insight fill:#e8ecfb,stroke:#b9c2ea,color:#22307a class ART,CAT,DAT src class MISO hub class ANS,SRCH,REC,SUM,AGENT outbox class ASKED,INTENT,PERF insight ``` One integration feeds both columns. Your readers get the products, and you get **Dojo**: what your audience asks, what it means to read next, and how your answers perform. Those same signals go back into Miso, so the results improve as your readers use them. ## Integrate once Send your content through WordPress, RSS, SFTP, the Data API, or the Miso crawler. Articles, product listings, structured data, images, and video are all supported. Miso keeps one catalog and syncs it continuously. Miso then does two things with that catalog. It **indexes** the text so it can retrieve any passage. It also **atomizes** it, which means it extracts the entities, the topics, and the relations between them. Every product below reads from the same catalog. See [API Overview](/api/overview) for the whole picture, and [Integrating Your Data](/data/integrating-your-data) for each upload method. ## What you can switch on | Product | What it does | Start here | | --- | --- | --- | | **Answers** | Answers a reader's question from your articles, with citations. | [Ask — Quick Start](/sdk/ask/quick-start) | | **Hybrid Search** | Search your content and answer the question behind it. | [Hybrid Search — Quick Start](/sdk/hybrid-search/quick-start) | | **Explore** | Topic, trending, and related-content feeds. | [Explore — Quick Start](/sdk/explore/quick-start) | | **Recommendation** | Suggests the next article for a reader. | [Search & Recommendation](/api/search-rec/overview) | | **Summary** | Summarizes one article or a whole topic. | [Summary API](/api/genai/summary) | | **Tagging** | Applies your taxonomy to your content. | [Content Tagging](/api/genai/tagging) | | **MCP** | Lets an AI agent search and read your content. | [MCP Server](/mcp/internal) | Studio, News Feed, and LightBox are built on the same catalog. Ask your Miso representative to enable them. ## More about Answers Answers is the product most customers start with. It runs on your own pages, it answers only from your content, and it cites the articles it used. Answers supports: - Questions against your article catalog - Simple queries against structured data and lists - Custom responses for questions you want to control - Tuning for recency and relevance - Custom guardrails - Affiliate advertising ## Your content stays yours Miso **never** uses your content or your readers' questions to train its models. Each brand's catalog is separate, and Miso tunes each deployment for that brand alone. ## Start here 1. [Getting Started](/start/getting-started) — your first question and answer. 2. [Integrating Your Data](/data/integrating-your-data) — get your catalog in. 3. [API Overview](/api/overview) — the API, and the conventions it follows. # Getting Started From nothing to your first answer, in about ten minutes. This page takes you from nothing to your first answer. It needs about ten minutes. ## Before you start You need two things: content in Miso, and an API key. | If you are | Do this | | --- | --- | | **New to Miso** | [Request a free sandbox](https://miso.ai/get-answers). Miso builds it from your public content, usually about 3 months of it. | | **Already a customer** | Get your API keys from [Dojo](https://dojo.askmiso.com/). | API keys are issued to customers only. The sandbox is the fastest way to see how Answers performs on your own content. To practise on content that is not yours, follow [Example: Wikinews](/start/example-news-site). It loads a free public archive of about 20,900 news articles, and every step is code you can run. ### Which key to use | Key | Where it belongs | What it can reach | | --- | --- | --- | | **Secret** | Your server. Never ship it to a browser. | Every endpoint. | | **Publishable** | Browser code. | `POST /v1/interactions` only. | The calls on this page use the secret key, so run them from a server or a terminal. See [Authentication](/api/authentication). *** ## Your first API call An answer is a two-step flow. First you submit the question. Then you poll for the answer. Miso builds the answer in the background, so the first call returns at once. Pass your key as the `X-API-KEY` header, or as an `api_key` query parameter. ## 1. Submit a question ```bash cURL curl -X POST "https://api.askmiso.com/v1/ask/questions" \ -H "X-Api-Key: YOUR_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "anonymous_id": "visitor-8f3a1c", "question": "How do interest rate cuts affect mortgages?" }' ``` ```javascript JavaScript const res = await fetch("https://api.askmiso.com/v1/ask/questions", { method: "POST", headers: { "X-Api-Key": "YOUR_SECRET_KEY", "Content-Type": "application/json", }, body: JSON.stringify({ anonymous_id: "visitor-8f3a1c", question: "How do interest rate cuts affect mortgages?", }), }); const questionId = (await res.json()).data.question_id; ``` ```python Python import requests res = requests.post( "https://api.askmiso.com/v1/ask/questions", headers={"X-Api-Key": "YOUR_SECRET_KEY"}, json={"anonymous_id": "visitor-8f3a1c", "question": "How do interest rate cuts affect mortgages?"}, ) question_id = res.json()["data"]["question_id"] ``` You get back a `question_id` to poll: ```json Response highlight={3} { "message": "success", "data": { "question_id": "0e1f2a3b-4c5d-6e7f-8a9b-0c1d2e3f4a5b" } } ``` `anonymous_id` identifies the reader. Send the same value for the same person, so Miso can keep their history and report on their usage. ## 2. Fetch the answer Poll this endpoint until `finished` is `true`: ```bash cURL QUESTION_ID=0e1f2a3b-4c5d-6e7f-8a9b-0c1d2e3f4a5b curl "https://api.askmiso.com/v1/ask/questions/$QUESTION_ID/answer" \ -H "X-Api-Key: YOUR_SECRET_KEY" ``` ```javascript JavaScript const url = `https://api.askmiso.com/v1/ask/questions/${questionId}/answer`; const headers = { "X-Api-Key": "YOUR_SECRET_KEY" }; let answer; while (true) { const res = await fetch(url, { headers }); answer = (await res.json()).data; if (answer.finished) { break; } await new Promise((r) => setTimeout(r, 1500)); } ``` ```python Python import time url = f"https://api.askmiso.com/v1/ask/questions/{question_id}/answer" headers = {"X-Api-Key": "YOUR_SECRET_KEY"} while True: answer = requests.get(url, headers=headers).json()["data"] if answer["finished"]: break time.sleep(1.5) ``` Poll every 1 to 2 seconds. A typical answer finishes in **12 seconds**, after passing through these stages: ```text answer_stage, in order "" (queued) "Researching different sources" "Doing more research, this may take a little longer" "Generating summary" finished: true ``` The response grows as Miso works, so you can show the partial answer while you wait. **Stop on `finished`. Do not test `answer_stage`.** As the list above shows, it is a sentence for a reader, and Miso translates it into the language of your app. Its wording changes. The `finished` flag does not. When it finishes, you get the answer, its sources, and suggested follow-ups: ```json Response lineNumbers highlight={3-4} { "data": { "finished": true, "answer": "Lower rates make mortgages cheaper. [1]", "sources": [ { "product_id": "rates-and-mortgages", "title": "What rate cuts mean for your mortgage", "url": "https://example.com/markets/rates", "date": "2026-06-12T00:00:00+00:00", "snippet": "The central bank said it expects two cuts…", "highlight_text": "two cuts in 2026", "boosted": false } ], "followup_questions": [ "When is the next central-bank meeting?", "Should I fix my mortgage now?" ] } } ``` The `[1]` in the answer is a citation. It points at the first item in `sources`. Render each one as a link back to your article. See [Answer response fields](/api/genai/answer-fields) for every field. ### If a call fails | Code | What to do | | --- | --- | | `401` | The key is missing or wrong. Check the header name and the key itself. | | `403` | You used a publishable key. Use the secret key for this endpoint. | | `404` | The `question_id` is unknown, or it belongs to another app. | | `429` | You are over the rate limit. Wait, then retry with a longer delay. | *** ## Add Miso to your site The API is the whole platform, but you do not have to build the front end. The Miso SDK gives you the components **and** it captures interactions for you. | Workflow | What it gives your readers | Quick start | | --- | --- | --- | | **Ask** | A question box that answers from your content. | [Ask — Quick Start](/sdk/ask/quick-start) | | **Explore** | Related questions on an article page. | [Explore — Quick Start](/sdk/explore/quick-start) | | **Hybrid Search** | Search results and an answer together. | [Hybrid Search — Quick Start](/sdk/hybrid-search/quick-start) | ## Next steps 1. [Integrating Your Data](/data/integrating-your-data) — keep your catalog in sync. 2. [API Overview](/api/overview) — the conventions every endpoint follows. 3. [Answer Metrics](/operate/answer-metrics) — see how your answers perform. # Example: Wikinews Index a real publication end to end, with data you can download. This page indexes a real publication end to end, with real data you can download yourself. The source is **[Wikinews](https://en.wikinews.org/)**, the free news wiki. Its full archive is a public dump under a Creative Commons licence, so you can run every step here without a content deal. The English archive holds **about 20,900 published articles**, from 2004 to 2026. The median article is 249 words. By the end you will have parsed the dump, sent it to Miso, confirmed it landed, and asked a question that cites one of the articles. > **Every step on this page was run for real**, against the live dump and a > live Miso app, so the numbers and the responses are the ones you get. ## Before you start - A **secret** API key. Keep it on a server. See [Authentication](/api/authentication). - Python 3, with `mwxml` and `mwparserfromhell`. ```bash Set your key export MISO_SECRET_KEY="YOUR_SECRET_KEY" ``` *** ## 1. Get the dump Wikimedia publishes a new dump every few weeks. The articles file is about 47 MB compressed: ```bash Download the archive curl -O https://dumps.wikimedia.org/enwikinews/latest/\ enwikinews-latest-pages-articles.xml.bz2 ``` You do not need to decompress it. Python reads it as it goes. > To try the flow on a handful of articles first, pull them from the > [MediaWiki API](https://en.wikinews.org/w/api.php) instead, with > `action=query&generator=categorymembers&gcmtitle=Category:Published`. ## 2. Map the fields Wikinews articles are wikitext, so the parser reads templates and link markup rather than columns. Each piece maps to a Miso field: | In the wikitext | Miso field | Note | | --- | --- | --- | | `` from the dump | `product_id` | Stable. The title is not — articles get renamed. | | `` | `title` | | | `{{date\|…}}`, `{{byline\|date=…}}` | `published_at` | The **publication** date. The revision timestamp is the last edit, which can be years later. | | Body text | `description` | After the templates and link markup are stripped. | | `[[File:…]]` | `cover_image` | The lead image. Resolve the file name to a URL. | | `[[Category:…]]` | `tags` | Drop the maintenance categories. | ## 3. Parse the dump Two maintained libraries do the heavy lifting. `mwxml` reads the dump, and `mwparserfromhell` parses wikitext into a tree, so templates and links come out correctly nested instead of half-matched by a regular expression. ```bash Install pip install mwxml mwparserfromhell ``` Stream the file: 20,900 articles will not fit in memory as one tree. Keep only namespace `0`, and only articles that carry `{{publish}}`. The rest are drafts, talk pages, and templates. ```python wikinews.py lineNumbers import bz2, re from datetime import datetime, timezone from urllib.parse import quote import mwparserfromhell import mwxml DUMP = "enwikinews-latest-pages-articles.xml.bz2" DROP_SECTIONS = {"sources", "external links", "related news"} SKIP_CATEGORY = re.compile( r"^(Published|Archived|Articles? |Pages |Translated news|" r"Original reporting|Corrected|[A-Z][a-z]+ \d{1,2}, \d{4}$)", re.I) IMAGE_EXT = re.compile(r"\.(jpe?g|png|gif|svg)$", re.I) NOT_A_PHOTO = re.compile(r"(logo|icon|stub|wikinews|commons)", re.I) DATE_FORMATS = ("%B %d, %Y", "%d %B %Y", "%B %Y") def _to_iso(raw): for fmt in DATE_FORMATS: try: d = datetime.strptime(raw.strip(), fmt) return d.replace(tzinfo=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") except ValueError: continue return None def parse_date(code): """{{date}}, then {{byline|date=}}, then the date category.""" for tpl in code.filter_templates(): name = tpl.name.strip().lower() if name == "date" and tpl.params: iso = _to_iso(str(tpl.params[0])) if iso: return iso if name == "byline" and tpl.has("date"): iso = _to_iso(str(tpl.get("date").value)) if iso: return iso for link in code.filter_wikilinks(): title = str(link.title) if title.lower().startswith("category:"): iso = _to_iso(title.split(":", 1)[1]) if iso: return iso return None def body_text(code): keep = [] for section in code.get_sections(include_lead=True, flat=True): heads = section.filter_headings() name = heads[0].title.strip().lower() if heads else "" if name in DROP_SECTIONS: continue for h in heads: section.remove(h) keep.append(section.strip_code(normalize=True, collapse=True)) text = "\n\n".join(k.strip() for k in keep if k.strip()) return re.sub(r"\n{3,}", "\n\n", text) def topics(code): out = [] for link in code.filter_wikilinks(): title = str(link.title) if not title.lower().startswith("category:"): continue name = title.split(":", 1)[1].strip() if name and not SKIP_CATEGORY.match(name) and name not in out: out.append(name) return out def cover_image(code, width=1200): for link in code.filter_wikilinks(): title = str(link.title) if not re.match(r"(File|Image):", title, re.I): continue name = title.split(":", 1)[1].strip() if not IMAGE_EXT.search(name) or NOT_A_PHOTO.search(name): continue slug = quote(name.replace(" ", "_")) return (f"https://en.wikinews.org/wiki/Special:FilePath/" f"{slug}?width={width}") return None def is_published(code): return any(t.name.strip().lower() == "publish" for t in code.filter_templates()) def to_product(page, revision, code): body = body_text(code) slug = quote(page.title.replace(" ", "_")) record = { "product_id": f"wikinews-{page.id}", "title": page.title, "url": f"https://en.wikinews.org/wiki/{slug}", "description": body, "published_at": parse_date(code), "updated_at": revision.timestamp.strftime("%Y-%m-%dT%H:%M:%SZ"), "cover_image": cover_image(code), "tags": topics(code)[:12], "custom_attributes": { "source": "wikinews", "license": "CC BY 2.5", "word_count": len(body.split()), }, } return {k: v for k, v in record.items() if v} def articles(path=DUMP): dump = mwxml.Dump.from_file(bz2.open(path, "rt", encoding="utf-8")) for page in dump: if page.namespace != 0 or page.redirect: continue for revision in page: if not revision.text: break code = mwparserfromhell.parse(revision.text) if is_published(code): yield to_product(page, revision, code) break ``` The parse takes about two minutes for the whole archive, and yields 20,903 articles. `strip_code()` is the call worth having: it removes templates, links, and markup in one pass, and it does not trip over a template inside a template. One record comes out like this: ```json One parsed article { "product_id": "wikinews-820", "title": "Big Linux Beta 3 released", "url": "https://en.wikinews.org/wiki/Big_Linux_Beta_3_released", "cover_image": "https://en.wikinews.org/wiki/Special:FilePath/Biglinux1.png?width=1200", "description": "Big Linux 2.0 Beta 3 has been released. Big Linux is a Live Compact Disc Brazilian Linux distribution, based on Knoppix…", "published_at": "2004-11-15T00:00:00Z", "updated_at": "2024-12-17T15:53:33Z", "tags": [ "Brazil", "Computing", "Science and technology", "FLOSS", "Linux", "Software" ], "custom_attributes": { "source": "wikinews", "license": "CC BY 2.5", "word_count": 280 } } ``` ### Should you send the HTML? Send `html` when you have it, because Miso reads the tags to understand the structure of the document. The dump carries wikitext only, so this example sends `description`, which is enough for a first index. For a production load, render each page with the MediaWiki API (`action=parse`) and send `html` instead. That is one request per article, so cache the result. ### The image is a file name, not a URL Wikitext names the file — `[[File:Gross-Powell.jpg|thumb|Colin Powell]]` — and gives no address. `Special:FilePath` resolves it, whether the file sits on Wikinews or on Commons: ```text Resolve a file name https://en.wikinews.org/wiki/Special:FilePath/Gross-Powell.jpg?width=1200 ``` Take photo extensions only, because `.ogv` files also appear as `[[File:…]]`, and drop logos and icons. 55% of the archive has a usable image. Omit `cover_image` for the rest, because an empty string tells your front end nothing. ### Get the date right, or ruin recency Here `published_at` is 2009 and `updated_at` is 2024, because a maintenance edit touched thousands of old articles. **Never fall back to the revision timestamp**. It puts 2004 news at the top of every question about recent events. The parser reads `{{date}}`, then `{{byline|date=}}`, then the date category. That covers every article but 369 of them (1.8%), which get no `published_at` at all. ## 4. Validate before you write Send one record with `dry_run=1`. Nothing is written, and the schema is checked: ```python Dry run import json, os, requests from wikinews import articles API = "https://api.askmiso.com" HEADERS = { "X-Api-Key": os.environ["MISO_SECRET_KEY"], "Content-Type": "application/json", } first = next(articles()) res = requests.post(f"{API}/v1/products?dry_run=1", headers=HEADERS, json={"data": [first]}) print(res.status_code, res.json()) ``` A pass returns `Dry run pass`. A `422` names every problem in the batch. Fix the mapping now, while the batch is one record. ## 5. Upload the archive Send about 100 records per call. One bad record fails a whole batch, so keep batches small enough to debug. A product upload is asynchronous: it returns a task id, and you poll until the records land. ```python wikinews.py — upload lineNumbers import time CHUNK = 100 def send(products): res = requests.post(f"{API}/v1/products", headers=HEADERS, json={"data": products}) if res.status_code == 429: # over the rate limit time.sleep(5) return send(products) if res.status_code == 422: # nothing was written for problem in res.json().get("data", []): print("invalid:", problem) res.raise_for_status() return res.json()["data"] def wait_for(task_id, timeout=300): url = f"{API}/v1/products/_status/{task_id}" deadline = time.time() + timeout while time.time() < deadline: body = requests.get(url, headers=HEADERS).json() if body.get("message") != "pending": return body["data"]["items"] time.sleep(2) raise TimeoutError(task_id) def index_all(): batch, done = [], 0 for product in articles(): batch.append(product) if len(batch) < CHUNK: continue accepted = send(batch) # Most apps are asynchronous. Some return the result at once. if "task_id" in accepted: items = wait_for(accepted["task_id"]) else: items = accepted.get("items", []) done += len(items) print(f"{done} articles indexed") batch = [] if batch: send(batch) ``` Each finished batch reports one entry per record: ```json Batch finished { "message": "success", "data": { "items": [ { "id": "wikinews-100811", "status": "created" } ] } } ``` The archive runs oldest first, which is what you want: history lands before recent news is written on top of it. **The full load:** 20,901 records in 210 batches, about **23 minutes**, with no failed batch. Four articles are skipped, because the wikitext cleaner leaves them with an empty body. The index trails the upload. At the halfway point Miso accepted 11,000 records, and 8,501 of them were searchable. Both numbers meet at the end, so count the catalog when the load finishes, not while it runs. ## 6. Ask a question ```python Ask def ask(question, reader="wikinews-demo"): res = requests.post(f"{API}/v1/ask/questions", headers=HEADERS, json={"anonymous_id": reader, "question": question}) qid = res.json()["data"]["question_id"] url = f"{API}/v1/ask/questions/{qid}/answer" while True: answer = requests.get(url, headers=HEADERS).json()["data"] if answer["finished"]: return answer time.sleep(1.5) answer = ask("What did Wikinews report about the Linux operating system?") print(answer["answer"]) for source in answer["sources"]: print("-", source["title"], source["url"]) ``` That query answers from the archive you uploaded, about 23 seconds after the question: ```text Answer Wikinews reported extensively on the major shift in the CentOS ecosystem following Red Hat's December 2020 announcement to move focus away from CentOS Linux in favor of CentOS Stream. This transition effectively moved the end-of-life (EOL) date for CentOS 8 from May 2029 to December 31, 2021, causing significant concern within the community [1][2]. ``` `sources` carried three articles. Each one looks like this: ```json One source { "product_id": "wikinews-2911067", "title": "Red Hat to move focus away from CentOS in favour of Stream…", "url": "https://en.wikinews.org/wiki/Red_Hat_to_move_focus_away_from_CentOS…", "date": "2020-12-14T00:00:00+00:00", "snippet": "CentOS 8's End of Life (EOL) has been moved up from May 2029…", "highlight_text": "CentOS 8's End of Life (EOL) has been moved up from May 2029…", "boosted": false } ``` The `[1]` markers in the answer point at those entries, in order. Miso also returns six follow-up questions, such as *"What is the primary goal of the Rocky Linux project?"*. If the answer cites a Wikinews article and the link works, the integration is done. An empty or refused answer usually means the batch is not indexed yet, or the question is outside the archive. A refusal is not an error: `finish_reason` is still `success`, and `sources` is empty. ## Keep it in sync The Wikinews archive is fixed: the wiki stopped publishing new articles, so one load is enough. Your own newsroom is not fixed. Miso never compares your source against its index, so send every change as it happens. | Event | What to send | | --- | --- | | An article is published | `POST /v1/products` with the new record. | | An article is edited | `POST /v1/products` with the **same `product_id`**. It overwrites. | | An article is withdrawn | `POST /v1/products/_delete`. | ```bash Remove articles curl -X POST "https://api.askmiso.com/v1/products/_delete" \ -H "X-Api-Key: $MISO_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": { "product_ids": ["wikinews-100811"] } }' ``` The body takes `product_ids` and nothing else, as a flat array. A nested array returns `422`. Delete is asynchronous, the same as an upload, so it returns a task id that you poll. ### Ask Miso what it holds `GET /v1/products/_ids` returns **every** `product_id` in your index, in one response. There is no paging. ```bash Every id Miso holds curl "https://api.askmiso.com/v1/products/_ids" \ -H "X-Api-Key: $MISO_SECRET_KEY" ``` ```json Response { "message": "success", "data": { "ids": ["wikinews-100811", "wikinews-129125"] } } ``` Add `type=article` to count one content type only. ### Reconcile after each dump This is the repair for a missed delete. Compare what Miso holds against what your source holds now, and remove the difference. ```python Reconcile lineNumbers def indexed_ids(): res = requests.get(f"{API}/v1/products/_ids", headers=HEADERS) res.raise_for_status() return set(res.json()["data"]["ids"]) def reconcile(source_ids, apply=False): """Delete records Miso still holds that the source no longer has.""" indexed = indexed_ids() orphans = sorted(indexed - set(source_ids)) print(f"{len(indexed)} indexed, {len(source_ids)} at source, " f"{len(orphans)} to delete") # Guard: a broken extract looks like "everything was deleted". if orphans and len(orphans) > 0.10 * len(indexed): raise SystemExit("Refusing: more than 10% would be deleted. " "Check the source extract first.") url = f"{API}/v1/products/_delete" if not apply: url += "?dry_run=1" for i in range(0, len(orphans), CHUNK): res = requests.post( url, headers=HEADERS, json={"data": {"product_ids": orphans[i:i + CHUNK]}}) res.raise_for_status() return orphans # Wikinews: product_id is the page id, so build the set from the new dump. source_ids = {p["product_id"] for p in articles()} reconcile(source_ids) # dry run, prints the count # reconcile(source_ids, apply=True) # then delete for real ``` Run it after each new dump. Three things make it safe: - **`dry_run=1` first, every time.** It reports without deleting. - **The percentage guard.** If your extract fails and returns 40 ids, the difference is your whole catalog. The guard stops that. - **`product_id` is the page id, not the title.** A renamed article keeps its id, so a rename never looks like a deletion. > **A missed delete never expires.** If an article comes down at the source and > no delete reaches Miso, the old version stays in the index and keeps > appearing in answers. Wire the delete to the same event that unpublishes the > page. For a wiki, `action=query&list=recentchanges&rcnamespace=0` gives you the changed pages since your last run. For a CMS, use its publish webhook. ## Next - [Integrating Your Data](/data/integrating-your-data) — every field, and the other upload methods. - [Getting Started](/start/getting-started) — the SDK, to put this on a site. # Integrating Your Data Send your content, check it landed, and keep it in sync. Miso answers from the data you send it. Below we send one article, check it landed, and then scale the same call to an archive. > Data management in Dojo is available to customers only. ## What Miso accepts **Your content catalog.** The articles, opinion pieces, and other content your readers consume. Answers are built from this data. Send transcripts for video and audio too. Most teams send the whole catalog first, then exclude what must stay out of Answers. This way, nobody has to guess what Miso holds. You can upload or delete at any time. Miso does not charge for indexing. **Databases and lists (optional).** Useful when you want an exact value instead of a passage from an article. For example, profile pages for investment funds, design agencies, supermarkets, or hospitals. Ranked lists such as a Top 50 or an award shortlist also work well. **Users and interactions (optional).** Data about your readers and what they read. Miso is a privacy-first platform, and many customers send hashed ids. **Do not send PII.** ## How to send it | Method | Use it when | | --- | --- | | **WordPress plugin** | Your site runs on WordPress. It syncs for you. | | **Data API** | You want control, and your CMS can call an API. | | **SFTP** | You already export files. Miso reads the drop and loads it. | | **Crawler** | You cannot export at all. Miso reads your public pages. | All four keep Miso in near real-time sync with your catalog. See [Ingest Methods](/data/ingest-methods) to choose between them. Ask your Miso representative to set up WordPress, SFTP, or the crawler. The rest of this page covers the API. *** ## Upload with the Data API The [Data APIs](/api/reference/tag/product-content-apis) upload and manage your data. They accept bulk inserts, and they satisfy GDPR and CCPA, because a reader's data can be deleted. Use your **secret** key, from a server. A publishable key reaches `POST /v1/interactions` and nothing else. See [Authentication](/api/authentication). **Send about 100 records per call.** Larger batches risk a timeout. ### Products — your content ```bash Upload products curl -X POST "https://api.askmiso.com/v1/products" \ -H "X-Api-Key: YOUR_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": [ { "product_id": "art-20260612-rates", "title": "Central bank signals 2026 cuts", "url": "https://example.com/markets/rates", "cover_image": "https://example.com/img/rates.jpg", "authors": ["Jane Reporter"], "categories": [["News", "Markets"]], "published_at": "2026-06-12T09:00:00Z", "html": "<p>Full article body…</p>", "custom_attributes": { "section": "markets", "premium": true } } ] }' ``` ### Users — optional, hashed ids only ```bash Upload users curl -X POST "https://api.askmiso.com/v1/users" \ -H "X-Api-Key: YOUR_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": [ { "user_id": "u-10293", "subscription_tier": "premium" } ] }' ``` ### Interactions — what readers do ```bash Upload interactions curl -X POST "https://api.askmiso.com/v1/interactions" \ -H "X-Api-Key: YOUR_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": [ { "type": "product_detail_page_view", "user_id": "u-10293", "product_ids": ["art-20260612-rates"], "timestamp": "2026-06-12T10:15:00Z" } ] }' ``` The Miso SDK sends interactions for you. Upload them yourself only when you built your own front end. See [SDK Overview](/sdk/overview). *** ## Uploads are asynchronous A product or user upload does **not** write your records before it answers. Miso accepts the batch, queues it, and returns a task id at once: ```json 200 — batch accepted { "message": "success", "data": { "task_id": "b3BhcXVlLXRhc2staWQtYWJvdXQtMTQwLWNoYXJhY3RlcnMtbG9uZw…" } } ``` The task id is an opaque string of about 140 characters. Store it as it comes. **A `200` here means "accepted", not "indexed".** The records reach the index a moment later. Treat the task id as your receipt. ```mermaid %%{init: {'theme':'base','themeVariables':{ 'fontFamily':'IBM Plex Sans, ui-sans-serif, system-ui','fontSize':'14px', 'actorBkg':'#3148be','actorBorder':'#3148be','actorTextColor':'#ffffff', 'actorLineColor':'#9aa3c0','signalColor':'#9aa3c0','signalTextColor':'#6b7392', 'labelBoxBkgColor':'#f4effc','labelBoxBorderColor':'#cdbcf0', 'labelTextColor':'#40277a','noteBkgColor':'#e8ecfb','noteBorderColor':'#b9c2ea', 'noteTextColor':'#22307a','sequenceNumberColor':'#ffffff' }}}%% sequenceDiagram autonumber participant C as Your CMS participant M as Miso participant I as The index C->>M: POST /v1/products (100 records) M-->>C: 200 with a task_id Note over C,M: accepted, not yet searchable M->>I: write the batch in the background loop every 2 seconds C->>M: GET /v1/products/_status/{task_id} M-->>C: pending end I-->>M: the batch is written C->>M: GET /v1/products/_status/{task_id} M-->>C: errors false, one entry per record Note over C,I: about 51 seconds for one record ``` ### Check the task Poll the status endpoint with the task id: <scalar-code-group> ```bash cURL curl "https://api.askmiso.com/v1/products/_status/TASK_ID" \ -H "X-Api-Key: YOUR_SECRET_KEY" ``` ```python Python import time, requests def wait_for(task_id, key, timeout=300): url = f"https://api.askmiso.com/v1/products/_status/{task_id}" headers = {"X-Api-Key": key} deadline = time.time() + timeout while time.time() < deadline: body = requests.get(url, headers=headers).json() if body.get("message") != "pending": return body time.sleep(2) raise TimeoutError(task_id) ``` ```javascript Node.js async function waitFor(taskId, key, timeoutMs = 300000) { const url = `https://api.askmiso.com/v1/products/_status/${taskId}`; const headers = { "X-Api-Key": key }; const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { const body = await (await fetch(url, { headers })).json(); if (body.message !== "pending") { return body; } await new Promise((r) => setTimeout(r, 2000)); } throw new Error(`timeout: ${taskId}`); } ``` </scalar-code-group> While Miso works, the status is `pending`: ```json Still working { "message": "pending" } ``` When the batch is written, the shape changes completely: ```json Finished { "took": 9, "errors": false, "data": [], "code": 200 } ``` | Field | What it means | | --- | --- | | `errors` | `false` when every record was written. **Read this**, not the HTTP status. | | `code` | `200`, or the code of the first record that failed. | | `data` | Messages about the records. Empty when nothing went wrong. | | `took` | How long the write took, in seconds. | | Response | What it means | | --- | --- | | `{"message": "pending"}` | Miso is still writing the batch. Poll again. | | A body with `errors` and `code` | The batch is finished. | | `404` | The task id is unknown, or it expired. | **Allow at least 60 seconds.** A single-record batch against production takes about **51 seconds** to move from `pending` to finished. Poll every 2 to 5 seconds, and set a timeout in minutes, not seconds. The record becomes readable at the same moment the status resolves, so `GET /v1/products/{product_id}` is an equally good check for one known id. A **delete** is faster, and its status carries a different `data`: ```json Delete finished { "took": 0, "errors": false, "data": { "deleted": { "count": 1, "list": ["art-20260612-rates"] } }, "code": 200 } ``` That one resolved in 11 seconds, against 51 for an insert. Afterwards `GET /v1/products/{product_id}` returns `404 {"message": "not found"}`. ### Which calls are asynchronous | Endpoint | Behavior | | --- | --- | | `POST /v1/products` | Asynchronous. Returns `task_id`. | | `POST /v1/users` | Asynchronous. Returns `task_id`. Poll `/v1/users/_status/{task_id}`. | | `POST /v1/interactions` | Synchronous. It answers immediately, so you can call it on every click. | | `POST /v1/products/_delete` | Asynchronous. Returns `"message": "deleted"` and a `task_id`. | Some apps are configured for synchronous uploads. Those return the per-record `items` in the first response, with no task id. Write your client to accept both: if `data.task_id` is present, poll. If `data.items` is present, you are already done. ### Validate before you write Add `dry_run=1` to check a batch against the schema without writing it. Use it in your build, and on the first batch of a new pipeline. ```bash Dry run curl -X POST "https://api.askmiso.com/v1/products?dry_run=1" \ -H "X-Api-Key: YOUR_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": [ … ] }' ``` *** ## The product schema Every field Miso accepts, what it is for, and how to design your custom attributes: see [Product Schema](/data/product-schema). *** ## Read your data In [Dojo](https://dojo.askmiso.com/), you can see everything you uploaded in a visual dashboard. You can also read it through the API: ```bash Read one product curl "https://api.askmiso.com/v1/products/PRODUCT_ID" \ -H "X-Api-Key: YOUR_SECRET_KEY" ``` ## Delete your data In [Dojo](https://dojo.askmiso.com/), you can delete single records, or everything in your environment. Through the API, get the ids first, then delete in bulk: ```bash List every product id curl "https://api.askmiso.com/v1/products/_ids" \ -H "X-Api-Key: YOUR_SECRET_KEY" ``` ```bash Delete products by id curl -X POST "https://api.askmiso.com/v1/products/_delete" \ -H "X-Api-Key: YOUR_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": { "product_ids": ["PRODUCT_1", "PRODUCT_2"] } }' ``` > **A delete is an event you send.** Miso does not compare your catalog > against its index. If an article is removed on your side and no delete > reaches Miso, the old version stays and keeps serving. Send the delete. *** ## Troubleshooting ### 422 — schema validation A failed upload is almost always a schema error. **One bad record fails the whole batch**, and Miso writes nothing. Read the `data` field to find each problem: ```json 422 validation error lineNumbers { "errors": true, "message": "No records inserted - see the `data` field.", "data": [ "data.0.product_ids is invalid. Expected 'array' or 'null'.", "data.0.timestamp is invalid. Expected 'date-time' format." ] } ``` `data.0` is the first record in the batch you sent. Correct the records that the response names, then send the batch again. Miso logs these errors too, so your Miso solutions engineer can help. ### The data is wrong Review it in [Dojo](https://dojo.askmiso.com/). You can delete a record, or upload a corrected version over it. Miso deduplicates on `product_id` during upload and keeps the newest version. ### Other errors | Code | What it means | | --- | --- | | `401` | The key is missing or wrong. | | `403` | You used a publishable key. Products and users need the secret key. | | `429` | Too many requests. Slow down, then retry. | # Product Schema The fields Miso accepts, and how to shape yours. A product is one piece of content: an article, a video, a page. The schema validates only `product_id`, but a record with only an id is of no use to Answers. The fields below are what Miso works from. To send the records, see [Integrating Your Data](/data/integrating-your-data). ## Send these on every record | Field | Type | Why Miso needs it | | --- | --- | --- | | `product_id` | string | Your id for the content. It is the key: an upload with an id that exists overwrites that record. Interactions and answers point back with it. | | `title` | string | The strongest short signal for retrieval, and the text a reader sees in a citation. | | `url` | string | Where the citation links to. Without it an answer can cite the article but not send anyone to it. | | `html` **or** `description` | string | The body. This is the text Miso answers from. Send `html` when you have it, because the tags carry the structure. | | `published_at` | ISO-8601 date or datetime | Drives recency. Without it Miso cannot tell new from old, and "latest" questions get stale answers. | ## Send these when you have them | Field | Type | What it buys you | | --- | --- | --- | | `authors` | array of strings | Author filters and "by X" questions. One name per entry, not one joined string. | | `cover_image` | string | The thumbnail in your UI and in Dojo Sandboxes. | | `categories` | array of arrays | Your hierarchy. See below. | | `tags` | array of strings | Flat labels, for filtering and boosting. | | `children` | array of objects | Chapters or sections of long-form content. See [below](#long-form-content-children). | Everything else in the schema is optional: `type`, `language`, `updated_at`, `brand`, `rating`, `original_price`, and more. Send what you have. ## How Miso reads each field This decides where your text belongs. | Treated as | Fields | What happens | | --- | --- | --- | | **Text** | `html`, `description` | Tokenized, and read for meaning. Term frequency matters here. | | **Feature or keyword** | Everything else | Used to filter, boost, and rank. Not read as prose. | | **Display only** | `url`, `cover_image` | Not used for training. They render the result. | So: put the words in `html` or `description`. Put the facts in their own fields. **Prefer `html` when you have it.** Miso's parser reads the tags to understand the structure of your document — headings, paragraphs, lists, and tables. That structure tells Miso which passage answers a question. Send `description` when plain text is all you hold. ## Categories are hierarchical `categories` is an **array of arrays**. Each inner array runs from broad to narrow, and a product can sit in more than one: ```json Hierarchical categories { "categories": [["News", "Markets", "Interest rates"], ["Analysis"]], "tags": ["central-bank", "mortgages"] } ``` Use `categories` for a taxonomy with levels. Use `tags` for flat labels. A flat list is **rejected**. `"categories": ["News", "Markets"]` returns `422` with `data.0.categories/0 is invalid`. Each entry must itself be an array, even when the path has one level: `[["News"]]`. *** ## Custom attributes `custom_attributes` is a free-form object for everything specific to your business. Miso handles hundreds of them, so send all the metadata you hold. A key must be a string. A value can be a boolean, a string or array of strings, a number or array of numbers, an array of objects, or `null`. ```json Custom attributes { "product_id": "art-20260612-rates", "title": "Central bank signals 2026 cuts", "custom_attributes": { "section": "markets", "premium": true, "read_minutes": 6, "item_source": "WIRE", "alternative_langs": ["en", "zh"], "series": { "name": "Rate Watch", "part": 4 } } } ``` ## Long-form content: `children` A book, a report, or a two-hour podcast is one product with many parts. Send the parts as `children`, and Miso finds the passage that answers a question inside the right chapter. In the following record, we send a book with two of its chapters: ```json Children { "product_id": "book-9781234567890", "title": "Designing Data Pipelines", "url": "https://example.com/books/designing-data-pipelines", "published_at": "2026-03-01", "children": [ { "id": "ch-01", "title": "Why pipelines fail", "url": "https://example.com/books/designing-data-pipelines/ch01", "headers": ["Silent schema drift", "Backfills that never end"], "html": "<h1>Why pipelines fail</h1><p>Most failures start upstream…</p>", "custom_attributes": { "page_start": 1, "page_end": 24 } }, { "id": "ch-02", "title": "Idempotent loads", "url": "https://example.com/books/designing-data-pipelines/ch02", "headers": ["Keys and versions", "Replaying a day"], "html": "<h1>Idempotent loads</h1><p>A load you can run twice…</p>", "custom_attributes": { "page_start": 25, "page_end": 51 } } ] } ``` | Field | Type | What Miso does with it | | --- | --- | --- | | `id` | string | Required. Your id for the part, unique within the product. Miso uses it to say which part a passage came from. | | `title` | string | The part's name. Searched as text to find the right part, and shown with the citation. | | `url` | string | Where the part lives. When an answer cites a passage from this part, the citation links here. Without it the citation links to the product's `url`. | | `html` **or** `description` | string | The part's body. Same rule as the product: send `html` when you have it. | | `headers` | array of strings | The headings inside the part. Searched as text alongside `title`. | | `custom_attributes` | object | Facts about the part, with the same value types as the product's [custom attributes](#custom-attributes). | Keep the product's own `title`, `url`, and `published_at`. Children add to the product, and the product still carries recency and the citation fallback. A short article does not need children. Miso already reads its structure from `html`. ## Why the design matters: every attribute becomes a filter Whatever you send is queryable by its path, as `custom_attributes.<key>`. That is how filters (`fq`) and boosts (`boost_fq`) reach your own data: ```text Filter and boost by your own fields fq: custom_attributes.premium:"false" boost_fq: custom_attributes.item_source:WIRE AND tags:markets ``` See [Filter Syntax (fq)](/api/fq) for the operators, ranges, and the two mistakes that return nothing instead of an error. Nested objects work with a dotted path — `custom_attributes.series.name`. You can combine your attributes with the standard fields in one expression. This is the reason to think about shape before you send. If a value must be filtered on, it needs its own key or its own path. ## Shape the fields for the updates you make Take products that are available in some regions only. Two ways to model it: 1. One list: `{"regional_availability": ["region_1", "region_3"]}` 2. One field per region: `{"region_1_availability": true, "region_2_availability": false}` Option 1 reads better and filters cleanly. Option 2 is easier for a partial update, because you send only the regions that changed. Your Miso solutions architect can help you decide. ## Put the front end's fields in there too If your UI needs a rating score or a badge to render a result, send it as a custom attribute. It comes back with the result, so your page does not need a second request. > **Warning: text belongs in `description`.** Miso reads only `description` > and `html` as text. Every other field, including every custom attribute, is > treated as a feature or a keyword. If your summary has several sections, put > the whole text in `description`. Do not create one custom attribute per > section — that text will not be searched as prose. ## Naming rules Custom attribute keys are not restricted: a leading `_` and a dot both pass validation. Avoid the dot anyway. It is the path separator in a filter, so `custom_attributes.a.b` cannot tell your key `a.b` from a nested field `b` inside `a`. The **top level** is strict. Miso rejects any field it does not define: ```json 422 — unknown top-level field { "errors": true, "message": "None of the records were inserted…", "data": [ "data.0 is invalid. The attribute must not contain additional properties" ] } ``` Everything of your own belongs in `custom_attributes`. *** # Ingest Methods Four ways to get your catalog into Miso, and how to choose. There are four ways to get your catalog into Miso. They all end at the same place, so you can mix them: a crawler for the archive, then the API for everything new. | Method | Use it when | You build | | --- | --- | --- | | **[WordPress plugin](https://github.com/MisoAI/miso-wordpress-plugin)** | Your site runs on WordPress. | Nothing. Install it, paste your key, sync. | | **Data API** | Your CMS can call an API. | A publish hook. | | **SFTP** | You already export files. | An export job. | | **Crawler** | You cannot export at all. | Nothing. | The Data API and the WordPress plugin you can set up alone. For SFTP and the crawler, ask your Miso representative to enable and configure it. ## WordPress plugin **[MisoAI/miso-wordpress-plugin](https://github.com/MisoAI/miso-wordpress-plugin)** — the official plugin. It syncs your posts to your Miso catalog, and keeps them in sync as they change. What it does: - Hooks `wp_after_insert_post`, so an update or a deletion cascades to Miso. - Adds a **Miso AI** menu to your admin panel, for the API key and for manual syncs. - Adds WP-CLI commands, for a sync you script or schedule. Four steps to a live catalog: 1. Install and activate the plugin. 2. Open **Miso AI ▸ Settings** in your WordPress admin panel. 3. Enter your API key, then select **Save Changes**. 4. Open **Miso AI ▸ Posts** and select **Sync Posts** to send everything you have. Step 4 is your backfill. After that the hook keeps Miso current, so publishing a post in WordPress puts it in Miso without another step. ### Multisite: set a product ID prefix > **CAUTION: On a multisite network, set a prefix on every site before you > sync.** Without one, two sites overwrite each other's records, and a full > sync on one site deletes the other site's records. The plugin builds each `product_id` from the WordPress post id. Post `12345` becomes product `12345`. Every site in a network numbers its posts from 1, so two sites both hold a post `12345`, and the second upload overwrites the first. **Product ID prefix** on the **Miso AI ▸ Settings** page corrects this. Give each site a different value: | Site | Prefix | Post 12345 becomes | | --- | --- | --- | | Site one | `mysite1_` | `mysite1_12345` | | Site two | `mysite2_` | `mysite2_12345` | The prefix also scopes deletion. A full sync removes the records that carry **that** prefix, and leaves the rest of the catalog alone. This is what makes one Miso catalog safe for a whole network. Set the prefix **before** the first sync. If you add one later, the records from the first sync keep their old unprefixed ids, and a later full sync does not clean them up. Ask your Miso representative to remove them, or delete them with [`POST /v1/products/_delete`](/data/integrating-your-data). ## Data API Your CMS calls Miso when an article changes. This gives you the most control: you decide the fields, the timing, and what to exclude. ```bash On publish curl -X POST "https://api.askmiso.com/v1/products" \ -H "X-Api-Key: YOUR_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": [ { "product_id": "art_001", "title": "…" } ] }' ``` Wire three CMS events, and your catalog stays correct: | CMS event | Call | | --- | --- | | Publish | `POST /v1/products` | | Update | `POST /v1/products` with the same `product_id`. It overwrites. | | Unpublish or delete | `POST /v1/products/_delete` | See [Integrating Your Data](/data/integrating-your-data) for batching, the status poll, and validation. ## SFTP You drop files, and Miso loads them. Use it when a nightly export already exists, or when your CMS cannot call out. - Miso gives you the host and the credentials. - You write JSON, XML, or CSV, on your own schedule. - Miso reads each drop and loads it. The trade-off is latency. Your catalog is as fresh as your last drop, so a nightly export means answers are up to a day behind. Send breaking news through the API even when the archive arrives by SFTP. ## Crawler Miso reads your public pages, the way a search engine does. It needs no work from your team, which makes it the fastest way to start and the usual choice for a sandbox. Two limits: - **It sees what a visitor sees.** Content behind a paywall or a login does not reach Miso unless you allow the crawler through. - **It infers structure.** The API tells Miso exactly which text is the body and which value is the publication date. A crawler works it out from the page. Most customers start on the crawler and move to the API or the plugin when they go live. ## Which to choose | If | Choose | | --- | --- | | You run WordPress | [The plugin](https://github.com/MisoAI/miso-wordpress-plugin) | | You need a record in Miso within seconds of publishing | The Data API | | You already export nightly, and a day of latency is acceptable | SFTP | | You want to see Answers on your content this week | The crawler | Whatever you choose, **send deletes**. Miso never compares your source against its index, so an article you remove keeps serving until a delete arrives. See [Integrating Your Data](/data/integrating-your-data). # SDK Overview Add Miso to any site with a few lines of JavaScript. With the **Miso Client JS SDK**, you can add Miso-powered experiences to any website with a few lines of JavaScript. These experiences are AI answers, related-question discovery, hybrid search, and personalized search and recommendations. Everything is fully customizable: HTML, CSS, and logic. > Looking for a runnable example? Open the [Live Showcase](https://poc.miso.ai/demo/showcase/index.html#/hybrid-search/two-columns) to see every component in action. ## Parts of the SDK The SDK has three parts: | Part | What it does | | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- | | **API** | Call the [Miso API](/api/overview) programmatically. | | **UI** | Prebuilt UI elements and layouts. They render workflows such as Ask, Explore, and Hybrid Search. You can customize their HTML, CSS, and logic. | | **Progressive Markdown** | Tools to display streamed Markdown as it arrives, so answers appear word by word. | ## Install ### As a node module In your project directory, run: ```bash npm npm install --save @miso.ai/client-sdk ``` Then import `MisoClient` from the SDK: ```javascript Import import MisoClient from "@miso.ai/client-sdk"; ``` ### Using a script tag ```html Script tag <script async src="https://cdn.jsdelivr.net/npm/@miso.ai/client-sdk@latest/dist/umd/miso.min.js"></script> ``` The script tag loads the SDK asynchronously, so your code must wait for it. Use the `misocmd` queue, which runs your function as soon as the SDK is ready: ```javascript Wait for the SDK const misocmd = window.misocmd || (window.misocmd = []); misocmd.push(() => { const MisoClient = window.MisoClient; // Your code goes here. }); ``` Then create a client with your publishable API key: ```javascript Create a client const client = new MisoClient("YOUR_PUBLISHABLE_KEY"); ``` > Use a **publishable** (front-end) API key in the browser — never your secret key. See [Authentication](/api/authentication). ## Quick Starts Pick the experience you want to ship: * [**Ask** — Quick Start](/sdk/ask/quick-start): an AI question-answering box. * [**Explore** — Quick Start](/sdk/explore/quick-start): related questions that drive on-page engagement. * [**Hybrid Search** — Quick Start](/sdk/hybrid-search/quick-start): one bar that blends keyword results with an AI answer. * [**Chat History** — Quick Start](/sdk/history/quick-start): a chat page that keeps each signed-in reader's conversations. # Ask — Quick Start Put a question box on your page. Readers ask in their own words and get an answer from your content, with citations. ![A question box, with an answer and numbered citations below it.](/images/quickstart-ask/ask-finished-page.png) Takes about ten minutes. ## Before you start **Get your publishable API key.** Copy it from **Overview** in the [Miso Dashboard](https://dojo.askmiso.com). The SDK runs in the browser, so it takes the publishable key, never the secret key. See [Authentication](/api/authentication). **Put your content in Miso.** Everything below works from your catalog. See [Integrating Your Data](/data/integrating-your-data) to upload it, and confirm the result in **Dashboard ▸ Data Sets ▸ Catalog**. > **No content of your own yet?** Load a real one in a few minutes. [Example: Wikinews](/start/example-news-site) parses a free public archive of about 20,900 news articles and sends it to Miso, so you have something to ask questions about. --- ## 1. Install the SDK ### As a node module In your project directory, run: ```bash npm npm install --save @miso.ai/client-sdk ``` Then import `MisoClient` from the SDK: ```javascript Import import MisoClient from "@miso.ai/client-sdk"; ``` ### Using a script tag ```html Script tag <script async src="https://cdn.jsdelivr.net/npm/@miso.ai/client-sdk@latest/dist/umd/miso.min.js"></script> ``` The script tag loads the SDK asynchronously, so your code must wait for it. Use the `misocmd` queue, which runs your function as soon as the SDK is ready: ```javascript Wait for the SDK const misocmd = window.misocmd || (window.misocmd = []); misocmd.push(() => { const MisoClient = window.MisoClient; // Your code goes here. }); ``` ## 2. Add the container Put this where the question box belongs: ```html Container <div id="miso-ask-combo" class="miso-ask-combo"></div> ``` ## 3. Start the workflow ```javascript Start Ask const misocmd = window.misocmd || (window.misocmd = []); misocmd.push(async () => { const client = new MisoClient("YOUR_PUBLISHABLE_API_KEY"); const workflow = client.ui.ask; await client.ui.ready; // styles are loaded const defaults = MisoClient.ui.defaults.ask; const root = document.querySelector("#miso-ask-combo"); root.innerHTML = defaults.templates.root(); workflow.autoQuery(); // read ?q= from the URL }); ``` `autoQuery()` reads the `q` parameter from the page URL and asks that question. Call `workflow.query('…')` instead to ask one yourself. --- ## The complete page ```html ask.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Miso Ask
``` ## Check it works Save the page, open it in a browser, and add `?q=media` to the URL. You get an answer from your own content, with follow-up questions and the articles it used. ![The Ask workflow, with an answer and its sources.](/images/quickstart-ask/ask-demo-result.png) If nothing appears, check these three things first: | Symptom | Cause | | ---------------------------------- | ------------------------------------------------------------------- | | The box never renders | The key is the secret key, or it is wrong. Use the publishable key. | | The answer refuses every question | The catalog is empty, or the upload is still running. | | The page is blank until you reload | Your code ran before the SDK loaded. Use the `misocmd` queue. | ## Next * [API Configuration](/sdk/ask/api-config) — which articles the answers can cite. * [Events](/sdk/ask/events) — run your own code at each step of a question. * [Citation Links](/sdk/ask/citation-links) — the class, the attributes and the tooltip of each citation. * [Explore — Quick Start](/sdk/explore/quick-start) — related questions on an article page. * [Hybrid Search — Quick Start](/sdk/hybrid-search/quick-start) — search results and an answer together. * [UI Customization](/sdk/ask/ui-customization) — change the headings, the parts and the order of the page. * [Answer Response Fields](/api/genai/answer-fields) — the API behind the workflow, for your own front end. # Ask — API Configuration Choose which articles Ask can cite in its answers, and change the response before Ask shows it. `useApi` takes the request body that Ask sends to the [Answer API](/api/genai/answer). The question comes from the reader, and the other fields control the answer. ## Filter the source articles `fq` restricts which articles an answer can cite. It takes the same [filter syntax](/api/fq) as every other Miso endpoint. Set it on `client.ui.asks`, the context that covers every Ask workflow on the page. Each follow-up answer is a new workflow, so a filter on `client.ui.ask` does not reach it. ```javascript Markets coverage only client.ui.asks.useApi({ fq: 'categories:"Markets"', }); ``` Filter values are matched exactly. Check yours against the rules for [case](/api/fq#values-are-case-sensitive) and [quoting](/api/fq#quote-any-value-with-a-space). To change the filter while the page runs, see [Filtering (fq)](/sdk/filtering#change-it-while-the-page-runs). ## Change the response `useDataProcessor` takes a function that gets each response before Ask renders it. `data.value` holds the [Answer API](/api/genai/answer) response, with `answer`, `sources` and the other fields. Return `data`, changed or not. Set it on `client.ui.asks`, so that follow-up answers get it too. This one takes the site name off the end of each source title: ```javascript Shorter source titles client.ui.asks.useDataProcessor((data) => { const { value } = data; if (!value || !value.sources) { return data; } return { ...data, value: { ...value, sources: value.sources.map((source) => ({ ...source, title: source.title.replace(/ \| Example News$/, ""), })), }, }; }); ``` The SDK calls the function each time the data changes. Before the response arrives, `data.value` is `undefined`, and while the answer streams in, the function runs again on each new part. Check for the field you change, and return `data` as it is when the field is missing. Each call to `useDataProcessor` adds a function, and the functions run in the order you add them. `clearDataProcessor()` removes the ones added on the same object. # Ask — UI Customization Change the headings, the parts and the order of the Ask page, and choose when each part shows. The quick start writes the page with the SDK's template helpers. Below we change the text they write, add a notice under every answer, and then take over the HTML. Last, `visible-when` decides when each part shows. You need a working Ask page first. See [Ask — Quick Start](/sdk/ask/quick-start). ## How the templates build the page Two functions in `MisoClient.ui.defaults.ask.templates` return the HTML: | Template | What it returns | | ------------------- | ------------------------------------------------------------------------------------------------------------- | | `root(options)` | The question box, the first answer, and a `` element. | | `followUp(options)` | One follow-up answer. The SDK calls it for each follow-up question, and adds the HTML to ``. | The quick start puts `root()` in the page. Give the SDK your version of `followUp` with `useTemplates` on `client.ui.asks`, the context. A change that belongs on every answer goes into both templates. Since 1.12.5 `useTemplates`. ## Change the headings Pass your own text in `phrases`, to both templates: ```javascript Your own headings const templates = MisoClient.ui.defaults.ask.templates; const phrases = { question: "Your question", sources: "Sources", followUpQuestions: "Ask next", }; client.ui.asks.useTemplates({ followUp: (args) => templates.followUp({ ...args, phrases }), }); const root = document.querySelector("#miso-ask-combo"); root.innerHTML = templates.root({ phrases }); ``` Keep `...args`. It carries `parentQuestionId`, which ties each follow-up answer to its question. | Key | Default text | | ------------------- | --------------------------------------------- | | `question` | You asked... | | `thoughts` | Thoughts | | `sources` | This reply is based on the following articles | | `followUpQuestions` | Related questions you can explore | | `relatedResources` | Go beyond, and learn more about this topic | `relatedResources` is in `root()` only. ## Add or remove a part A template returns a string, so you can change the string before it goes into the page. This adds a notice under the feedback buttons of every answer: ```javascript A notice under every answer const templates = MisoClient.ui.defaults.ask.templates; function addNotice(html) { return html.replace( "", "" + '

AI answers can contain mistakes. Check the sources.

' ); } client.ui.asks.useTemplates({ followUp: (args) => addNotice(templates.followUp(args)), }); const root = document.querySelector("#miso-ask-combo"); root.innerHTML = addNotice(templates.root()); ``` To remove a part, replace its element with an empty string. This removes the feedback buttons: ```javascript No feedback buttons function removeFeedback(html) { return html.replace("", ""); } ``` Pass it to both templates, the same way as `addNotice`. ## Write the HTML yourself To change the order, start from the HTML that `root()` returns. Print it in the browser console on a page that loads the SDK: ```javascript Print the default HTML console.log(MisoClient.ui.defaults.ask.templates.root()); ``` Put the HTML in the page, inside the container, and edit it there. Then remove the `root.innerHTML` line from your script. This version shows the sources above the answer, and leaves out the thoughts box and the related articles: ```html Sources above the answer
You asked...

Sources

``` Keep these when you edit: | Keep | Because | | --------------------------------------- | ------------------------------------------------------------------------- | | Each Miso element inside a `` | `` connects the elements in it to the workflow. | | The class names | The default styles select them. | | `logo="false"` | Without it, a `` that holds `` adds the Miso logo. | | `miso-circled-citation-index` | It draws each citation number in a circle. | | `` | Follow-up answers go into it. Leave it out to stop at one answer. | Follow-up answers still come from `followUp()`. To change their order too, give `useTemplates` a function that returns your HTML. Put `parent-question-id="${parentQuestionId}"` on each `` in it, as `followUp()` does. ## Show a part at the right moment The `visible-when` attribute shows an element only in the states it names. Put it on a ``, or on an element inside one. The templates use it on each part. The answer has `visible-when="ready"`, so it stays hidden until the answer starts to arrive. The query box of a follow-up has `visible-when="initial loading"`, so it hides when its answer arrives. | Value | Shows the element when | | ----------- | ---------------------------------------------------- | | `initial` | The workflow has not sent a request yet. | | `loading` | The request is out, and no data has arrived. | | `ready` | The data is arriving or has arrived. | | `ongoing` | The data is still arriving. | | `done` | All the data has arrived. | | `erroneous` | The request failed. | | `empty` | No Miso element in the container has data. | | `nonempty` | At least one Miso element in the container has data. | * Separate values with spaces to show the element in any of them: `visible-when="initial loading"`. * Join a state to `empty` or `nonempty` with `+` to need both: `visible-when="ready+empty"`. * Only the Miso elements that show data count toward `empty` and `nonempty`. The query box and the buttons do not. * The SDK shows the element with `display: block !important`. To lay it out as a flex row or a grid, put `visible-when` on a wrapper around it. The notice from [Add or remove a part](#add-or-remove-a-part) shows as soon as the answer starts. To show it only when the answer is complete, add `visible-when="done"`: ```html Notice after the answer

AI answers can contain mistakes. Check the sources.

``` To show a message when a question fails, add this to the answer section: ```html Error message ``` ## If it does not work | Symptom | Cause | | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | | Follow-up answers have the old look | The change went into `root()` only. Give `followUp` to `useTemplates` too. | | The console shows `… needs to be placed under a workflow container element` | A Miso element is outside every ``. | | An element with `visible-when` always shows | The attribute name is wrong, or the element is outside every ``. The name is `visible-when`. | | A flex row breaks into lines when it shows | `visible-when` sets `display: block`. Put it on a wrapper. | | The console shows `useTemplates is not a function` | The SDK is older than 1.12.5. | ## Next * [Sources and Related Resources](/sdk/ask/sources) — where the links open, the date format, and the fields and layout of each list. * [Citation Links](/sdk/ask/citation-links) — the class, the attributes and the tooltip of each citation. * [Events](/sdk/ask/events) — run your own code at each step of a question. # Ask — Sources and Related Resources Change how Ask lists articles: where the links open, how the dates read, the layout, and the markup of each item. Ask lists articles in two places: the sources that an answer cites, and the related resources under the answer. Below we open the links in the same tab, change the date format, switch the related resources to cards, and then write the markup of an item, with the authors added. You need a working Ask page first. See [Ask — Quick Start](/sdk/ask/quick-start). ## The two lists | Element | What it lists | Fields from | Layout | | -------------------------- | -------------------------------------------------------------------- | --------------------- | ------ | | `` | The articles that the answer cites, numbered to match the citations. | `source_fl` | `list` | | `` | More articles on the topic of the question. | `related_resource_fl` | `list` | Each change below goes to `useLayouts` on `client.ui.asks`, the context, so that follow-up answers get it too. The key is the role of the list: `sources` or `related_resources`. Your options are merged over the defaults, so set only what you change. Set them before the template goes into the page. ## Open links in the same tab Each item is a link to the article's `url`, and it opens in a new tab. To open it in the same tab, set `link.open` to `false`: ```javascript Links in the same tab client.ui.asks.useLayouts({ sources: { link: { open: false } }, related_resources: { link: { open: false } }, }); ``` | `link` option | Default | What it does | | ------------- | ------------ | ------------------------------------------------------------------------- | | `open` | `true` | `false` leaves out `target` and `rel`, so the link opens in the same tab. | | `target` | `"_blank"` | The `target` attribute of the link. | | `rel` | `"noopener"` | The `rel` attribute of the link. | ## Change the date format Each item shows `published_at`, or `created_at` or `updated_at` when the record has no `published_at`. The default format is `Mar 5, 2026`. Give the `date` template the options of [`toLocaleDateString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString), with `locale` added: ```javascript 5 March 2026 const dateFormat = { locale: "en-GB", year: "numeric", month: "long", day: "numeric" }; client.ui.asks.useLayouts({ sources: { templates: { date: dateFormat } }, related_resources: { templates: { date: dateFormat } }, }); ``` `date` can also be a locale string, such as `"de-DE"`, or a function that gets the date value from the record and returns the text. ## Change the layout Give the layout type before the options. This shows the related resources as cards, and keeps their links in the same tab: ```javascript Related resources as cards client.ui.asks.useLayouts({ related_resources: ["cards", { link: { open: false } }], }); ``` | Type | What the reader sees | | ---------- | ----------------------------------------- | | `list` | One item on each row. The default. | | `cards` | Items side by side, in a grid. | | `carousel` | One row of items, with buttons to scroll. | ## Write the markup of an item To draw an item your own way, give the `article` template. This one shows the number, the title, the authors and the date of each source. An item can show only the fields that the request asks for, so first add `authors` to the field list. The list replaces its default, so keep the fields that the page still uses: ```javascript Ask for the authors client.ui.asks.useApi({ source_fl: ["cover_image", "url", "created_at", "updated_at", "published_at", "authors"], }); ``` Then write the template. Start it with `tagPair`, which returns the opening and closing tag of the item. The tags link to the article and carry the attributes that the SDK uses to record clicks: ```javascript Number, title, authors and date function renderArticle(layout, state, data, meta) { const { tagPair, escapeHtml } = layout.templates.helpers; const [openTag, closeTag] = tagPair(layout, data); const authors = (data.authors || []).map(escapeHtml).join(", "); const date = data.published_at ? new Date(data.published_at).toLocaleDateString("en-US", { dateStyle: "medium" }) : ""; return openTag + `` + `
${escapeHtml(data.title)}
` + `` + closeTag; } client.ui.asks.useLayouts({ sources: { templates: { article: renderArticle } }, }); ``` | Argument | What it holds | | -------- | ------------------------------------------------------------------------------------------------------------------ | | `layout` | The layout. `layout.templates.helpers` has `tagPair` and `escapeHtml`. | | `state` | The state of the whole list. | | `data` | The article, with the fields from `source_fl` or `related_resource_fl`. `product_id` and `title` are always there. | | `meta` | `meta.index` is the position of the item, counted from 0. | Keep these in mind when you write one: * **The number of a source.** The `miso-citation-index` element draws it, in the same style as the citations in the answer. Use `meta.index + 1`, so that `[1]` in the answer points to the first source. Leave it out for related resources, which are not cited. * **Escape every value from the record** with `escapeHtml`. * **Format the date yourself.** The `date` option applies to the default markup only. * **Style your own classes** in your CSS. ## If it does not work | Symptom | Cause | | ------------------------------------------- | ------------------------------------------------------------- | | A field shows `undefined` | It is not in `source_fl` or `related_resource_fl`. | | Follow-up answers have the old look | The layout is on `client.ui.ask`. Set it on `client.ui.asks`. | | The SDK stops recording clicks on the items | The `article` template does not use `tagPair`. | | The sources have no numbers | The `article` template has no `miso-citation-index` element. | ## Next * [UI Customization](/sdk/ask/ui-customization) — change the headings, the parts and the order of the page. * [Citation Links](/sdk/ask/citation-links) — the class, the attributes and the tooltip of each citation. # Ask — Citation Links Change the class, the attributes, the URL and the tooltip of each citation link in an answer. Each `[1]` in an answer is a link to the source it cites. Below we hook into every citation link, mark it with a class and a data attribute, add a tracking parameter to its URL, give it a tooltip, and then read a field that the response does not send by default. You need a working Ask page first. See [Ask — Quick Start](/sdk/ask/quick-start). ## Customize each link Give the answer layout an `onCitationLink` function. Set it on `client.ui.asks`, the context, so follow-up answers get it too: ```javascript A class and a data attribute function onCitationLink({ addClass, setAttribute }, { source }) { addClass("my-citation-link"); if (!source) { return; } setAttribute("data-title", source.title); } client.ui.asks.useLayouts({ answer: { onCitationLink }, }); ``` The second argument is `{ source, index }`. `source` is the cited item from the response's `sources`, and `index` is its position, counted from 0. `source` can be `undefined`, so check it before you read from it. The first argument holds the methods that change the link: | Method | What it does | | -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | `addClass(name)`, `removeClass(name)` | Add or remove a class on the link. | | `setAttribute(key, value)`, `removeAttribute(key)` | Set or remove an attribute, such as `data-title`. The SDK escapes the value. Use `addClass` for classes. | | `setHref(href)` | Set the URL that the link opens. Pass a string, or a function that gets the current URL and returns the new one.Since 1.14.1 | | `setTooltipText(text)` | Show plain text in the tooltip. | | `setTooltipHtml(html)` | Show HTML in the tooltip. Escape every value from `source` with `escapeHtml`. | | `escapeHtml(text)` | Escape text for use in HTML. | The SDK calls the function each time it renders the answer, and it renders the answer many times as the text streams in. Only change the link inside the function. ## Change the URL Since 1.14.1 Each link opens the URL that the answer gives it. Change it with `setHref`. This one adds a `utm_source` parameter: ```javascript A tracking parameter on every link function onCitationLink({ setHref }) { setHref((href) => { const url = new URL(href, window.location.href); url.searchParams.set("utm_source", "miso"); return url.href; }); } ``` Use `setHref` for the URL, not `setAttribute("href", …)`. `setAttribute` escapes the value, which breaks a URL that has `&` in it. ## Add a tooltip Put content in the link's tooltip with `setTooltipText` or `setTooltipHtml`. This one shows the source's title and date: ```javascript Title and date in a tooltip function onCitationLink({ setTooltipHtml, escapeHtml }, { source }) { if (!source) { return; } const date = new Date(source.published_at).toLocaleDateString(); setTooltipHtml( `${escapeHtml(source.title)}` + `${date}` ); } ``` The SDK styles already place the tooltip above the link and show it on hover. Style what you put inside it: ```css Tooltip content .miso-citation-tooltip .title { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; width: max-content; max-width: 12rem; overflow: hidden; font-weight: 600; } .miso-citation-tooltip .date { display: block; margin-top: 0.5em; } ``` ## Use more source fields `source` carries only the fields that the request asks for. `product_id` and `title` always arrive, whether `source_fl` names them or not. By default, the Ask workflow requests these fields: ```js Default source_fl ["cover_image", "url", "created_at", "updated_at", "published_at"] ``` To read any other field, name it in `source_fl` in the request payload. The list replaces the default, so keep the fields that the page still uses. The source list under the answer draws `cover_image` and `url`. ```javascript Add the authors client.ui.asks.useApi({ source_fl: ["cover_image", "url", "created_at", "updated_at", "published_at", "authors"], }); ``` `source.authors` is then available in `onCitationLink`. A custom attribute uses its dotted path, such as `custom_attributes.section`. See `source_fl` on the question request in the [API Reference](/api/reference/tag/ask-apis), and the field names in [Product Schema](/data/product-schema). ## If it does not work | Symptom | Cause | | ---------------------------------------------- | -------------------------------------------------------------------------- | | The tooltip shows `undefined` | The field is not in `source_fl`. | | Follow-up answers have plain links | The layout is on `client.ui.ask`. Set it on `client.ui.asks`. | | The tooltip shows raw tags | The HTML went to `setTooltipText`. Use `setTooltipHtml`. | | The console shows `setHref is not a function` | The SDK is older than 1.14.1. | | Nothing changes and error shown in console log | The function throws. The SDK logs the error and leaves the link as it was. | # Ask — Events Run your own code when a question goes out, when its answer shows and finishes, and when the reader rates it. The Ask workflow emits an event at each step of a question. Below we listen to one, list the events a question goes through, and then look at the `data` event, which tracks the response itself. You need a working Ask page first. See [Ask — Quick Start](/sdk/ask/quick-start). ## Listen to an event Call `on` with the event name and a function. Set it on `client.ui.asks`, the context, so follow-up answers emit to it too: ```javascript Log each finished answer const off = client.ui.asks.on("done", ({ workflow }) => { console.log("Answer done", workflow.questionId); }); ``` Each event on the context carries `workflow`, the Ask workflow that emitted it. Its `questionId` is the question the event belongs to. For a follow-up, that is different from `client.ui.ask.questionId`, the first question of the thread. `on` returns a function. Call it to remove the listener: ```javascript Remove the listener off(); ``` To listen to the first question only, call `on` on `client.ui.ask`. Events on a single workflow do not carry `workflow`. ## Lifecycle events Each question goes through these events in order. Each one fires at most once for a question: | Event | Fires when | | --------------------- | ------------------------------------------------------------------------------------ | | `request` | The SDK sends the question to Miso. `payload` is the request body. | | `loading` | The request is out, and the SDK waits for the answer. | | `ready` | The answer starts to show. | | `blocked`Since 1.13.0 | Miso withheld the answer, for example at a metering limit. `blockedReason` says why. | | `done` | The full answer is on screen. | | `interrupt` | A new question replaced this one before its answer finished. | | `error` | The question failed. | | `finally` | The question has ended, in any of the three ways above. | A question always ends with one of `done`, `interrupt` and `error`, and then with `finally`. Use `finally` for clean-up that has to run each time, such as hiding a spinner of your own. `ready` and `done` follow what is on screen. `done` fires when the last word of the answer shows, which is after the last part of the response arrives. To act on the response as it arrives, use the [`data` event](#the-data-event). Apart from `request`, these events carry: | Property | What it holds | | --------- | --------------------------------------------------------------- | | `session` | The session of the question. A new question gets a new session. | | `status` | `loading`, `ready` or `erroneous`. | | `ongoing` | `true` while more of the answer is on the way. | The SDK also emits `answer-stage` each time the progress label of the answer changes, with the label in `answer_stage`. Use it for display only. The labels change without notice, so do not branch on them. See [Answer API](/api/genai/answer). ## Feedback event `feedback` fires when the reader clicks **Helpful** or **Not helpful** under an answer: ```javascript Act on feedback client.ui.asks.on("feedback", ({ workflow, value, unselected }) => { if (unselected) { return; // the reader cleared their choice } console.log(workflow.questionId, value); }); ``` `value` is `helpful` or `unhelpful`. A second click on the same button clears the choice. The event then carries `unselected: true` and no `value`. The SDK sends the feedback to Miso by itself. Listen to this event only to send it somewhere else as well, such as to [Google Analytics 4](/sdk/ask/ga4). ## The data event `data` fires each time the data of the workflow changes. That includes a new question, the request going out, and each part of the response as it streams in. ```javascript Read the sources of a complete response client.ui.asks.on("data", ({ workflow, status, ongoing, value }) => { if (status !== "ready" || ongoing) { return; } console.log(workflow.questionId, value.sources); }); ``` The event carries the data object: | Property | What it holds | | --------- | -------------------------------------------------------------------------------------------- | | `session` | The session of the question. | | `status` | `initial`, `loading`, `ready` or `erroneous`. | | `ongoing` | `true` while more of the response is on the way. Set only when `status` is `ready`. | | `request` | The request that the SDK sent, with the body in `request.payload`. | | `value` | The [Answer API](/api/genai/answer) response, with `answer`, `sources` and the other fields. | | `error` | The error, when `status` is `erroneous`. | For one question, `data` fires in this order: 1. `status: "initial"` when the new question starts, with no `request` yet. 2. `status: "loading"` when the request goes out. 3. `status: "ready"` and `ongoing: true` for each part of the response. This repeats as the answer streams in. 4. `status: "ready"` and `ongoing: false` when the response is complete. If the question fails, the last one has `status: "erroneous"` instead. The event shows the data after each [data processor](/sdk/ask/api-config#change-the-response) has run, so a field you changed there arrives changed here. The event cannot change the data. To change what Ask shows, use `useDataProcessor`. `data` comes before the lifecycle events. The response is complete at `ongoing: false`, but the answer can still be typing out on screen until `done`. ## If it does not work | Symptom | Cause | | ----------------------------------------------- | ------------------------------------------------------------------------------------------------ | | Follow-up answers emit nothing | The listener is on `client.ui.ask`. Set it on `client.ui.asks`. | | `workflow` is `undefined` | The listener is on a single workflow. Events there do not carry `workflow`. | | `value` is `undefined` in `data` | The response has not arrived yet. Check `status` first. | | A listener runs many times for one answer | It listens to `data`, which fires for each part of the response. Use `done`, or check `ongoing`. | | Nothing fires and an error shows in the console | The function throws. The SDK logs the error and goes on. | ## Next * [API Configuration](/sdk/ask/api-config) — change the request and the response. * [Ask — Google Analytics 4](/sdk/ask/ga4) — send these events to GA4. # Ask — Interactions See what the Ask workflow reports to Miso as a reader uses the question box, and send the same records yourself when you render part of it on your own. Each record is an interaction: a reader saw, scrolled to, clicked or rated something. Miso builds the answer metrics in Dojo from them. Below we list the interactions Ask sends, the fields Miso needs on each one, and then send one by hand. You need a working Ask page first. See [Ask — Quick Start](/sdk/ask/quick-start). ## What Ask sends The SDK watches each part of the answer and sends an interaction when the reader acts on it. `property` names the part: | Property | Element | Types | Subject | | ------------------------------ | ---------------------------- | -------------------------------------------- | ------------------------------------------------------ | | `sources` | `` | `impression`, `viewable_impression`, `click` | `product_ids` of the articles | | `related_resources` | `` | `impression`, `viewable_impression`, `click` | `product_ids` of the articles | | `images` | `` | `impression`, `viewable_impression`, `click` | `product_ids` of the images | | `affiliation` | `` | `impression`, `viewable_impression`, `click` | The affiliate products, with `channel` and `positions` | | `suggested_followup_questions` | `` | `impression`, `viewable_impression`, `click` | `items`, the question texts | | `answer` | `` | `click` | `items`, the link texts, with `urls` | A click on a citation in the answer, such as `[2]`, counts as a click on that source. It goes out as a `sources` click with `event_target: "citation-link"`, so you can tell it apart from a click in the source list. The rating buttons send one more type. When the reader clicks **Helpful** or **Not helpful**, Ask sends `type: "feedback"` with `result_type: "answer"` and `value` set to `helpful` or `unhelpful`. A second click on the same button clears the rating and sends `value: "unselected"`. This record has no `property`. The types mean: | Type | The reader | | --------------------- | ----------------------------------------------------- | | `impression` | Has the part on the page, seen or not. | | `viewable_impression` | Has at least half of the part in view for one second. | | `click` | Clicks a link in the part. | | `feedback` | Rates the answer. | Each part sends `impression` and `viewable_impression` once for each answer. A follow-up answer is a new question, so its parts send their own. ## What a record holds A click on the second citation of a follow-up answer goes out like this: ```json A citation click { "type": "click", "product_ids": ["article-1042"], "anonymous_id": "5f6a7b8c-9d0e-…", "context": { "custom_context": { "api_group": "ask", "api_name": "questions", "property": "sources", "event_target": "citation-link", "question_id": "0e1f2a3b-4c5d-…", "root_question_id": "9a8b7c6d-5e4f-…", "parent_question_id": "9a8b7c6d-5e4f-…", "question_source": "_organic", "workflow": "ask" } } } ``` The fields mean: | Field | Value | | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | | `type` | One of the types above. | | `product_ids` | The `product_id` of each article, image or product the reader acted on. `[]` for a part whose subjects are text. | | `anonymous_id`, `user_id` | The reader, from [the client context](/sdk/user-type). | | `value`, `result_type` | On `feedback` only: the rating, and `answer`. | | `context.custom_context.api_group` | `ask` | | `context.custom_context.api_name` | `questions` | | `context.custom_context.workflow` | `ask` | | `context.custom_context.property` | One of the properties above. Absent on `feedback`. | | `context.custom_context.items` | The texts the reader acted on, for `suggested_followup_questions` and `answer`. | | `context.custom_context.event_target` | `citation-link` on a citation click. | | `context.custom_context.question_id` | The `question_id` of the answer the part belongs to. | | `context.custom_context.root_question_id` | The `question_id` of the first question in the thread. On the first question, this is the same as `question_id`. | | `context.custom_context.parent_question_id` | On a follow-up, the question it follows. | | `context.custom_context.question_source` | How the reader asked: `_organic` for a typed question, `_suggested_questions` for a click on a follow-up question. | ## Send an interaction yourself Send your own when you render a part of the answer with your own code, for example a list of sources you build from the [`data` event](/sdk/ask/events#the-data-event). Ask cannot see clicks in markup it did not render. Turn off the SDK's tracker for that part first, so the same click does not count twice: ```javascript Stop tracking sources client.ui.asks.useTrackers({ sources: { active: false } }); ``` To track every part yourself, turn off all the trackers: ```javascript Stop all tracking client.ui.asks.useTrackers(false); ``` Then call `client.api.interactions.upload` with the fields above. Pass it the `workflow` and `request` from the `data` event you rendered the list from. `client.ui.ask` is the first question of the thread: ```javascript Report a source click function reportSourceClick(client, { workflow, request }, productId) { const { metadata = {} } = request.payload; client.api.interactions.upload({ type: "click", product_ids: [productId], context: { custom_context: { api_group: "ask", api_name: "questions", workflow: "ask", property: "sources", question_id: workflow.questionId, root_question_id: client.ui.ask.questionId, parent_question_id: workflow.parentQuestionId, question_source: metadata.question_source, }, }, }); } ``` The SDK adds the reader's `anonymous_id` or `user_id` and the page URL for you. Send `impression` and `viewable_impression` for the same list too, or the click-through rate for that part has nothing to divide by. From a server, or with no SDK on the page, send the same record to `POST /v1/interactions`. See the [API Reference](/api/reference). ## If it does not work | Symptom | Cause | | ----------------------------------------------------------------- | ------------------------------------------------------------------------------ | | Clicks count twice | The SDK tracker for that part is still on. Turn it off with `useTrackers`. | | A part shows clicks but no click-through rate | Only `click` is sent. Send `impression` and `viewable_impression` as well. | | Follow-up clicks count toward the first question | `question_id` is the root question. Take it from `workflow.questionId`. | | Nothing reaches Miso and the console warns about a playground app | Miso does not store interactions for a playground app. Use your own app's key. | ## Next * [Ask — Events](/sdk/ask/events) — the events that carry `workflow` and the response. * [Answer Metrics](/operate/answer-metrics) — the reports Miso builds from these interactions. # Ask — Google Analytics 4 Give Miso the reader id GA4 already has, and send what happens in the question box to GA4 as events. Your GA4 property knows who is on the page. Miso's question box knows what they asked, what they read, and whether the answer helped. Below we join the two: one reader id on both sides, then five GA4 events fired from the Ask workflow's own hooks. You need gtag.js and the SDK on the page. See [Ask — Quick Start](/sdk/ask/quick-start) for the SDK install. --- ## One reader id on both sides GA4 knows every browser by a `client_id`, and a signed-in reader by a `user_id` on top. Miso has the same pair: `anonymous_id` for the browser and `user_id` for the reader. Give Miso the GA4 values for both, and a report in either system can be joined to the other, before and after sign-in. | Id | GA4 | Miso | | -------------------------- | ------------------------------ | ------------------------------------------------------ | | The browser, always | `client_id`, minted by gtag.js | `client.context.anonymous_id`, set to that `client_id` | | The reader, when signed in | `user_id`, set by you | `client.context.user_id`, the same value | The SDK reads the ids from `client.context` at the moment it sends a request, so the handoff runs before the first request. The function below does the handoff. It goes in a script of its own, or at the top of the SDK script: ```javascript ga4Ids() // If gtag.js has not run yet, define the queue it expects. The calls below then // wait in dataLayer until it loads. Harmless when the gtag snippet already ran. window.dataLayer = window.dataLayer || []; window.gtag = window.gtag || function () { dataLayer.push(arguments); }; // Give Miso the GA4 ids. Resolves true when GA4 answered, false when it did not. async function ga4Ids(client, measurementId) { if (window.READER_ID) { client.context.user_id = READER_ID; client.context.user_type = "subscriber"; // if you meter, see /operate/metering } const clientId = await new Promise((resolve) => { gtag("get", measurementId, "client_id", resolve); setTimeout(() => resolve(null), 2000); }); if (!clientId) { return false; } client.context.anonymous_id = clientId; if (window.READER_ID) { gtag("config", measurementId, { user_id: READER_ID }); } return true; } ``` Three names in there are yours: * `G-XXXXXXXXXX`, the argument you pass as `measurementId`, is the **Measurement ID** of your GA4 web data stream. It is under **Admin › Data streams › your stream** in GA4, and in your existing gtag snippet after `gtag/js?id=`. * `READER_ID` stands for wherever your page keeps the signed-in reader's id: a global your template writes, a cookie, or your auth library. * `"subscriber"` is the reader's tier, when you meter. The return value is the all-or-none switch. When gtag.js is blocked, or loads after the two seconds, GA4 never answers with a `client_id`. The function then returns false and the page skips every GA4 event, so a session is either fully joined or absent from GA4. Miso still receives `user_id` and its own `anonymous_id`, and the answer box starts. With Google Tag Manager there is no gtag.js on the page. Read the browser id from the `_ga` cookie instead, whose value is `GA1.1.` followed by the `client_id`, and send the events through `dataLayer` and a GTM trigger: ```javascript client_id from the cookie const match = document.cookie.match(/(?:^|; )_ga=GA\d\.\d\.([^;]+)/); if (match) { client.context.anonymous_id = match[1]; } ``` --- ## Send question events to GA4 The Ask workflow emits an event at each step of a question. In the following function, we turn five of them into GA4 events: ```javascript ga4AskEvents() function ga4AskEvents(client) { const asks = client.ui.asks; asks.on("request", ({ payload }) => { gtag("event", "miso_question", { question: payload.question.slice(0, 100), question_source: (payload.metadata || {}).question_source, parent_question_id: payload.parent_question_id, }); }); asks.on("ready", ({ workflow }) => { gtag("event", "miso_answer", { question_id: workflow.questionId }); }); asks.on("error", ({ workflow }) => { gtag("event", "miso_answer_error", { question_id: workflow.questionId }); }); asks.on("feedback", ({ workflow, value }) => { gtag("event", "miso_feedback", { question_id: workflow.questionId, value }); }); asks.on("tracker", ({ workflow, type, role, event_target, items }) => { if (type !== "click" || role !== "sources" || event_target !== "citation-link") { return; } gtag("event", "miso_citation_click", { question_id: workflow.questionId, product_id: items[0], }); }); } ``` | Ask hook | GA4 event | Fires when | | -------------------------------------------------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `request` | `miso_question` | A question goes to Miso. `question_source` says how: `_organic` for a typed question, `_suggested_questions` for a click on a related question. A follow-up carries `parent_question_id`. | | `ready` | `miso_answer` | The answer has arrived and starts to show. `done` fires later, once the last word is on screen. | | `error` | `miso_answer_error` | The question failed. | | `feedback` | `miso_feedback` | The reader clicks Helpful or Not helpful. `value` is `helpful` or `unhelpful`. | | `tracker`, a `click` on `sources` from a `citation-link` | `miso_citation_click` | The reader opens a cited article. `product_id` is the article. | Every hook hands you the `workflow` that owns the event. Its `questionId` is the question the event belongs to, which for a follow-up differs from `client.ui.ask.questionId`, the root of the thread. A related question the reader clicks is a new question, so it arrives as its own `miso_question` and `miso_answer` pair. GA4 keeps event names to 40 characters, parameter names to 40, and parameter values to 100. That is why `question` is cut at 100. To see a parameter in reports, register it as a custom dimension under **Admin › Custom definitions**. --- ## Put it together The id handoff and the styles load side by side, and the question box starts when both are in: ```javascript Start Ask with GA4 const misocmd = window.misocmd || (window.misocmd = []); misocmd.push(async () => { const client = new MisoClient("YOUR_PUBLISHABLE_API_KEY"); const [ga4] = await Promise.all([ga4Ids(client, "G-XXXXXXXXXX"), client.ui.ready]); if (ga4) { ga4AskEvents(client); } const root = document.querySelector("#miso-ask-combo"); root.innerHTML = MisoClient.ui.defaults.ask.templates.root(); client.ui.ask.autoQuery(); // the first request goes out here }); ``` --- ## What stays with Miso The SDK already reports to Miso on its own: which sources were shown and seen, which were clicked, and the reader's feedback. Dojo builds its answer metrics from those, so there is no need to send the same to GA4 twice. The events above give GA4 what it is good at: the question box as a step in the reader's session, next to page views, sign-ups and subscriptions. --- ## Check it 1. On a test page, add `debug_mode: true` to the config call in your gtag snippet, so the page reports to DebugView: ```javascript gtag snippet, debug on gtag("config", "G-XXXXXXXXXX", { debug_mode: true }); ``` To test a live page without editing it, install the [Google Analytics Debugger](https://chromewebstore.google.com/detail/google-analytics-debugger/jnkmfdileelhofjcijamephohjechhna) extension and turn it on. It puts the browser in debug mode for every page. 2. Load the page, ask a question, click a citation, click Helpful. 3. In GA4, open **Admin › DebugView** and pick your device in the top-left list. Each event appears in the timeline with its parameters. --- ## Summary | Step | What you did | | ------------- | ------------------------------------------------------------------------------------------- | | One reader id | GA4's `client_id` is Miso's `anonymous_id`, and your `user_id` is on both when signed in. | | All or none | No `client_id` from GA4 means no GA4 events, and the answer box starts anyway. | | Events | `miso_question`, `miso_answer`, `miso_answer_error`, `miso_feedback`, `miso_citation_click` | ## Next * [Explore — Google Analytics 4](/sdk/explore/ga4) — the same for related questions on an article page. # Explore — Quick Start Suggest questions on an article page. Miso generates questions for each article. A reader picks one and lands on your answers page. ![A placeholder article, with four suggested questions and a question box below it.](/images/quickstart-ask/explore-finished-page.png) Shown under a placeholder article. Takes about ten minutes. ## Before you start **Explore needs activation for your environment.** Miso generates the related questions on a schedule, and that job runs only for the environments Miso turns it on for. Ask your Miso representative, or write to , before you start. **Get your publishable API key.** Copy it from **Overview** in the [Miso Dashboard](https://dojo.askmiso.com). The SDK runs in the browser, so it takes the publishable key, never the secret key. See [Authentication](/api/authentication). **Put your content in Miso.** Everything below works from your catalog. See [Integrating Your Data](/data/integrating-your-data) to upload it, and confirm the result in **Dashboard ▸ Data Sets ▸ Catalog**. > **No content of your own yet?** Load a real one in a few minutes. [Example: Wikinews](/start/example-news-site) parses a free public archive of about 20,900 news articles and sends it to Miso, so you have something to ask questions about. **Have an answers page.** A reader who picks a question needs somewhere to land. Build it with [Ask — Quick Start](/sdk/ask/quick-start) first, or point `useLink` at any page that accepts a question. --- ## 1. Install the SDK ### As a node module In your project directory, run: ```bash npm npm install --save @miso.ai/client-sdk ``` Then import `MisoClient` from the SDK: ```javascript Import import MisoClient from "@miso.ai/client-sdk"; ``` ### Using a script tag ```html Script tag ``` The script tag loads the SDK asynchronously, so your code must wait for it. Use the `misocmd` queue, which runs your function as soon as the SDK is ready: ```javascript Wait for the SDK const misocmd = window.misocmd || (window.misocmd = []); misocmd.push(() => { const MisoClient = window.MisoClient; // Your code goes here. }); ``` ## 2. Add the elements Put the Miso elements where the questions belong, usually under the article body: ```html Elements ``` `miso-related-questions` lists the generated questions. `miso-query` adds a box for a reader who wants to ask their own. ## 3. Start the workflow ```javascript Start Explore const misocmd = window.misocmd || (window.misocmd = []); misocmd.push(() => { const client = new MisoClient("YOUR_PUBLISHABLE_API_KEY"); const workflow = client.ui.explore; // Which article to generate questions for. This id must exist // in your catalog. workflow.useApi({ product_id: "art_001" }); // Where a question sends the reader. workflow.useLink(question => `/ask.html?q=${encodeURIComponent(question)}`); workflow.start(); }); ``` Three things to set: | Call | What it controls | | ------------------------ | ---------------------------------------------------------------------------------- | | `useApi({ product_id })` | The article Miso reads. Render this from your CMS, so each page passes its own id. | | `useLink(fn)` | The destination. Return the URL of your answers page. | | `start()` | Runs the workflow and renders the questions. | --- ## The complete page ```html explore.html Miso Explore

Your article title

The article body.

``` ## Check it works Open the page. Miso lists questions about that one article. Select one, and your answers page opens with the question in the URL. ![The related-questions panel under an article.](/images/quickstart-ask/ask-demo-related-questions.png) | Symptom | Cause | | ------------------------------- | ---------------------------------------------------------------------------------------- | | No questions appear | Explore is not enabled for this environment, or the `product_id` is not in your catalog. | | The questions are generic | The article has little text. Send the body in `html` or `description`. | | A question opens the wrong page | `useLink` returns a path your site does not serve. | ## Next * [UI Customization](/sdk/explore/ui-customization) — change the parts around the questions, and when they show. * [Ask — Quick Start](/sdk/ask/quick-start) — the answers page these questions lead to. * [Hybrid Search — Quick Start](/sdk/hybrid-search/quick-start) — search results and an answer together. * [API Configuration](/sdk/explore/api-config) — how many questions, and which articles they come from. * [Events](/sdk/explore/events) — run your own code when the questions load and when the reader picks one. * [Explore workflow reference](https://misoai.github.io/miso-client-js-sdk/answers/explore/) — every element and option. * [Explore Questions API](/api/genai/explore) — generate the questions from your own back end. # Explore — API Configuration Choose how many questions Explore shows under an article and which articles they come from, and change the response before Explore shows it. `useApi` takes the request body that Explore sends to the [Related Questions API](/api/genai/explore#related-questions). `product_id` names the article, and the other fields control what comes back. For a page with no article, see [Trending Questions](/sdk/explore/trending-questions). ## Number of questions `rows` sets how many questions to ask for. The default is 5. ```javascript Three questions workflow.useApi({ product_id: "art_001", rows: 3, }); ``` Miso returns fewer than `rows` questions when it has fewer for that article. ## Filter the source articles `fq` restricts which articles Miso draws the questions from. It takes the same [filter syntax](/api/fq) as every other Miso endpoint. ```javascript Markets coverage only workflow.useApi({ product_id: "art_001", fq: 'categories:"Markets"', }); ``` Render the filter from your CMS, the same way as `product_id`. To keep each article's questions inside its own section, write that section into the filter. Filter values are matched exactly. Check yours against the rules for [case](/api/fq#values-are-case-sensitive) and [quoting](/api/fq#quote-any-value-with-a-space). ## Change the response `useDataProcessor` takes a function that gets each response before Explore renders it. `data.value` holds the [Related Questions API](/api/genai/explore#related-questions) response, and `related_questions` is the list of questions. Return `data`, changed or not. This one drops the questions that are too long for a narrow column: ```javascript Short questions only workflow.useDataProcessor((data) => { const { value } = data; if (!value || !value.related_questions) { return data; } return { ...data, value: { ...value, related_questions: value.related_questions.filter((question) => question.text.length <= 80), }, }; }); ``` The SDK calls the function each time the data changes. Before the response arrives, `data.value` is `undefined`. Check for the field you change, and return `data` as it is when the field is missing. Each call to `useDataProcessor` adds a function, and the functions run in the order you add them. `clearDataProcessor()` removes the ones added on the same object. # Explore — UI Customization Change the parts and the order of the related questions, and choose when each part shows. The elements from the quick start are the whole Explore UI, so you change it in the HTML. Below we remove the query box, add a heading, and then show the block only when there are questions. You need a working Explore page first. See [Explore — Quick Start](/sdk/explore/quick-start). ## Move, add and remove elements The quick start puts these elements on the page: ```html Elements ``` `` connects the Miso elements inside it to the workflow. Inside it, put the elements in any order, leave out the ones you do not want, and add your own HTML between them: | Element | What the reader sees | | -------------------------- | ---------------------------------------------------- | | `` | The questions about the article. | | `` | A box where the reader asks a question of their own. | | `` | The error message when the request fails. | This version shows a heading and the questions, without the query box: ```html Heading, no query box

Questions about this article

``` ## Show a part at the right moment The heading above shows even when Miso has no questions for the article. The `visible-when` attribute shows an element only in the states it names. Put it on a ``, or on an element inside one. | Value | Shows the element when | | ----------- | ---------------------------------------------------- | | `initial` | The workflow has not sent a request yet. | | `loading` | The request is out, and no data has arrived. | | `ready` | The data is arriving or has arrived. | | `ongoing` | The data is still arriving. | | `done` | All the data has arrived. | | `erroneous` | The request failed. | | `empty` | No Miso element in the container has data. | | `nonempty` | At least one Miso element in the container has data. | * Separate values with spaces to show the element in any of them: `visible-when="initial loading"`. * Join a state to `empty` or `nonempty` with `+` to need both: `visible-when="ready+empty"`. * Only the Miso elements that show data count toward `empty` and `nonempty`. The query box and the buttons do not. * The SDK shows the element with `display: block !important`. To lay it out as a flex row or a grid, put `visible-when` on a wrapper around it. Put `visible-when="nonempty"` on the container, and the whole block, heading included, shows only when there are questions: ```html Heading with the questions

Questions about this article

``` A failed request has no questions, so this block stays hidden then too. To tell the reader that the request failed, add a second `` for the error message. Both containers connect to the same workflow. This time `visible-when` is on an element inside the container, which works the same way: ```html Error message
``` For more than one Explore unit on a page, give both containers the same `unit-id`. ## If it does not work | Symptom | Cause | | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | | The console shows `… needs to be placed under a workflow container element` | A Miso element is outside every ``. | | An element with `visible-when` always shows | The attribute name is wrong, or the element is outside every ``. The name is `visible-when`. | | A flex row breaks into lines when it shows | `visible-when` sets `display: block`. Put it on a wrapper. | ## Next * [Related Questions](/sdk/explore/related-questions) — where a question takes the reader, and how each question looks. * [Events](/sdk/explore/events) — run your own code when the questions load and when the reader picks one. * [API Configuration](/sdk/explore/api-config) — how many questions, and which articles they come from. # Explore — Related Questions Change where a related question takes the reader, and how each question looks. `` lists the questions as links. Below we open your answers page in the same tab, and then write the markup of a question. You need a working Explore page first. See [Explore — Quick Start](/sdk/explore/quick-start). ## Open the answers page in the same tab A selected question opens the URL that your `useLink` function returns, in a new tab. To open it in the same tab, pass `open: false` as the second argument: ```javascript Same tab client.ui.explore.useLink( (question) => `/ask.html?q=${encodeURIComponent(question)}`, { open: false }, ); ``` Call `useLink` before `start()`. | `useLink` option | Default | What it does | | ---------------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `open` | `true` | `false` opens the page in the same tab. | | `target` | `"_blank"` | Where the page opens when `open` is `true`. | | `showUrl` | `false` | `true` puts the address in the `href` of each link. By default, each link is `#`, and the SDK opens the page when the reader selects it. | ## Change how a question looks Each question is drawn by the `question` template. Give your own with `useLayouts`, under the role `related_questions`. `data.text` is the question. Start the markup with `tagPair`, which returns the opening and closing tag of the item. The tags carry the link and the attributes that the SDK uses to handle the selection and to record clicks. ```javascript An arrow after each question function renderQuestion(layout, state, data) { const { tagPair, escapeHtml } = layout.templates.helpers; const [openTag, closeTag] = tagPair(layout, data); return openTag + `${escapeHtml(data.text)}` + '' + closeTag; } client.ui.explore.useLayouts({ related_questions: { templates: { question: renderQuestion } }, }); ``` Call `useLayouts` before `start()`. Style the classes in your own CSS. ## More than one unit on a page Set the options on `client.ui.explores`, the context, to reach every Explore unit on the page: ```javascript Every unit client.ui.explores.useLayouts({ related_questions: { templates: { question: renderQuestion } }, }); ``` ## If it does not work | Symptom | Cause | | --------------------------------------------------------------------------------------------- | ----------------------------------------------- | | A question does nothing when selected | The `question` template does not use `tagPair`. | | The console shows `Must define link mapping function with useLink(fn) before calling start()` | `start()` runs before `useLink`. | | The page opens in a new tab | `useLink` has no `open: false`. | ## Next * [UI Customization](/sdk/explore/ui-customization) — change the parts around the questions, and when they show. * [Events](/sdk/explore/events) — run your own code when the reader picks a question. * [API Configuration](/sdk/explore/api-config) — how many questions, and which articles they come from. # Explore — Events Run your own code when Explore loads its questions and when the reader picks one. The Explore workflow emits an event at each step. Below we listen to one, list the events a page load goes through, and then look at the `data` event, which tracks the response itself. You need a working Explore page first. See [Explore — Quick Start](/sdk/explore/quick-start). ## Listen to an event Call `on` on the workflow with the event name and a function. Add the listener before `start()`, so it catches the first events: ```javascript Log when the questions show const off = client.ui.explore.on("done", () => { console.log("Questions shown"); }); ``` `on` returns a function. Call it to remove the listener: ```javascript Remove the listener off(); ``` The lifecycle events and `data` also reach `client.ui.explores`, the context, with the workflow that emitted them in `workflow`. Use the context for a page with more than one Explore unit. `select` reaches the workflow only. ## Lifecycle events `start()` sends the request, and the events follow in this order. Each one fires at most once: | Event | Fires when | | ----------- | ----------------------------------------------------------------- | | `request` | The SDK sends the request to Miso. `payload` is the request body. | | `loading` | The request is out, and the SDK waits for the questions. | | `ready` | The questions show. | | `done` | The questions show. Explore emits it right after `ready`. | | `interrupt` | You called `restart()` before the questions arrived. | | `error` | The request failed. | | `finally` | The request has ended, in any of the three ways above. | The request always ends with one of `done`, `interrupt` and `error`, and then with `finally`. Explore shows all its questions at once, so `ready` and `done` come together. Listen to either one. Apart from `request`, these events carry: | Property | What it holds | | --------- | ---------------------------------- | | `session` | The session of the request. | | `status` | `loading`, `ready` or `erroneous`. | ## Select event `select` fires when the reader clicks a related question, before the SDK follows the link: ```javascript Act on the pick client.ui.explore.on("select", ({ question }) => { console.log("Question picked", question.text); }); ``` `question.text` is the question. The SDK then sends the reader on through your `useLink` function. The SDK reports the click to Miso by itself. Listen to this event only to send it somewhere else as well, such as to [Google Analytics 4](/sdk/explore/ga4). A question that the reader types in the search box goes to the answers page with no `select` event. ## The data event `data` fires each time the data of the workflow changes: when the workflow starts, when the request goes out, and when the response arrives. ```javascript Count the questions client.ui.explore.on("data", ({ status, value }) => { if (status !== "ready") { return; } console.log(value.related_questions.length, "questions"); }); ``` The event carries the data object: | Property | What it holds | | --------- | --------------------------------------------------------------------------- | | `session` | The session of the request. | | `status` | `initial`, `loading`, `ready` or `erroneous`. | | `request` | The request that the SDK sent, with the body in `request.payload`. | | `value` | The [Related Questions API](/api/genai/explore#related-questions) response. | | `error` | The error, when `status` is `erroneous`. | Each item in `value.related_questions` is an object with `text` and `url`. The SDK turns the strings in the response into these objects before anything else reads them. For one request, `data` fires in this order: 1. `status: "initial"` when the workflow starts, with no `request` yet. 2. `status: "loading"` when the request goes out. 3. `status: "ready"` when the response arrives. If the request fails, the last one has `status: "erroneous"` instead. The event shows the data after each [data processor](/sdk/explore/api-config#change-the-response) has run, so a field you changed there arrives changed here. The event cannot change the data. To change what Explore shows, use `useDataProcessor`. ## If it does not work | Symptom | Cause | | ----------------------------------------------- | ----------------------------------------------------------------------- | | `select` never fires | The listener is on `client.ui.explores`. Set it on `client.ui.explore`. | | `request` and `loading` never fire | The listener is added after `start()`. Add it before. | | `value` is `undefined` in `data` | The response has not arrived yet. Check `status` first. | | `question.length` is `undefined` | Each question is an object. Read `question.text`. | | Nothing fires and an error shows in the console | The function throws. The SDK logs the error and goes on. | ## Next * [API Configuration](/sdk/explore/api-config) — change the request and the response. * [Explore — Google Analytics 4](/sdk/explore/ga4) — send the pick to GA4. * [Ask — Events](/sdk/ask/events) — the events on the answers page. # Explore — Interactions See what the Explore workflow reports to Miso as a reader sees and opens the questions, and send the same records yourself when you render them on your own. Each record is an interaction: a reader saw, scrolled to, clicked or submitted something. Miso builds the Explore metrics in Dojo from them. Below we list the interactions Explore sends, the fields Miso needs on each one, and then send one by hand. You need a working Explore page first. See [Explore — Quick Start](/sdk/explore/quick-start). ## What Explore sends The SDK watches each part of the unit and sends an interaction when the reader acts on it. `property` names the part: | Property | Element | Types | Subject | | ------------------- | -------------------------- | -------------------------------------------- | ---------------------------------- | | `related_questions` | `` | `impression`, `viewable_impression`, `click` | `items`, the question texts | | `container` | `` | `impression`, `viewable_impression` | The unit itself | | `query` | `` | `submit` | `value`, the text the reader typed | `container` is tracked whether or not the unit has questions to show. The unit still has a record on a new article with no questions yet, or on a page with only the query box. Dojo divides `query` submits by `container` impressions to get the submit rate. The types mean: | Type | The reader | | --------------------- | ----------------------------------------------------- | | `impression` | Has the part on the page, seen or not. | | `viewable_impression` | Has at least half of the part in view for one second. | | `click` | Clicks a question. | | `submit` | Sends a question from the query box. | Each part sends `impression` and `viewable_impression` once for each page load. ## What a record holds A click on a related question goes out like this: ```json A question click { "type": "click", "product_ids": [], "miso_id": "d02603ab-d544-…", "anonymous_id": "5f6a7b8c-9d0e-…", "context": { "custom_context": { "api_group": "ask", "api_name": "related_questions", "property": "related_questions", "items": ["How do rate cuts affect mortgages?"], "unit_id": "default", "workflow": "explore" } } } ``` The fields mean: | Field | Value | | ---------------------------------- | ------------------------------------------------------------------------------------------------------- | | `type` | One of the types above. | | `product_ids` | `[]`. The questions are text. | | `miso_id` | The `miso_id` of the response the questions came from. | | `anonymous_id`, `user_id` | The reader, from [the client context](/sdk/user-type). | | `context.custom_context.api_group` | `ask` | | `context.custom_context.api_name` | `related_questions`, or `trending_questions` for [trending questions](/sdk/explore/trending-questions). | | `context.custom_context.workflow` | `explore` | | `context.custom_context.property` | One of the properties above. | | `context.custom_context.items` | The question texts the reader acted on, for `related_questions`. | | `context.custom_context.value` | On `submit` only: the text the reader typed. | | `context.custom_context.unit_id` | The unit, from the `unit-id` attribute of ``. `default` on a page with one unit. | ## Send an interaction yourself Send your own when you render the questions with your own code, for example a list you build from the [`data` event](/sdk/explore/events#the-data-event). Explore cannot see clicks in markup it did not render. Turn off the SDK's tracker for that part first, so the same click does not count twice: ```javascript Stop tracking questions client.ui.explore.useTrackers({ related_questions: { active: false } }); ``` To track every part yourself, turn off all the trackers: ```javascript Stop all tracking client.ui.explore.useTrackers(false); ``` Then call `client.api.interactions.upload` with the fields above. Pass it the `value` from the `data` event you rendered the list from: ```javascript Report a question click function reportQuestionClick(client, value, question) { const workflow = client.ui.explore; client.api.interactions.upload({ type: "click", product_ids: [], miso_id: value.miso_id, context: { custom_context: { api_group: "ask", api_name: "related_questions", workflow: "explore", property: "related_questions", items: [question], unit_id: workflow.id, }, }, }); } ``` The SDK adds the reader's `anonymous_id` or `user_id` and the page URL for you. Send `impression` and `viewable_impression` for the same list too, or the click-through rate has nothing to divide by. From a server, or with no SDK on the page, send the same record to `POST /v1/interactions`. See the [API Reference](/api/reference). ## If it does not work | Symptom | Cause | | ----------------------------------------------------------------- | ------------------------------------------------------------------------------ | | Clicks count twice | The SDK tracker for that part is still on. Turn it off with `useTrackers`. | | The questions show clicks but no click-through rate | Only `click` is sent. Send `impression` and `viewable_impression` as well. | | Two units on a page share one set of numbers | Both use the `default` unit. Give each `` its own `unit-id`. | | Nothing reaches Miso and the console warns about a playground app | Miso does not store interactions for a playground app. Use your own app's key. | ## Next * [Explore — Events](/sdk/explore/events) — the events that carry the response. * [Answer Metrics](/operate/answer-metrics) — the reports Miso builds from these interactions. # Explore — Trending Questions Show the questions trending across your site on a page with no article, such as a homepage or a section front. Explore asks for related questions by default, and those need an article. Below we switch the workflow to trending questions, choose how many to show, and limit them to one brand. You need a working Explore page first. See [Explore — Quick Start](/sdk/explore/quick-start). ## Ask for trending questions Give `useApi` the API name as the first argument, and the request body as the second. Leave out `product_id`: ```javascript Trending questions workflow.useApi("trending_questions", { rows: 5, }); ``` Call `useApi` before `start()`. The elements, `useLink` and `start()` stay as they are in the quick start. The body takes the fields of the [Trending Questions API](/api/genai/explore#trending-questions): | Field | Default | What it does | | ------------ | ------- | ----------------------------------------------------------------- | | `rows` | `10` | How many questions to ask for. | | `_meta.site` | — | Limits the questions to one site or brand, for a multi-brand app. | ## Limit the questions to one brand In an app that holds more than one brand, set `_meta.site` to the brand of the page: ```javascript One brand workflow.useApi("trending_questions", { rows: 5, _meta: { site: "markets" }, }); ``` Render the value from your CMS, so each brand's homepage passes its own. ## Change the response The response puts the questions in `related_questions`, the same key as the [Related Questions API](/api/genai/explore#related-questions). A `useDataProcessor` function from [API Configuration](/sdk/explore/api-config#change-the-response) works for both APIs without a change. ## If it does not work | Symptom | Cause | | ----------------------------------------------- | --------------------------------------------------------------------- | | No questions appear | Explore is not enabled for this environment. | | The request fails with `product_id is required` | `useApi` has no API name, so the workflow asks for related questions. | | Questions from another brand appear | The body has no `_meta.site`. | ## Next * [API Configuration](/sdk/explore/api-config) — the options for related questions, and how to change the response. * [UI Customization](/sdk/explore/ui-customization) — change the parts around the questions, and when they show. * [Trending Questions API](/api/genai/explore#trending-questions) — get the questions from your own back end. # Explore — Google Analytics 4 Give Miso the reader id GA4 already has, and send a click on a related question to GA4 as an event. Explore lists related questions under an article, and a reader who picks one lands on your answers page. Below we join GA4 and Miso on one reader id, then report the pick as a GA4 event, so the path from article to answer shows in one GA4 session. You need gtag.js and the SDK on the page. See [Explore — Quick Start](/sdk/explore/quick-start) for the SDK install. --- ## One reader id on both sides GA4 knows every browser by a `client_id`, and a signed-in reader by a `user_id` on top. Miso has the same pair: `anonymous_id` for the browser and `user_id` for the reader. Give Miso the GA4 values for both, and a report in either system can be joined to the other, before and after sign-in. | Id | GA4 | Miso | | -------------------------- | ------------------------------ | ------------------------------------------------------ | | The browser, always | `client_id`, minted by gtag.js | `client.context.anonymous_id`, set to that `client_id` | | The reader, when signed in | `user_id`, set by you | `client.context.user_id`, the same value | The SDK reads the ids from `client.context` at the moment it sends a request, so the handoff runs before the first request. The function below does the handoff. It goes in a script of its own, or at the top of the SDK script: ```javascript ga4Ids() // If gtag.js has not run yet, define the queue it expects. The calls below then // wait in dataLayer until it loads. Harmless when the gtag snippet already ran. window.dataLayer = window.dataLayer || []; window.gtag = window.gtag || function () { dataLayer.push(arguments); }; // Give Miso the GA4 ids. Resolves true when GA4 answered, false when it did not. async function ga4Ids(client, measurementId) { if (window.READER_ID) { client.context.user_id = READER_ID; client.context.user_type = "subscriber"; // if you meter, see /operate/metering } const clientId = await new Promise((resolve) => { gtag("get", measurementId, "client_id", resolve); setTimeout(() => resolve(null), 2000); }); if (!clientId) { return false; } client.context.anonymous_id = clientId; if (window.READER_ID) { gtag("config", measurementId, { user_id: READER_ID }); } return true; } ``` Three names in there are yours: * `G-XXXXXXXXXX`, the argument you pass as `measurementId`, is the **Measurement ID** of your GA4 web data stream. It is under **Admin › Data streams › your stream** in GA4, and in your existing gtag snippet after `gtag/js?id=`. * `READER_ID` stands for wherever your page keeps the signed-in reader's id: a global your template writes, a cookie, or your auth library. * `"subscriber"` is the reader's tier, when you meter. The return value is the all-or-none switch. When gtag.js is blocked, or loads after the two seconds, GA4 never answers with a `client_id`. The function then returns false and the page skips every GA4 event, so a session is either fully joined or absent from GA4. Miso still receives `user_id` and its own `anonymous_id`, and the answer box starts. With Google Tag Manager there is no gtag.js on the page. Read the browser id from the `_ga` cookie instead, whose value is `GA1.1.` followed by the `client_id`, and send the events through `dataLayer` and a GTM trigger: ```javascript client_id from the cookie const match = document.cookie.match(/(?:^|; )_ga=GA\d\.\d\.([^;]+)/); if (match) { client.context.anonymous_id = match[1]; } ``` --- ## Send the click to GA4 A click on a related question emits `select` on the Explore workflow, with the question the reader chose: ```javascript ga4ExploreEvents() function ga4ExploreEvents(client) { client.ui.explore.on("select", ({ question }) => { gtag("event", "miso_explore_click", { question: question.text.slice(0, 100) }); }); } ``` The click then goes wherever your link function points, usually the answers page. There the same question arrives as a `miso_question` with `question_source: _organic`, if that page reports to GA4 too. See [Ask — Google Analytics 4](/sdk/ask/ga4). GA4 keeps parameter values to 100 characters. That is why `question` is cut at 100. To see it in reports, register it as a custom dimension under **Admin › Custom definitions**. --- ## Put it together The id handoff runs first, and `start()` sends the first request: ```javascript Start Explore with GA4 const misocmd = window.misocmd || (window.misocmd = []); misocmd.push(async () => { const client = new MisoClient("YOUR_PUBLISHABLE_API_KEY"); const explore = client.ui.explore; const ga4 = await ga4Ids(client, "G-XXXXXXXXXX"); if (ga4) { ga4ExploreEvents(client); } explore.useApi({ product_id: "art_001" }); explore.useLink((q) => `/ask.html?q=${encodeURIComponent(q)}`); explore.start(); // the first request goes out here }); ``` --- ## Check it 1. On a test page, add `debug_mode: true` to the config call in your gtag snippet, so the page reports to DebugView: ```javascript gtag snippet, debug on gtag("config", "G-XXXXXXXXXX", { debug_mode: true }); ``` To test a live page without editing it, install the [Google Analytics Debugger](https://chromewebstore.google.com/detail/google-analytics-debugger/jnkmfdileelhofjcijamephohjechhna) extension and turn it on. It puts the browser in debug mode for every page. 2. Load the page, ask a question, click a citation, click Helpful. 3. In GA4, open **Admin › DebugView** and pick your device in the top-left list. Each event appears in the timeline with its parameters. --- ## Summary | Step | What you did | | ------------- | ----------------------------------------------------------------------------------------- | | One reader id | GA4's `client_id` is Miso's `anonymous_id`, and your `user_id` is on both when signed in. | | All or none | No `client_id` from GA4 means no GA4 events, and the answer box starts anyway. | | Events | `miso_explore_click` | ## Next * [Ask — Google Analytics 4](/sdk/ask/ga4) — the answers page these clicks lead to. # Hybrid Search — Quick Start Replace your search results page with one that answers. One search returns an AI answer with citations, plus the matching articles. ![A search box. Below it are the answer, its sources, the category filters and the results list.](/images/quickstart-ask/hybrid-search-finished-page.png) The article images are placeholders. Takes about ten minutes. ## Before you start **Get your publishable API key.** Copy it from **Overview** in the [Miso Dashboard](https://dojo.askmiso.com). The SDK runs in the browser, so it takes the publishable key, never the secret key. See [Authentication](/api/authentication). **Put your content in Miso.** Everything below works from your catalog. See [Integrating Your Data](/data/integrating-your-data) to upload it, and confirm the result in **Dashboard ▸ Data Sets ▸ Catalog**. Send `categories` and `cover_image` for this workflow. The results list renders the image, and the category filters come from the hierarchy. > **No content of your own yet?** Load a real one in a few minutes. [Example: Wikinews](/start/example-news-site) parses a free public archive of about 20,900 news articles and sends it to Miso, so you have something to ask questions about. --- ## 1. Install the SDK ### As a node module In your project directory, run: ```bash npm npm install --save @miso.ai/client-sdk ``` Then import `MisoClient` from the SDK: ```javascript Import import MisoClient from "@miso.ai/client-sdk"; ``` ### Using a script tag ```html Script tag ``` The script tag loads the SDK asynchronously, so your code must wait for it. Use the `misocmd` queue, which runs your function as soon as the SDK is ready: ```javascript Wait for the SDK const misocmd = window.misocmd || (window.misocmd = []); misocmd.push(() => { const MisoClient = window.MisoClient; // Your code goes here. }); ``` ## 2. Add the container Put this where the search page belongs: ```html Container
``` ## 3. Start the workflow ```javascript Start Hybrid Search const misocmd = window.misocmd || (window.misocmd = []); misocmd.push(async () => { const client = new MisoClient("YOUR_PUBLISHABLE_API_KEY"); const workflow = client.ui.hybridSearch; await client.ui.ready; // styles are loaded const defaults = MisoClient.ui.defaults.hybridSearch; const root = document.querySelector("#miso-hybrid-search-combo"); root.innerHTML = defaults.templates.root(); workflow.autoQuery(); // read ?q= from the URL }); ``` `autoQuery()` reads the `q` parameter from the page URL, which is what a normal search form already submits. Point your existing form at this page, and the integration is done. --- ## The complete page ```html search.html Miso Hybrid Search
``` ## Check it works Save the page, open it in a browser, and add `?q=media` to the URL. You get an answer with its sources, the matching articles, and the category filters. ![Hybrid Search: the answer, its sources, and the results list.](/images/quickstart-ask/hybrid-search-demo.png) | Symptom | Cause | | ----------------------------- | ---------------------------------------------------------------------------------------------- | | Results appear, but no answer | The question matched no passage. Check that the article bodies are in `html` or `description`. | | No category filters | Your records carry no `categories`. | | Results have no image | Your records carry no `cover_image`. | | The page renders empty | The key is the secret key, or your code ran before the SDK loaded. | ## Next * [UI Customization](/sdk/hybrid-search/ui-customization) — change the headings, the parts and the order of the page. * [API Configuration](/sdk/hybrid-search/api-config) — how many results load at a time, and which articles the search can return. * [Events](/sdk/hybrid-search/events) — run your own code at each step of a search and its answer. * [Citation Links](/sdk/hybrid-search/citation-links) — the class, the attributes and the tooltip of each citation. * [Ask — Quick Start](/sdk/ask/quick-start) — the question box on its own. * [Explore — Quick Start](/sdk/explore/quick-start) — related questions on an article page. * [Live Showcase](https://poc.miso.ai/demo/showcase/index.html#/hybrid-search/two-columns) — the layouts you can build. * [Hybrid Search API](/api/genai/hybrid-search) — the API behind the workflow, for your own front end. # Hybrid Search — API Configuration Choose how many results Hybrid Search loads at a time and which articles it can return, and change the response before Hybrid Search shows it. `useApi` takes the request body that Hybrid Search sends to the [Hybrid Search API](/api/genai/hybrid-search). The query comes from the reader, and the other fields control what comes back. ## Number of results `rows` sets how many search results each request returns. The default is 10. When the reader scrolls to the end of the list, the next request loads the next `rows` results. ```javascript Twenty results at a time client.ui.hybridSearch.useApi({ rows: 20, }); ``` ## Filter the articles `fq` restricts the search results, and the articles the answer can cite. It takes the same [filter syntax](/api/fq) as every other Miso endpoint. ```javascript Markets coverage only client.ui.hybridSearch.useApi({ fq: 'categories:"Markets"', }); ``` A reader's facet choices apply inside your filter, and the facet counts follow it. See [Filtering (fq)](/sdk/filtering). Filter values are matched exactly. Check yours against the rules for [case](/api/fq#values-are-case-sensitive) and [quoting](/api/fq#quote-any-value-with-a-space). ## Change the response `useDataProcessor` takes a function that gets each response before Hybrid Search renders it. Return `data`, changed or not. The function gets two kinds of response, so check which one `data.value` holds: * **Search results**, from the [Hybrid Search API](/api/genai/hybrid-search): `products`, `total` and `facet_counts`. When the reader scrolls for more, the function gets each new page of results before the SDK adds it to the list. * **The answer**: `answer`, `sources` and the other fields of the [Answer API](/api/genai/answer) response. This one takes the site name off the end of each title, in the results and in the sources of the answer: ```javascript Shorter titles function shortenTitle(item) { return { ...item, title: item.title.replace(/ \| Example News$/, "") }; } client.ui.hybridSearch.useDataProcessor((data) => { const { value } = data; if (value && value.products) { return { ...data, value: { ...value, products: value.products.map(shortenTitle) } }; } if (value && value.sources) { return { ...data, value: { ...value, sources: value.sources.map(shortenTitle) } }; } return data; }); ``` The SDK calls the function each time the data changes. Before the response arrives, `data.value` is `undefined`, and while the answer streams in, the function runs again on each new part. Check for the field you change, and return `data` as it is when the field is missing. Each call to `useDataProcessor` adds a function, and the functions run in the order you add them. `clearDataProcessor()` removes the ones added on the same object. # Hybrid Search — UI Customization Change the headings, the parts and the order of the search page, and choose when each part shows. The quick start writes the page with the SDK's template helper. Below we change the text it writes, remove a part, put the answer in a box that opens, and then take over the HTML. Last, `visible-when` decides when each part shows. You need a working Hybrid Search page first. See [Hybrid Search — Quick Start](/sdk/hybrid-search/quick-start). ## How the template builds the page `MisoClient.ui.defaults.hybridSearch.templates.root(options)` returns the HTML of the whole page: the query box, the answer with its sources, and the search results with their filters. The quick start puts it in the page as it is. ## Change the headings Pass your own text in `phrases`: ```javascript Your own headings const templates = MisoClient.ui.defaults.hybridSearch.templates; const root = document.querySelector("#miso-hybrid-search-combo"); root.innerHTML = templates.root({ phrases: { keywords: "Results for “${value}”", sources: "Read more", }, }); ``` | Key | Default text | | ---------- | ----------------------------- | | `question` | `You asked “${value}”` | | `sources` | Sources | | `keywords` | `You searched for “${value}”` | | `total` | `${value}` | `${value}` marks where the question, the search text or the number of results goes. Write the phrase in plain quotes, not in backticks, so that JavaScript leaves `${value}` for the SDK to fill. ## Add or remove a part The template returns a string, so you can change the string before it goes into the page. This removes the sort order selector: ```javascript No sort selector const templates = MisoClient.ui.defaults.hybridSearch.templates; const root = document.querySelector("#miso-hybrid-search-combo"); root.innerHTML = templates .root() .replace("", ""); ``` Add a part the same way: find an element in the string, and put your HTML before or after it. ## Put the answer in a box With `answerBox: true`, the answer shows in a box of fixed height, with a **Show more** button that opens it. The box needs `wireAnswerBox` to show and open: ```javascript Answer box const defaults = MisoClient.ui.defaults.hybridSearch; const root = document.querySelector("#miso-hybrid-search-combo"); root.innerHTML = defaults.templates.root({ answerBox: true }); defaults.wireAnswerBox(client, root); ``` The box hides when Miso has no answer to the question. To show it anyway, pass `hideWhenUnanswerable: false`. To change the button text, pass `phrases`: ```javascript Answer box options defaults.wireAnswerBox(client, root, { hideWhenUnanswerable: false, phrases: { showMore: "Read the full answer", showLess: "Show less" }, }); ``` ## Write the HTML yourself To change the order, start from the HTML that `root()` returns. Print it in the browser console on a page that loads the SDK: ```javascript Print the default HTML console.log(MisoClient.ui.defaults.hybridSearch.templates.root()); ``` Put the HTML in the page, inside the container, and edit it there. Then remove the `root.innerHTML` line from your script. This version puts the search results first and the answer after them, and leaves out the filters: ```html Results above the answer
You searched for “”
You asked “”

Sources

``` Keep these when you edit: | Keep | Because | | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | Each Miso element inside a `` | `` connects the elements in it to the workflow. | | The class names | The default styles select them. | | `logo="false"` | Without it, a `` that holds `` or `` adds the Miso logo. | | `miso-circled-citation-index` | It draws each citation number in a circle. | ## Show a part at the right moment The `visible-when` attribute shows an element only in the states it names. Put it on a ``, or on an element inside one. The template uses it on each part. The search results have `visible-when="loading ready"`, so they stay hidden until the first search starts. | Value | Shows the element when | | ----------- | ---------------------------------------------------- | | `initial` | The workflow has not sent a request yet. | | `loading` | The request is out, and no data has arrived. | | `ready` | The data is arriving or has arrived. | | `ongoing` | The data is still arriving. | | `done` | All the data has arrived. | | `erroneous` | The request failed. | | `empty` | No Miso element in the container has data. | | `nonempty` | At least one Miso element in the container has data. | * Separate values with spaces to show the element in any of them: `visible-when="initial loading"`. * Join a state to `empty` or `nonempty` with `+` to need both: `visible-when="ready+empty"`. * Only the Miso elements that show data count toward `empty` and `nonempty`. The query box and the buttons do not. * The SDK shows the element with `display: block !important`. To lay it out as a flex row or a grid, put `visible-when` on a wrapper around it. Hybrid Search adds one more value, `!unanswerable`. It hides the element when Miso has no answer to the question. Use it after a value that shows the element, as the answer does with `visible-when="ready !unanswerable"`. To keep the answer in view when there is no answer, remove `!unanswerable`. To show a message when the search fails, add this to the page: ```html Error message ``` ## If it does not work | Symptom | Cause | | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | | The answer box never shows | The page does not call `wireAnswerBox`. | | The console shows `value is not defined` | A phrase with `${value}` is in backticks. Use plain quotes. | | The console shows `… needs to be placed under a workflow container element` | A Miso element is outside every ``. | | An element with `visible-when` always shows | The attribute name is wrong, or the element is outside every ``. The name is `visible-when`. | | A flex row breaks into lines when it shows | `visible-when` sets `display: block`. Put it on a wrapper. | ## Next * [Results and Sources](/sdk/hybrid-search/results) — where the links open, the date format, and the fields and layout of each list. * [Facets](/sdk/hybrid-search/facets) — the category filters next to the results. * [Citation Links](/sdk/hybrid-search/citation-links) — the class, the attributes and the tooltip of each citation. * [Live Showcase](https://poc.miso.ai/demo/showcase/index.html#/hybrid-search/two-columns) — the layouts you can build. # Hybrid Search — Results and Sources Change how Hybrid Search lists articles: where the links open, how the dates read, the layout, and the markup of each item. Hybrid Search lists articles in two places: the search results, and the sources that the answer cites. Below we open the links in the same tab, change the date format, show the results as cards, and then write the markup of a result, with its date added. You need a working Hybrid Search page first. See [Hybrid Search — Quick Start](/sdk/hybrid-search/quick-start). ## The two lists | Element | What it lists | Fields from | Layout | | ----------------- | -------------------------------------------------------------------- | ----------- | ----------------------------------------------- | | `` | The search results. | `fl` | `list`, with more results as the reader scrolls | | `` | The articles that the answer cites, numbered to match the citations. | `source_fl` | `horizontal`: one row of small cards | Each change below goes to `useLayouts` on `client.ui.hybridSearch`. The key is the role of the list: `products` or `sources`. Your options are merged over the defaults, so set only what you change. Set them before the template goes into the page. ## Open links in the same tab Each item is a link to the article's `url`, and it opens in a new tab. To open it in the same tab, set `link.open` to `false`: ```javascript Links in the same tab client.ui.hybridSearch.useLayouts({ products: { link: { open: false } }, sources: { link: { open: false } }, }); ``` | `link` option | Default | What it does | | ------------- | ------------ | ------------------------------------------------------------------------- | | `open` | `true` | `false` leaves out `target` and `rel`, so the link opens in the same tab. | | `target` | `"_blank"` | The `target` attribute of the link. | | `rel` | `"noopener"` | The `rel` attribute of the link. | ## Change the date format The sources show the authors and the date. The date is `published_at`, or `created_at` or `updated_at` when the record has no `published_at`. The default format is `Mar 5, 2026`. Give the `date` template the options of [`toLocaleDateString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString), with `locale` added: ```javascript 5 March 2026 client.ui.hybridSearch.useLayouts({ sources: { templates: { date: { locale: "en-GB", year: "numeric", month: "long", day: "numeric" }, }, }, }); ``` `date` can also be a locale string, such as `"de-DE"`, or a function that gets the date value from the record and returns the text. ## Show the results as cards Give the layout type before the options: ```javascript Results as cards client.ui.hybridSearch.useLayouts({ products: ["cards", { link: { open: false } }], }); ``` | Type | What the reader sees | | ------- | ------------------------------------ | | `list` | One result on each row. The default. | | `cards` | Results side by side, in a grid. | ## Write the markup of a result A result shows its image, title and description. To draw it your own way, give the `product` template. This one adds the date under the title. Start the template with `tagPair`, which returns the opening and closing tag of the item. The tags link to the article and carry the attributes that the SDK uses to record clicks: ```javascript Image, title, date and description function renderProduct(layout, state, data, meta) { const { tagPair, escapeHtml } = layout.templates.helpers; const [openTag, closeTag] = tagPair(layout, data); const image = data.cover_image ? `` : ""; const date = data.published_at ? new Date(data.published_at).toLocaleDateString("en-US", { dateStyle: "medium" }) : ""; return openTag + image + `
${escapeHtml(data.title)}
` + `
${date}
` + `
${escapeHtml(data.description || "")}
` + closeTag; } client.ui.hybridSearch.useLayouts({ products: { templates: { product: renderProduct } }, }); ``` | Argument | What it holds | | -------- | --------------------------------------------------------------------------------------------------------------------------- | | `layout` | The layout. `layout.templates.helpers` has `tagPair` and `escapeHtml`. | | `state` | The state of the whole list. | | `data` | The record, with the fields from `fl` for a result, or `source_fl` for a source. `product_id` and `title` are always there. | | `meta` | `meta.index` is the position of the item, counted from 0. | A field that `fl` does not name is `undefined` in the template. The default `fl` is: ```js Default fl ["cover_image", "url", "created_at", "updated_at", "published_at", "title"] ``` To show another field, add it with `useApi`. The list replaces the default, so keep the fields that the template still uses. A custom attribute uses its dotted path, such as `custom_attributes.section`: ```javascript Ask for the categories client.ui.hybridSearch.useApi({ fl: ["cover_image", "url", "published_at", "title", "description", "categories"], }); ``` For a source, give the `article` template under `sources` in the same way. Add `` to it. That element draws the number that the citations in the answer point to. Keep these in mind when you write one: * **Escape every value from the record** with `escapeHtml`. * **Format the date yourself.** The `date` option applies to the default markup only. * **Style your own classes** in your CSS. ## If it does not work | Symptom | Cause | | ------------------------------------------- | --------------------------------------------------------------- | | A field shows `undefined` | It is not in `fl` for a result, or in `source_fl` for a source. | | The SDK stops recording clicks on the items | The `product` or `article` template does not use `tagPair`. | | The sources have no numbers | The `article` template has no `miso-citation-index` element. | ## Next * [UI Customization](/sdk/hybrid-search/ui-customization) — change the headings, the parts and the order of the page. * [Facets](/sdk/hybrid-search/facets) — the category filters next to the results. * [Citation Links](/sdk/hybrid-search/citation-links) — the class, the attributes and the tooltip of each citation. # Hybrid Search — Facets Let a reader narrow the results, inside the boundary you set. Facets let a reader narrow the results themselves, inside the boundary you set. Below we switch them on, then make them read like your site. | | Set by | Job | | --- | --- | --- | | **`fq`** | You | Remove content the reader must never see, across every request. | | **Facets** | The reader | Narrow what is left. | The two never fight. `fq` decides the pool, facets pick from that pool, and a reader cannot widen past your filter. See [Filter results (fq)](/sdk/filtering). **The SDK owns the facet state.** It reads the counts, renders the groups, tracks what is selected, sends the filter, and refreshes the results. Your part is to name the fields and style the block. There is no filter logic to write. Facets belong to Hybrid Search and Search. An answer has no result list to narrow. ## Turn them on Two steps: name the fields, and put the element on the page. ```js Step 1 — name the fields const workflow = client.ui.hybridSearch; workflow.useApi({ facets: ["tags", "categories"], }); ``` Miso counts only the fields you name. A custom attribute uses its dotted path, such as `custom_attributes.section`. ```js Step 2 — render await client.ui.ready; document.querySelector("#my-root").innerHTML = MisoClient.ui.defaults.hybridSearch.templates.root(); ``` The default markup already holds ``. To place the block yourself, put that element where you want it. ## What a click sends A reader selecting a value does not change `q` or `fq`. The SDK adds a separate field, `facet_filters`, and runs the search again: ```json After a reader picks Computing { "q": "linux", "facets": ["tags"], "facet_filters": { "tags": { "terms": ["Computing"] } } } ``` **Your `fq` still applies.** A reader narrows inside the rules you set, and cannot widen past them. See [Filter results (fq)](/sdk/filtering). **One value per field.** Picking a second value in the same group replaces the first: a click on `Computing` sends `["Computing"]`, and a click on `FLOSS` next sends `["FLOSS"]`, not both. Selecting values in **different** fields does combine. ## Rename the labels Field names read like a schema. Replace them with words your readers know: ```js Readable labels const LABELS = { tags: "Topic", categories: "Section", "custom_attributes.section": "Desk", }; workflow.useLayouts({ facets: { templates: { title(layout, { field }) { const { escapeHtml } = layout.templates.helpers; return escapeHtml(LABELS[field] || field); }, value(layout, { value }) { return layout.templates.helpers.escapeHtml(value); }, }, }, }); ``` The heading now reads "Topic" rather than "tags". Use `value` the same way to tidy the values themselves, such as turning `science-and-tech` into "Science and technology". Miso strips a `custom_attributes.` prefix before it draws the default heading, so `custom_attributes.section` already shows as `section`. Your `LABELS` lookup sees the full path, so key it either way: ```js Handle the prefix title(layout, { field }) { const name = field.replace("custom_attributes.", ""); return layout.templates.helpers.escapeHtml(LABELS[name] || name); } ``` ## The templates Each one replaces a smaller part of the block. Change the least you can. | Template | Draws | Arguments | | --- | --- | --- | | `title` | One group heading. | `(layout, { field })` | | `value` | One option label. | `(layout, { field, value, count })` | | `count` | The number beside a value. | `(layout, { count })` | | `option` | One whole row. | `(layout, entry, state)` | | `options` | The list of rows in a group. | `(layout, facet, state)` | | `header` | The heading row of a group. | `(layout, facet, state)` | | `facet` | One whole group. | `(layout, facet, state)` | | `facets` | Every group. | `(layout, state)` | > **Keep `data-role="option"` if you rewrite `option`.** The SDK listens for > clicks on that attribute. A row without it renders correctly and stops > filtering, with no error. Hide the counts, for example, by returning nothing from `count`: ```js No counts workflow.useLayouts({ facets: { templates: { count: () => "" } }, }); ``` ## Hide some values To drop values a reader has no use for, override `options`, filter the entries, and hand the rest to the original template: ```js Hide one value workflow.useLayouts({ facets: { templates: { options(layout, data, state) { const skip = ["Uncategorised"]; const entries = data.entries.filter(([value]) => !skip.includes(value)); const { options: defaultOptions } = layout.constructor.defaultTemplates; return defaultOptions(layout, { ...data, entries }, state); }, }, }, }); ``` `data.entries` is an array of `[value, count]` pairs, so `entries[0]` is the value and `entries[1]` is the count. Filter, sort or slice it, then let Miso draw the rows. > **Reach the original through `layout.constructor.defaultTemplates`.** Inside > an override, `layout.templates.options` is your own function, so calling it > repeats forever. `defaultTemplates` holds the version you replaced. This is > the way to add to a template rather than rewrite it. The counts stay as Miso calculated them. Hiding a row removes the control, not the results behind it. To change what the query matches, filter with `fq`. ## Order and empty groups Values arrive **most common first**, and Miso returns the top 10 values per field. A field with no matching values is left out of the response, so the group does not render. To show a different number of values, or to filter which ones appear, set the facet as an object on the endpoint. See [Hybrid Search API](/api/genai/hybrid-search#facet-the-results) for `size`, `alias`, `include`, `exclude` and `ranges`, and [Filter by a facet](/api/genai/hybrid-search#filter-by-a-facet) for what the SDK sends when a reader picks a value. ## Can I use checkboxes, or a dropdown? Not today. Facets render as clickable rows, and each field holds one value. You can make the rows **look** like checkboxes with the `option` template, but do not. A checkbox tells a reader to tick several values in a group, and the second tick clears the first. The control then promises what the behaviour does not do. The SDK has a `checkbox` layout and a `select` layout, and neither one fits here. The `checkbox` layout is a single on and off switch, used for the Answer Updates subscribe button. The `select` layout is the single-choice dropdown used for sorting. **If you need several values at once**, filter with `fq` while you wait, and ask Miso for multi-select facets. See [Filter results (fq)](/sdk/filtering). ## Do not drive facets from your own code Facet state belongs to the SDK, and there is no public call to select a value for the reader. One owner of the selection means the chips, the counts, the request and the results cannot disagree. When your code needs to control what is eligible, that is a different job, and `fq` does it: ```js Your rule, not the reader's choice workflow.useApi({ fq: 'custom_attributes.premium:"false"' }); ``` Set `fq` and the facet counts follow it automatically. ## Next - [Filter results (fq)](/sdk/filtering) — the filters your product sets. - [Hybrid Search API](/api/genai/hybrid-search) — `facets`, `order_by` and the response shape. - [Hybrid Search — Results and Sources](/sdk/hybrid-search/results) — change what each result looks like. # Hybrid Search — Citation Links Change the class, the attributes, the URL and the tooltip of each citation link in an answer. Each `[1]` in an answer is a link to the source it cites. Below we hook into every citation link, mark it with a class and a data attribute, add a tracking parameter to its URL, give it a tooltip, and then read a field that the response does not send by default. You need a working Hybrid Search page first. See [Hybrid Search — Quick Start](/sdk/hybrid-search/quick-start). ## Customize each link Give the answer layout of the Hybrid Search workflow an `onCitationLink` function: ```javascript A class and a data attribute function onCitationLink({ addClass, setAttribute }, { source }) { addClass("my-citation-link"); if (!source) { return; } setAttribute("data-title", source.title); } client.ui.hybridSearch.useLayouts({ answer: { onCitationLink }, }); ``` The second argument is `{ source, index }`. `source` is the cited item from the response's `sources`, and `index` is its position, counted from 0. `source` can be `undefined`, so check it before you read from it. The first argument holds the methods that change the link: | Method | What it does | | -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | `addClass(name)`, `removeClass(name)` | Add or remove a class on the link. | | `setAttribute(key, value)`, `removeAttribute(key)` | Set or remove an attribute, such as `data-title`. The SDK escapes the value. Use `addClass` for classes. | | `setHref(href)` | Set the URL that the link opens. Pass a string, or a function that gets the current URL and returns the new one.Since 1.14.1 | | `setTooltipText(text)` | Show plain text in the tooltip. | | `setTooltipHtml(html)` | Show HTML in the tooltip. Escape every value from `source` with `escapeHtml`. | | `escapeHtml(text)` | Escape text for use in HTML. | The SDK calls the function each time it renders the answer, and it renders the answer many times as the text streams in. Only change the link inside the function. ## Change the URL Since 1.14.1 Each link opens the URL that the answer gives it. Change it with `setHref`. This one adds a `utm_source` parameter: ```javascript A tracking parameter on every link function onCitationLink({ setHref }) { setHref((href) => { const url = new URL(href, window.location.href); url.searchParams.set("utm_source", "miso"); return url.href; }); } ``` Use `setHref` for the URL, not `setAttribute("href", …)`. `setAttribute` escapes the value, which breaks a URL that has `&` in it. ## Add a tooltip Put content in the link's tooltip with `setTooltipText` or `setTooltipHtml`. This one shows the source's title and date: ```javascript Title and date in a tooltip function onCitationLink({ setTooltipHtml, escapeHtml }, { source }) { if (!source) { return; } const date = new Date(source.published_at).toLocaleDateString(); setTooltipHtml( `${escapeHtml(source.title)}` + `${date}` ); } ``` The SDK styles already place the tooltip above the link and show it on hover. Style what you put inside it: ```css Tooltip content .miso-citation-tooltip .title { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; width: max-content; max-width: 12rem; overflow: hidden; font-weight: 600; } .miso-citation-tooltip .date { display: block; margin-top: 0.5em; } ``` ## Use more source fields `source` carries only the fields that the request asks for. `product_id` and `title` always arrive, whether `source_fl` names them or not. By default, the Hybrid Search workflow requests these fields: ```js Default source_fl ["cover_image", "url", "created_at", "updated_at", "published_at", "title", "authors"] ``` To read any other field, name it in `source_fl` in the request payload. The list replaces the default, so start from the default and add your field. ```javascript Add the categories client.ui.hybridSearch.useApi({ source_fl: ["cover_image", "url", "created_at", "updated_at", "published_at", "title", "authors", "categories"], }); ``` `source.categories` is then available in `onCitationLink`. A custom attribute uses its dotted path, such as `custom_attributes.section`. See `source_fl` in the [Hybrid Search API](/api/genai/hybrid-search), and the field names in [Product Schema](/data/product-schema). ## If it does not work | Symptom | Cause | | ---------------------------------------------- | -------------------------------------------------------------------------- | | The tooltip shows `undefined` | The field is not in `source_fl`. | | The tooltip shows raw tags | The HTML went to `setTooltipText`. Use `setTooltipHtml`. | | The console shows `setHref is not a function` | The SDK is older than 1.14.1. | | Nothing changes and error shown in console log | The function throws. The SDK logs the error and leaves the link as it was. | # Hybrid Search — Events Run your own code when a search goes out, when its results and its answer show, and when the reader rates the answer. Hybrid Search runs two parts, the search results and the answer, and each part emits its own events. Below we listen to both, list the events each part goes through, and then look at the `data` event, which tracks the responses themselves. You need a working Hybrid Search page first. See [Hybrid Search — Quick Start](/sdk/hybrid-search/quick-start). ## Listen to an event Call `on` with the event name and a function. The search results emit on `client.ui.hybridSearch`, and the answer emits on `client.ui.hybridSearch.answer`: ```javascript Log each search and its answer const workflow = client.ui.hybridSearch; workflow.on("done", () => { console.log("Results shown"); }); workflow.answer.on("done", () => { console.log("Answer done", workflow.questionId); }); ``` An event on one part does not reach the other. To know when the answer is done, listen on `answer`. `on` returns a function. Call it to remove the listener: ```javascript Remove the listener const off = workflow.on("request", ({ payload }) => { console.log("Search", payload.q); }); off(); ``` ## Search results events Each search goes through these events in order. Each one fires at most once for a search: | Event | Fires when | | ----------- | --------------------------------------------------------------- | | `request` | The SDK sends a request to Miso. `payload` is the request body. | | `loading` | The request is out, and the SDK waits for the results. | | `ready` | The results show. | | `done` | The results show. Hybrid Search emits it right after `ready`. | | `interrupt` | A new search replaced this one before its results arrived. | | `error` | The search failed. | | `finally` | The search has ended, in any of the three ways above. | A search always ends with one of `done`, `interrupt` and `error`, and then with `finally`. A new query starts a new search, and so does a change of facet or sort order. The events above then fire again. When the reader scrolls for more results, the search stays the same, so only `request` and `data` fire. `request` carries `type`, which says why the SDK sent it: | `type` | Sent when | | -------- | --------------------------------------------- | | `query` | The reader searches. | | `refine` | The reader changes a facet or the sort order. | | `more` | The reader scrolls for more results. | Apart from `request`, these events carry: | Property | What it holds | | --------- | ----------------------------------------------------------- | | `session` | The session of the search. A new search gets a new session. | | `status` | `loading`, `ready` or `erroneous`. | ## Answer events The answer starts with each new query. A change of facet or sort order keeps the answer as it is. Each answer goes through these events in order: | Event | Fires when | | --------------------- | ------------------------------------------------------------------------------------ | | `request` | The SDK asks Miso for the answer, after the search results arrive. | | `loading` | The SDK waits for the answer. | | `ready` | The answer starts to show. | | `blocked`Since 1.13.0 | Miso withheld the answer, for example at a metering limit. `blockedReason` says why. | | `done` | The full answer is on screen. | | `interrupt` | A new query replaced this one before its answer finished. | | `error` | The answer failed. | | `finally` | The answer has ended, in any of the three ways above. | These events carry `session`, `status` and `ongoing`. `ongoing` is `true` while more of the answer is on the way. `ready` and `done` follow what is on screen. `done` fires when the last word of the answer shows, which is after the last part of the response arrives. To act on the response as it arrives, use the [`data` event](#the-data-event). The answer also emits `answer-stage` each time its progress label changes, with the label in `answer_stage`. Use it for display only. The labels change without notice, so do not branch on them. ## Feedback event `feedback` fires on the answer when the reader clicks **Helpful** or **Not helpful**: ```javascript Act on feedback const workflow = client.ui.hybridSearch; workflow.answer.on("feedback", ({ value, unselected }) => { if (unselected) { return; // the reader cleared their choice } console.log(workflow.questionId, value); }); ``` `value` is `helpful` or `unhelpful`. A second click on the same button clears the choice. The event then carries `unselected: true` and no `value`. The SDK sends the feedback to Miso by itself. Listen to this event only to send it somewhere else as well. ## The data event `data` fires each time the data of a part changes. Each part has its own `data` event, and each one carries the data object: | Property | What it holds | | --------- | ------------------------------------------------------------------ | | `session` | The session of the search or the answer. | | `status` | `initial`, `loading`, `ready` or `erroneous`. | | `ongoing` | On the answer, `true` while more of the response is on the way. | | `request` | The request that the SDK sent, with the body in `request.payload`. | | `value` | The response. See below for each part. | | `error` | The error, when `status` is `erroneous`. | The event shows the data after each [data processor](/sdk/hybrid-search/api-config#change-the-response) has run, so a field you changed there arrives changed here. The event cannot change the data. To change what Hybrid Search shows, use `useDataProcessor`. ### Search results On `client.ui.hybridSearch`, `value` is the [Hybrid Search API](/api/genai/hybrid-search) response, with `products`, `total` and `facet_counts`: ```javascript Read the results client.ui.hybridSearch.on("data", ({ status, value }) => { if (status !== "ready") { return; } console.log(value.products.length, "of", value.total); }); ``` For one search, `data` fires with `status: "initial"`, then `loading`, then `ready`. When the reader scrolls for more, it fires again with `loading` and then `ready`. `value.products` then holds every result loaded so far, the new page included. ### Answer On `client.ui.hybridSearch.answer`, `value` is the [Answer API](/api/genai/answer) response, with `answer`, `sources` and the other fields: ```javascript Read the sources of a complete answer client.ui.hybridSearch.answer.on("data", ({ status, ongoing, value }) => { if (status !== "ready" || ongoing) { return; } console.log(value.sources); }); ``` For one answer, `data` fires in this order: 1. `status: "initial"` when the new query starts. 2. `status: "loading"` while the search and then the answer are on the way. 3. `status: "ready"` and `ongoing: true` for each part of the response. This repeats as the answer streams in. 4. `status: "ready"` and `ongoing: false` when the response is complete. `data` comes before the lifecycle events. The response is complete at `ongoing: false`, but the answer can still be typing out on screen until `done`. ## If it does not work | Symptom | Cause | | ------------------------------------------------- | ------------------------------------------------------------------------------------------------ | | The answer emits nothing | The listener is on `client.ui.hybridSearch`. Set it on `client.ui.hybridSearch.answer`. | | `loading` and `done` do not fire for more results | Scrolling for more stays in the same search. Listen to `request` or `data`. | | `value.answer` is `undefined` | The listener is on the search results. Set it on `answer`. | | A listener runs many times for one answer | It listens to `data`, which fires for each part of the response. Use `done`, or check `ongoing`. | | Nothing fires and an error shows in the console | The function throws. The SDK logs the error and goes on. | ## Next * [API Configuration](/sdk/hybrid-search/api-config) — change the request and the response. * [Ask — Events](/sdk/ask/events) — the events of the question box. # Hybrid Search — Interactions See what the Hybrid Search workflow reports to Miso as a reader uses the results and the answer, and send the same records yourself when you render part of it on your own. Each record is an interaction: a reader saw, scrolled to, clicked or rated something. Miso builds the search and answer metrics in Dojo from them. Below we list the interactions Hybrid Search sends, the fields Miso needs on each one, and then send one by hand. You need a working Hybrid Search page first. See [Hybrid Search — Quick Start](/sdk/hybrid-search/quick-start). ## What Hybrid Search sends The SDK watches each part of the page and sends an interaction when the reader acts on it. `property` names the part: | Property | Element | Types | Subject | | ------------- | -------------------- | -------------------------------------------- | ------------------------------------------------------ | | `products` | `` | `impression`, `viewable_impression`, `click` | `product_ids` of the results | | `sources` | `` | `impression`, `viewable_impression`, `click` | `product_ids` of the articles | | `images` | `` | `impression`, `viewable_impression`, `click` | `product_ids` of the images | | `affiliation` | `` | `impression`, `viewable_impression`, `click` | The affiliate products, with `channel` and `positions` | | `answer` | `` | `click` | `items`, the link texts, with `urls` | The answer has its own workflow, `client.ui.hybridSearch.answer`, but its records go out as Hybrid Search records, with the same `api_name` and `workflow` as the results. A click on a citation in the answer, such as `[2]`, counts as a click on that source. It goes out as a `sources` click with `event_target: "citation-link"`, so you can tell it apart from a click in the source list. The rating buttons send one more type. When the reader clicks **Helpful** or **Not helpful**, Hybrid Search sends `type: "feedback"` with `result_type: "answer"` and `value` set to `helpful` or `unhelpful`. A second click on the same button clears the rating and sends `value: "unselected"`. This record has no `property`. The types mean: | Type | The reader | | --------------------- | ----------------------------------------------------- | | `impression` | Has the part on the page, seen or not. | | `viewable_impression` | Has at least half of the part in view for one second. | | `click` | Clicks a link in the part. | | `feedback` | Rates the answer. | Each part sends `impression` and `viewable_impression` once for each item and each query. ## What a record holds A click on a search result goes out like this: ```json A result click { "type": "click", "product_ids": ["article-1042"], "miso_id": "7c8d9e0f-1a2b-…", "anonymous_id": "5f6a7b8c-9d0e-…", "context": { "custom_context": { "api_group": "ask", "api_name": "search", "property": "products", "question_id": "0e1f2a3b-4c5d-…", "root_miso_id": "d02603ab-d544-…", "question_source": "_organic", "workflow": "hybrid-search" } } } ``` The fields mean: | Field | Value | | ---------------------------------------- | -------------------------------------------------------------------------------------------------- | | `type` | One of the types above. | | `product_ids` | The `product_id` of each result, article, image or product the reader acted on. `[]` for `answer`. | | `miso_id` | On `products` only: the `miso_id` of the search response the results came from. | | `anonymous_id`, `user_id` | The reader, from [the client context](/sdk/user-type). | | `value`, `result_type` | On `feedback` only: the rating, and `answer`. | | `context.custom_context.api_group` | `ask` | | `context.custom_context.api_name` | `search` | | `context.custom_context.workflow` | `hybrid-search` | | `context.custom_context.property` | One of the properties above. Absent on `feedback`. | | `context.custom_context.items` | The link texts the reader acted on, for `answer`. | | `context.custom_context.event_target` | `citation-link` on a citation click. | | `context.custom_context.question_id` | The `question_id` of the answer to the query. | | `context.custom_context.root_miso_id` | The `miso_id` of the first page of results for the query. On every record, answer parts included. | | `context.custom_context.question_source` | How the reader asked: `_organic` for a typed query. | ## Send an interaction yourself Send your own when you render a part of the page with your own code, for example a list of results you build from the [`data` event](/sdk/hybrid-search/events#the-data-event). Hybrid Search cannot see clicks in markup it did not render. Turn off the SDK's tracker for that part first, so the same click does not count twice: ```javascript Stop tracking results client.ui.hybridSearch.useTrackers({ products: { active: false } }); ``` To track every part yourself, turn off all the trackers: ```javascript Stop all tracking client.ui.hybridSearch.useTrackers(false); ``` Then call `client.api.interactions.upload` with the fields above. Pass it the `request` and `value` from the `data` event of `client.ui.hybridSearch` you rendered the list from: ```javascript Report a result click function reportResultClick(client, { request, value }, productId) { const { metadata = {} } = request.payload; client.api.interactions.upload({ type: "click", product_ids: [productId], miso_id: value.miso_id, context: { custom_context: { api_group: "ask", api_name: "search", workflow: "hybrid-search", property: "products", question_id: value.question_id, root_miso_id: value.root_miso_id, question_source: metadata.question_source, }, }, }); } ``` The SDK adds the reader's `anonymous_id` or `user_id` and the page URL for you. Send `impression` and `viewable_impression` for the same list too, or the click-through rate for that part has nothing to divide by. From a server, or with no SDK on the page, send the same record to `POST /v1/interactions`. See the [API Reference](/api/reference). ## If it does not work | Symptom | Cause | | ----------------------------------------------------------------- | ------------------------------------------------------------------------------ | | Clicks count twice | The SDK tracker for that part is still on. Turn it off with `useTrackers`. | | A part shows clicks but no click-through rate | Only `click` is sent. Send `impression` and `viewable_impression` as well. | | Nothing reaches Miso and the console warns about a playground app | Miso does not store interactions for a playground app. Use your own app's key. | ## Next * [Hybrid Search — Events](/sdk/hybrid-search/events) — the events that carry the response. * [Results and Sources](/sdk/hybrid-search/results) — the elements these interactions come from. # Chat History — Quick Start Give signed-in readers a chat page that remembers. Since 1.14.0 Two panels: past conversations and the open thread. Readers find their threads again on the next visit. ![Chat History on the Wikinews sample data. The thread list is on the left. The open thread shows an answer with numbered citations, and the question box is at the bottom.](/images/quickstart-ask/chat-history-demo.png) Takes about fifteen minutes. [Try the live demo](https://poc.miso.ai/demo/chat-history-demo/). ## Before you start **Get your publishable API key.** Copy it from **Overview** in the [Miso Dashboard](https://dojo.askmiso.com). The SDK runs in the browser, so it takes the publishable key, never the secret key. See [Authentication](/api/authentication). **Put your content in Miso.** Everything below works from your catalog. See [Integrating Your Data](/data/integrating-your-data) to upload it, and confirm the result in **Dashboard ▸ Data Sets ▸ Catalog**. > **No content of your own yet?** Load a real one in a few minutes. [Example: Wikinews](/start/example-news-site) parses a free public archive of about 20,900 news articles and sends it to Miso, so you have something to ask questions about. **Ask Miso to turn on User History.** Miso enables it per app. Until then, the history endpoints return `403`. See [User History](/api/genai/user-history). **Add an endpoint that signs a JWT for the reader.** History belongs to one reader, so the browser must prove who the reader is. Your server signs a short-lived JWT with your secret key and returns it to the page. See [Create a browser JWT](/api/genai/user-history#create-a-browser-jwt-server-side). --- ## 1. Install the SDK ### As a node module In your project directory, run: ```bash npm npm install --save @miso.ai/client-sdk ``` Then import `MisoClient` from the SDK: ```javascript Import import MisoClient from "@miso.ai/client-sdk"; ``` ### Using a script tag ```html Script tag ``` The script tag loads the SDK asynchronously, so your code must wait for it. Use the `misocmd` queue, which runs your function as soon as the SDK is ready: ```javascript Wait for the SDK const misocmd = window.misocmd || (window.misocmd = []); misocmd.push(() => { const MisoClient = window.MisoClient; // Your code goes here. }); ``` > **Beta.** The history panels ship in version `1.14.0`, which is in beta now. Until the stable release, write `@beta` where the snippets above say `@latest`. For npm, install `@miso.ai/client-sdk@beta`. ## 2. Add the panels `` is the list of threads. `` is the thread the reader has open. Put the two side by side: ```html Panels
What can I help with?
``` | Element | What the reader sees | | ------------------------------------------------ | ---------------------------------------------------------------------------------------- | | `` | The **New chat** button. | | `` | The list of threads, newest first. Each item has a menu to rename, subscribe, or delete. | | ``, ``, `` | The title of the open thread, and its rename and delete buttons. | | `` | The toggle for [Answer Updates](/api/genai/answer-updates) on the open thread. | | `` | The questions and answers of the open thread. | | `` | The box where the reader asks the next question. | The class names `miso-history` and `miso-conversation` apply Miso's default layout: each panel scrolls inside its own box, and the question box stays below the messages. The items keep their styles without the class names, so omit them when you write a layout of your own. The page decides the size and position of each panel: ```css Layout html, body { height: 100%; margin: 0; } #chat { display: flex; gap: 1rem; height: 100%; padding: 1rem; box-sizing: border-box; } #chat miso-history { flex: 0 0 20rem; } #chat miso-conversation { flex: 1 1 auto; } ``` ## 3. Sign the reader in and start ```javascript Start Chat History const misocmd = window.misocmd || (window.misocmd = []); misocmd.push(async () => { const client = new MisoClient("YOUR_PUBLISHABLE_API_KEY"); const workflow = client.ui.history; // The same id that your server signs into the JWT. client.context.user_id = "u-10293"; // Your endpoint. It returns a JWT for the signed-in reader. async function fetchToken() { const response = await fetch("/api/miso-token"); return (await response.json()).token; } // The styles load while your server signs the token. const [token] = await Promise.all([fetchToken(), client.ui.ready]); client.context.auth = `Bearer ${token}`; workflow.start(); // load the thread list }); ``` `client.ui.ready` resolves when the styles are loaded. The token request runs at the same time, so neither waits for the other. Set `client.context.user_id` too, although the JWT already names the reader. The JWT signs the reader in for the history requests. The SDK records interactions, such as a click on a citation, with the id in the context, and those do not read the JWT. Use the same id as the `user_id` claim of the JWT. If the two are different, Miso returns `401`. The SDK sends `client.context.auth` as the `Authorization` header on every request. `start()` loads the reader's threads. The conversation panel opens on a new, empty thread and needs no call of its own. ## 4. Renew the token when it expires A short-lived JWT expires while the page is open, and Miso then answers `401`. Set `client.api.onError` to get a new token and send the request again: ```javascript Renew the JWT let renewing; async function renewToken(hold) { // New requests wait here until the new token is set. const unhold = hold(); try { client.context.auth = `Bearer ${await fetchToken()}`; } finally { unhold(); renewing = undefined; } } client.api.onError = async (error, { hold, resend }) => { // Any other error, or a second 401 for the same request: stop here. if (error.status !== 401 || error.resent) { throw error; } // Requests that fail together share one renewal. await (renewing || (renewing = renewToken(hold))); return resend(); }; ``` `hold()` makes the SDK keep each new request until you call the function it returns. Without it, a request that starts during the renewal goes out with the expired token and fails too. Release the hold in `finally`, or the requests wait forever when the renewal fails. `error.resent` counts how many times the SDK sent this request again. The check stops a loop when the new token is rejected too. --- ## The complete page ```html chat.html Miso Chat History
What can I help with?
``` ## Check it works Open the page as a signed-in reader and ask a question. The answer streams into the conversation panel, and a new thread appears at the top of the list. Reload the page: the thread is still in the list, and a click opens it again. To match the image at the top, add the Inter font to the ``: ```html Font ``` Then add these rules after the layout styles. They hide the first question of each thread, because the title shows it. A renamed thread hides it too. To keep the question, remove that rule. ```css Optional styles body { background: radial-gradient(circle at 50% 110%, #4a4d55, #111216 65%); color: #1b1c1f; font-family: Inter, system-ui, sans-serif; } #chat { max-width: 76rem; height: calc(100% - 4rem); margin: 2rem auto; padding: 0.375rem; gap: 0; background: #e8e8ea; border-radius: 14px; box-shadow: 0 30px 80px rgba(0, 0, 0, 0.55); } #chat miso-history { flex-basis: 16rem; padding: 0.75rem 0.5rem; font-size: 0.8125rem; } #chat miso-conversation { padding: 1.5rem 1rem 1rem; background: #fff; border-radius: 10px; } #chat .miso-conversation__header, #chat miso-query, #chat .miso-messages__list { box-sizing: border-box; width: 100%; max-width: 42rem; margin-inline: auto; } #chat .miso-conversation__header [data-role="title"] { overflow: visible; white-space: normal; font-size: 1.5rem; font-weight: 600; letter-spacing: -0.02em; } #chat .miso-conversation__header, #chat .miso-conversation__header-row { border-color: #ececee; } /* The title already shows the first question. */ #chat .miso-messages__item:first-child .miso-messages__question { display: none; } #chat .miso-question { background: #f0f0f1; font-size: 0.875rem; } #chat .miso-markdown, #chat .miso-markdown * { color: #4a4b50; font-size: 0.875rem; line-height: 1.65; } #chat .miso-markdown h3, #chat .miso-markdown strong { color: #1b1c1f; } #chat .miso-markdown h3 { font-size: 1rem; } #chat .miso-markdown a, #chat .miso-markdown a * { color: #1b1c1f; font-style: normal; } #chat miso-new-thread button { background: none; border: 0; } #chat .miso-search-box__input-group { padding: 0.375rem; background: #f6f6f7; border: 1px solid #e6e6e8; border-radius: 12px; } #chat .miso-search-box__input { height: 2rem; padding-block: 0; background: none; font-size: 0.875rem; } #chat .miso-search-box__button { display: grid; flex: none; place-items: center; align-self: center; width: 2rem; height: 2rem; padding: 0; background: #1b1c1f; border: 0; border-radius: 8px; } #chat .miso-search-box__button svg { display: none; } #chat .miso-search-box__button::before { content: "→"; color: #fff; font-size: 1rem; line-height: 1; } ``` | Symptom | Cause | | ------------------------------------------------------ | ------------------------------------------------------------------------------------- | | The list shows an error, and the requests return `403` | User History is off for this app. Ask Miso to enable it. | | The list shows "Your session has expired" | The JWT is missing or expired, or it was signed with a different key. | | The panels never render | The page loads a release older than `1.14.0`, or your code ran before the SDK loaded. | ## Next * [UI Customization](/sdk/history/ui-customization) — change the parts of the two panels, and when they show. * [API Configuration](/sdk/history/api-config) — how many threads load at a time, and which articles the answers can cite. * [Citation Links](/sdk/history/citation-links) — the class, the attributes and the tooltip of each citation. * [User History](/api/genai/user-history) — the API behind the panels, for your own front end. * [Answer Updates](/api/genai/answer-updates) — what the subscription toggle does, and how the unread indicators clear. * [JWT (user authentication)](/api/authentication#jwt-user-authentication) — the claims Miso reads, and what each `401` means. # Chat History — API Configuration Choose how many threads the list loads at a time, and which articles the answers can cite. Chat History has a workflow for each panel. `client.ui.history` is the list of threads, and `client.ui.conversation` is the thread the reader has open. Each takes its own `useApi`. ## Number of threads `rows` sets how many threads each request for the list returns. The default is 100, and the maximum is 200. When the reader scrolls to the end of the list, the next request loads the next page. ```javascript Twenty threads at a time client.ui.history.useApi({ rows: 20, }); ``` Call it before `workflow.start()`, which loads the first page. ## Filter the source articles `fq` restricts which articles an answer can cite. It takes the same [filter syntax](/api/fq) as every other Miso endpoint. Set it on the conversation workflow, which posts the reader's questions. The filter then applies to every question in the panel, follow-ups included. ```javascript Markets coverage only client.ui.conversation.useApi({ fq: 'categories:"Markets"', }); ``` Filter values are matched exactly. Check yours against the rules for [case](/api/fq#values-are-case-sensitive) and [quoting](/api/fq#quote-any-value-with-a-space). # Chat History — UI Customization Change the parts and the order of the two chat panels, and choose when each part shows. The elements from the quick start are the whole chat UI, so you change it in the HTML. Below we move and remove parts of the panels, and then use `visible-when` to show a line when the reader has no chats yet. You need a working chat page first. See [Chat History — Quick Start](/sdk/history/quick-start). ## Move, add and remove elements `` and `` are the two containers. Each one connects the Miso elements inside it to its workflow, so keep each element in its own panel: | Container | Elements you can put in it | | --------------------- | -------------------------------------------------------------------------------------------------------------------------- | | `` | ``, ``, `` | | `` | ``, ``, ``, ``, ``, ``, `` | Inside a container, put the elements in any order, leave out the ones you do not want, and add your own HTML between them. This version puts the **New chat** button under the list, and removes the subscription toggle and the delete button from the header: ```html Panels
What can I help with?
``` Each thread in the list keeps its own menu to rename, subscribe or delete. The SDK draws that menu as part of ``, so these changes do not touch it. ## Show a part at the right moment The `visible-when` attribute shows an element only in the states it names. Put it on a `` or a ``, or on an element inside one. | Value | Shows the element when | | ----------- | ---------------------------------------------------- | | `initial` | The workflow has not sent a request yet. | | `loading` | The request is out, and no data has arrived. | | `ready` | The data is arriving or has arrived. | | `ongoing` | The data is still arriving. | | `done` | All the data has arrived. | | `erroneous` | The request failed. | | `empty` | No Miso element in the container has data. | | `nonempty` | At least one Miso element in the container has data. | * Separate values with spaces to show the element in any of them: `visible-when="initial loading"`. * Join a state to `empty` or `nonempty` with `+` to need both: `visible-when="ready+empty"`. * Only the Miso elements that show data count toward `empty` and `nonempty`. The query box and the buttons do not. * The SDK shows the element with `display: block !important`. To lay it out as a flex row or a grid, put `visible-when` on a wrapper around it. The quick start uses it three times in ``: | Element | `visible-when` | What the reader sees | | -------------- | -------------- | ------------------------------------------------------------- | | The header | `nonempty` | The title and its buttons, once the open thread has messages. | | The intro line | `ready+empty` | "What can I help with?", on a new thread with no messages. | | `` | `ready` | The question box, hidden while a thread loads. | The header puts `visible-when` on `miso-conversation__header`, and lays out the row on `miso-conversation__header-row` inside it. `visible-when` sets `display: block`, so the flex row needs a wrapper of its own. The thread list shows nothing when the reader has no chats. Add a line for that case: ```html No chats yet

Your chats show here.

``` ## If it does not work | Symptom | Cause | | --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | | The console shows `… needs to be placed under a workflow container element` | A Miso element is outside both containers. | | An element with `visible-when` always shows | The attribute name is wrong, or the element is outside both containers. The name is `visible-when`. | | A flex row breaks into lines when it shows | `visible-when` sets `display: block`. Put it on a wrapper. | ## Next * [API Configuration](/sdk/history/api-config) — how many threads load at a time, and which articles the answers can cite. * [Citation Links](/sdk/history/citation-links) — the class, the attributes and the tooltip of each citation. # Chat History — Citation Links Change the class, the attributes, the URL and the tooltip of each citation link in an answer. Each `[1]` in an answer is a link to the source it cites. Below we hook into every citation link, mark it with a class and a data attribute, add a tracking parameter to its URL, give it a tooltip, and then read a field that the response does not send by default. You need a working Chat History page first. See [Chat History — Quick Start](/sdk/history/quick-start). ## Customize each link Give the answer layout an `onCitationLink` function. Set it on `client.ui.conversation`, the panel the answers show in. It covers every message in the panel, follow-ups and reopened threads included: ```javascript A class and a data attribute function onCitationLink({ addClass, setAttribute }, { source }) { addClass("my-citation-link"); if (!source) { return; } setAttribute("data-title", source.title); } client.ui.conversation.useLayouts({ answer: { onCitationLink }, }); ``` The second argument is `{ source, index }`. `source` is the cited item from the response's `sources`, and `index` is its position, counted from 0. `source` can be `undefined`, so check it before you read from it. The first argument holds the methods that change the link: | Method | What it does | | -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | `addClass(name)`, `removeClass(name)` | Add or remove a class on the link. | | `setAttribute(key, value)`, `removeAttribute(key)` | Set or remove an attribute, such as `data-title`. The SDK escapes the value. Use `addClass` for classes. | | `setHref(href)` | Set the URL that the link opens. Pass a string, or a function that gets the current URL and returns the new one.Since 1.14.1 | | `setTooltipText(text)` | Show plain text in the tooltip. | | `setTooltipHtml(html)` | Show HTML in the tooltip. Escape every value from `source` with `escapeHtml`. | | `escapeHtml(text)` | Escape text for use in HTML. | The SDK calls the function each time it renders the answer, and it renders the answer many times as the text streams in. Only change the link inside the function. ## Change the URL Since 1.14.1 Each link opens the URL that the answer gives it. Change it with `setHref`. This one adds a `utm_source` parameter: ```javascript A tracking parameter on every link function onCitationLink({ setHref }) { setHref((href) => { const url = new URL(href, window.location.href); url.searchParams.set("utm_source", "miso"); return url.href; }); } ``` Use `setHref` for the URL, not `setAttribute("href", …)`. `setAttribute` escapes the value, which breaks a URL that has `&` in it. ## Add a tooltip Put content in the link's tooltip with `setTooltipText` or `setTooltipHtml`. This one shows the source's title and date: ```javascript Title and date in a tooltip function onCitationLink({ setTooltipHtml, escapeHtml }, { source }) { if (!source) { return; } const date = new Date(source.published_at).toLocaleDateString(); setTooltipHtml( `${escapeHtml(source.title)}` + `${date}` ); } ``` The SDK styles already place the tooltip above the link and show it on hover. Style what you put inside it: ```css Tooltip content .miso-citation-tooltip .title { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; width: max-content; max-width: 12rem; overflow: hidden; font-weight: 600; } .miso-citation-tooltip .date { display: block; margin-top: 0.5em; } ``` ## Use more source fields `source` carries only the fields that the request asks for. `product_id` and `title` always arrive, whether `source_fl` names them or not. By default, the conversation workflow requests these fields: ```js Default source_fl ["cover_image", "url", "created_at", "updated_at", "published_at", "title", "authors"] ``` To read any other field, name it in `source_fl` in the request payload. The list replaces the default, so start from the default and add your field. ```javascript Add the categories client.ui.conversation.useApi({ source_fl: ["cover_image", "url", "created_at", "updated_at", "published_at", "title", "authors", "categories"], }); ``` `source.categories` is then available in `onCitationLink`. A custom attribute uses its dotted path, such as `custom_attributes.section`. See `source_fl` on the question request in the [API Reference](/api/reference/tag/ask-apis), and the field names in [Product Schema](/data/product-schema). `source_fl` applies to the questions the reader asks in the panel. A thread the reader reopens loads its answers through a request that takes no field list, so a field you added can be missing there. Check for the field before you read it. ## If it does not work | Symptom | Cause | | ---------------------------------------------- | -------------------------------------------------------------------------- | | The tooltip shows `undefined` | The field is not in `source_fl`. | | Every link stays plain | The layout is on `client.ui.history`. Set it on `client.ui.conversation`. | | A field is missing in a reopened thread | `source_fl` applies to the questions asked in the panel only. | | The tooltip shows raw tags | The HTML went to `setTooltipText`. Use `setTooltipHtml`. | | The console shows `setHref is not a function` | The SDK is older than 1.14.1. | | Nothing changes and error shown in console log | The function throws. The SDK logs the error and leaves the link as it was. | # `` The generated answer. It types out as it arrives, with a number for each source it cites: ```html ``` ## Containers | Container | Options from | | ---------------------------------------------------------- | ------------------------ | | [``](/sdk/elements/miso-ask) | `client.ui.asks` | | [``](/sdk/elements/miso-hybrid-search) | `client.ui.hybridSearch` | | `` | `client.ui.conversation` | You do not write `` yourself. [``](/sdk/elements/miso-messages) puts one in each message of the open thread, with a `` in it. To change the answer, call `useLayouts` on the workflow of the container, under the role `answer`. For Ask, use `client.ui.asks`, the context, so that follow-up answers get the change too. ## Options Your options are merged over the defaults, so set only what you change. ```javascript Type faster client.ui.asks.useLayouts({ answer: { speed: 300 }, }); ``` | Option | What it does | | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `speed` | The typing speed, in characters per second. The default is `100`. Each step is a random amount between half and one and a half times this speed. | | `acceleration` | How fast the typing speeds up after the whole answer has arrived. Each second after that, the speed goes up by this many times the base speed. The default is `4`, and `0` turns it off. | | `instant` | `true` shows at once the part of the answer that has arrived, and types out only the rest. The messages of `` set it, so an answer from an earlier visit shows complete. | | `onCitationLink` | A function that changes each citation link. See [Citation Links](/sdk/ask/citation-links). | | `format` | `markdown`, the default, or `plaintext`. | | `tag` | The tag of the element that holds the text. The default is `div` for `markdown` and `p` for `plaintext`. | | `className` | The class of that element, in place of `miso-typewriter`. The cursor at the end of the text has the class name with `__cursor` added. | | `builtInStyles` | `false` removes the `miso-markdown` class, and with it the SDK styles for paragraphs, lists, tables and code in the answer. | ## Links in the answer | The reader selects | What happens | | ------------------------- | ---------------------------------------------------------- | | A citation, such as `[2]` | The SDK records a click on that source. | | Any other link | The link opens, and the SDK records a click on the answer. | The clicks are recorded as interactions. See [Ask — Interactions](/sdk/ask/interactions) and [Hybrid Search — Interactions](/sdk/hybrid-search/interactions). ## Next * [Ask — Citation Links](/sdk/ask/citation-links): the class, the attributes, the URL and the tooltip of each citation. * [Ask — Events](/sdk/ask/events): run your own code as the answer arrives and when it is done. * [``](/sdk/elements/miso-sources): the articles that the citations point to. # `` The container of the Ask workflow. Miso elements inside it show the data of one question and its answer: ```html ``` A page can have more than one `` for the same question. Each one connects the elements in it to the same workflow, so you can put the parts of an answer in different places in the page. To build a whole Ask page, see [Ask — Quick Start](/sdk/ask/quick-start). ## Elements | Element | Shows | | ------------------------------------------------------------------ | -------------------------------------------------- | | `` | The affiliate products that come with the answer. | | [``](/sdk/elements/miso-answer) | The generated answer. | | `` | The error message shown when the workflow fails. | | `` | The buttons that rate the answer. | | `` | The suggested follow-up questions. | | `` | The images that come with the answer. | | [``](/sdk/elements/miso-query) | The query box. | | `` | The question being answered. | | `` | The reasoning given while the answer is generated. | | [``](/sdk/elements/miso-related-resources) | The articles related to the question. | | [``](/sdk/elements/miso-sources) | The articles cited by the answer. | `` also works here, but it is deprecated. Use ``. ## Attributes ### `parent-question-id` Connects the container to the follow-up of a question. Without it, the container shows the first question on the page. ```html ``` The value is the question ID of the question before it. The `followUp()` template sets it for you. See [Ask — UI Customization](/sdk/ask/ui-customization#write-the-html-yourself). ### `workflow` `workflow="active"` connects the container to the latest question that the reader asked, the first one or a follow-up. When the reader asks a follow-up, the container moves to it. Use it for a part of the page that always shows the newest answer, such as a list of its sources in a side column: ```html ``` Set it in the HTML, and leave out `parent-question-id`. ### `logo` Controls the Miso logo at the end of the container. | Value | The logo shows | | ------------------ | --------------------------------------------------------------------------- | | Attribute left out | When the container holds ``, once the answer starts to arrive. | | `true` | Once the answer starts to arrive. | | `false` | Never. | Any other value is an error. To turn the logo off in every ``: ```javascript client.ui.asks.useLayouts({ container: { logo: false }, }); ``` ### `visible-when` Shows the container only in the states it names. It also works on an element inside the container. | Value | Shows the element when | | ----------- | ---------------------------------------------------- | | `initial` | The workflow has not sent a request yet. | | `loading` | The request is out, and no data has arrived. | | `ready` | The data is arriving or has arrived. | | `ongoing` | The data is still arriving. | | `done` | All the data has arrived. | | `erroneous` | The request failed. | | `empty` | No Miso element in the container has data. | | `nonempty` | At least one Miso element in the container has data. | * Separate values with spaces to show the element in any of them: `visible-when="initial loading"`. * Join a state to `empty` or `nonempty` with `+` to need both: `visible-when="ready+empty"`. * Only the Miso elements that show data count toward `empty` and `nonempty`. The query box and the buttons do not. * The SDK shows the element with `display: block !important`. To lay it out as a flex row or a grid, put `visible-when` on a wrapper around it. ## Next * [Ask — UI Customization](/sdk/ask/ui-customization) — the parts and the order of the Ask page. * [Ask — Events](/sdk/ask/events) — run your own code at each step of a question. # `` The container of the Conversation workflow: the open thread of the chat history interface. Miso elements inside it show the messages of that thread and the box to ask the next question: ```html ``` `` holds the list of threads beside it. To build both panels, see [Chat History — Quick Start](/sdk/history/quick-start). ## Elements | Element | Shows | | ------------------------------------------------ | ------------------------------------------------------ | | `` | The button that deletes a thread. | | `` | The error message shown when the workflow fails. | | [``](/sdk/elements/miso-messages) | The questions and answers of the open thread. | | [``](/sdk/elements/miso-query) | The query box. | | `` | The button that renames a thread. | | `` | The toggle that subscribes a thread to answer updates. | | `` | The title of a thread. | `` draws each message in a `` of its own, which holds the question, the answer and the sources of that message. ## Attributes ### `logo` Controls the Miso logo at the end of the container. The logo is off in the chat panels, so it shows only with `logo="true"`. | Value | The logo shows | | ------------------ | --------------------------- | | Attribute left out | Never. | | `true` | Once the thread has loaded. | | `false` | Never. | Any other value is an error. ### `visible-when` Shows the container only in the states it names. It also works on an element inside the container. | Value | Shows the element when | | ----------- | ---------------------------------------------------- | | `initial` | The workflow has not sent a request yet. | | `loading` | The request is out, and no data has arrived. | | `ready` | The data is arriving or has arrived. | | `ongoing` | The data is still arriving. | | `done` | All the data has arrived. | | `erroneous` | The request failed. | | `empty` | No Miso element in the container has data. | | `nonempty` | At least one Miso element in the container has data. | * Separate values with spaces to show the element in any of them: `visible-when="initial loading"`. * Join a state to `empty` or `nonempty` with `+` to need both: `visible-when="ready+empty"`. * Only the Miso elements that show data count toward `empty` and `nonempty`. The query box and the buttons do not. * The SDK shows the element with `display: block !important`. To lay it out as a flex row or a grid, put `visible-when` on a wrapper around it. ## Next * [Chat History — UI Customization](/sdk/history/ui-customization) — the parts and the order of the two panels. * [``](/sdk/elements/miso-history) — the thread list. # `` The container of the Explore workflow of a unit. Miso elements inside it show the questions related to the page: ```html ``` A page can have more than one `` for the same unit. Each one connects the elements in it to the same workflow. To add Explore to a page, see [Explore — Quick Start](/sdk/explore/quick-start). ## Elements | Element | Shows | | ------------------------------------------------------------------ | ------------------------------------------------ | | `` | The error message shown when the workflow fails. | | [``](/sdk/elements/miso-query) | The query box. | | [``](/sdk/elements/miso-related-questions) | The questions related to the page. | ## Attributes ### `unit-id` Picks the unit. Each unit is a workflow of its own, with its own questions and options. Without the attribute, the container uses the `default` unit. ```html ``` Give every container of one unit the same `unit-id`. To set the options of one unit, get its workflow with `client.ui.explores.get('sidebar')`. ### `logo` Controls the Miso logo at the end of the container. | Value | The logo shows | | ------------------ | ------------------------------------------------------------------------------- | | Attribute left out | When the container holds ``, once the questions arrive. | | `true` | Once the questions arrive. | | `false` | Never. | Any other value is an error. To turn the logo off in every ``: ```javascript client.ui.explores.useLayouts({ container: { logo: false }, }); ``` ### `visible-when` Shows the container only in the states it names. It also works on an element inside the container. | Value | Shows the element when | | ----------- | ---------------------------------------------------- | | `initial` | The workflow has not sent a request yet. | | `loading` | The request is out, and no data has arrived. | | `ready` | The data is arriving or has arrived. | | `ongoing` | The data is still arriving. | | `done` | All the data has arrived. | | `erroneous` | The request failed. | | `empty` | No Miso element in the container has data. | | `nonempty` | At least one Miso element in the container has data. | * Separate values with spaces to show the element in any of them: `visible-when="initial loading"`. * Join a state to `empty` or `nonempty` with `+` to need both: `visible-when="ready+empty"`. * Only the Miso elements that show data count toward `empty` and `nonempty`. The query box and the buttons do not. * The SDK shows the element with `display: block !important`. To lay it out as a flex row or a grid, put `visible-when` on a wrapper around it. ## Next * [Explore — UI Customization](/sdk/explore/ui-customization) — the heading, the parts and when they show. * [Related Questions](/sdk/explore/related-questions) — where a question takes the reader, and how each question looks. # `` The container of the History workflow: the thread list of the chat history interface. Miso elements inside it show the reader's chat threads and the button to start a new one: ```html ``` `` holds the open thread beside it. To build both panels, see [Chat History — Quick Start](/sdk/history/quick-start). ## Elements | Element | Shows | | ---------------------------------------------- | ------------------------------------------------ | | `` | The error message shown when the workflow fails. | | `` | The button that starts a new chat thread. | | [``](/sdk/elements/miso-threads) | The list of the chat threads. | `` draws each thread in a `` of its own, which holds the title and the menu of that thread. ## Attributes ### `logo` Controls the Miso logo at the end of the container. The logo is off in the chat panels, so it shows only with `logo="true"`. | Value | The logo shows | | ------------------ | ----------------------------- | | Attribute left out | Never. | | `true` | Once the threads have loaded. | | `false` | Never. | Any other value is an error. ### `visible-when` Shows the container only in the states it names. It also works on an element inside the container. | Value | Shows the element when | | ----------- | ---------------------------------------------------- | | `initial` | The workflow has not sent a request yet. | | `loading` | The request is out, and no data has arrived. | | `ready` | The data is arriving or has arrived. | | `ongoing` | The data is still arriving. | | `done` | All the data has arrived. | | `erroneous` | The request failed. | | `empty` | No Miso element in the container has data. | | `nonempty` | At least one Miso element in the container has data. | * Separate values with spaces to show the element in any of them: `visible-when="initial loading"`. * Join a state to `empty` or `nonempty` with `+` to need both: `visible-when="ready+empty"`. * Only the Miso elements that show data count toward `empty` and `nonempty`. The query box and the buttons do not. * The SDK shows the element with `display: block !important`. To lay it out as a flex row or a grid, put `visible-when` on a wrapper around it. ## Next * [Chat History — UI Customization](/sdk/history/ui-customization) — the parts and the order of the two panels. * [``](/sdk/elements/miso-conversation) — the open thread. # `` The container of the Hybrid Search workflow. One query gets two things: the search results and an answer. Each arrives on its own, so the elements fall into two groups, and one container holds elements from one group only. Put the results in one `` and the answer in another: ```html ``` All the containers connect to the same workflow, so the query box sends one query for both groups. To build a Hybrid Search page, see [Hybrid Search — Quick Start](/sdk/hybrid-search/quick-start). ## Elements ### Search results | Element | Shows | | ------------------------------------------------ | ------------------------------------------------ | | `` | The error message shown when the workflow fails. | | `` | The facet filters of the search results. | | `` | The query text the results are for. | | `` | The button that loads more search results. | | [``](/sdk/elements/miso-products) | The product results. | | [``](/sdk/elements/miso-query) | The query box. | | `` | The sort order selector of the search results. | | `` | The total number of search results. | ### Answer | Element | Shows | | ---------------------------------------------- | ------------------------------------------------- | | `` | The affiliate products that come with the answer. | | [``](/sdk/elements/miso-answer) | The generated answer. | | `` | The buttons that rate the answer. | | `` | The images that come with the answer. | | `` | The question being answered. | | [``](/sdk/elements/miso-sources) | The articles cited by the answer. | A container with elements from both groups stops with an error in the console: ` cannot contain both … for they don't share the same data lifecycle.` ## Attributes ### `logo` Controls the Miso logo at the end of the container. | Value | The logo shows | | ------------------ | ---------------------------------------------------------------------------------------------- | | Attribute left out | When the container holds `` or ``, once its data starts to arrive. | | `true` | Once the data of its group starts to arrive. | | `false` | Never. | Any other value is an error. To turn the logo off in every ``: ```javascript client.ui.hybridSearch.useLayouts({ container: { logo: false }, }); ``` ### `visible-when` Shows the container only in the states it names. It also works on an element inside the container. The state is the state of the container's group: an answer container can be `loading` while the results are `ready`. | Value | Shows the element when | | ----------- | ---------------------------------------------------- | | `initial` | The workflow has not sent a request yet. | | `loading` | The request is out, and no data has arrived. | | `ready` | The data is arriving or has arrived. | | `ongoing` | The data is still arriving. | | `done` | All the data has arrived. | | `erroneous` | The request failed. | | `empty` | No Miso element in the container has data. | | `nonempty` | At least one Miso element in the container has data. | * Separate values with spaces to show the element in any of them: `visible-when="initial loading"`. * Join a state to `empty` or `nonempty` with `+` to need both: `visible-when="ready+empty"`. * Only the Miso elements that show data count toward `empty` and `nonempty`. The query box and the buttons do not. * The SDK shows the element with `display: block !important`. To lay it out as a flex row or a grid, put `visible-when` on a wrapper around it. An answer container also has `unanswerable` when Miso has no answer for the query. `visible-when="ready !unanswerable"` shows the answer only when there is one. ## Next * [Hybrid Search — UI Customization](/sdk/hybrid-search/ui-customization) — the parts and the order of the page. * [Results and Sources](/sdk/hybrid-search/results) — the fields and the layout of each result. * [Facets](/sdk/hybrid-search/facets) — the filters beside the results. # `` The questions and answers of the open thread, oldest at the top. A new answer types out at the bottom: ```html ``` ## Containers | Container | Layout | | -------------------------------------------------------- | ---------- | | [``](/sdk/elements/miso-conversation) | `messages` | `messages` is the only layout for this element. The options below go to `useLayouts` on `client.ui.conversation`, under the role `messages`. ## Messages Each message is a ``, a container of its own. It holds these elements, in this order: | Element | Shows | | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `` | The question. A message that Miso wrote, such as an answer update, has a **Written by Miso** label. | | [``](/sdk/elements/miso-answer) | The answer. | | `` | The buttons that rate the answer. | | [``](/sdk/elements/miso-sources) | The articles that the answer cites, under a **Sources** heading. The heading hides when there are none. | | `` | Suggested questions, under **Related questions you can explore**, once the answer is done. Selecting one asks it in the same thread. | The elements in a message take their options from `client.ui.conversation`. To change the sources of every message, for example, use the role `sources`: ```javascript Sources as a list client.ui.conversation.useLayouts({ sources: "list", }); ``` `` has a `data-live` attribute on a message asked on this page. A message from an earlier visit shows when all of it has loaded, so its parts do not appear one at a time. ## Loading and scrolling The thread opens with its 30 newest messages. When the reader scrolls to the top, the older messages load above. The list stays at the bottom as an answer types out. When the reader scrolls up, it stays where the reader left it. While an answer is on its way, `` in the same container is off, so the reader cannot ask the next question too early. ## Errors When the thread cannot load, a notice takes the place of the list: | Cause | Text | | ------------------------------------ | ------------------------------------------------- | | The session has expired (status 401) | "Your session has expired. Please sign in again." | | Any other failure | "This conversation could not be loaded." | When one message fails, a notice takes the place of that message only. It reads "Something went wrong with this message.", or the session text above. Two templates return the text. Both get `(layout, error)`, and `error.status` is the HTTP status: ```javascript Error text client.ui.conversation.useLayouts({ messages: { templates: { errorMessage: (layout, error) => "We could not open this chat.", }, }, error: { templates: { message: (layout, error) => "This answer could not be loaded.", }, }, }); ``` `messages.templates.errorMessage` is the text for the thread, and `error.templates.message` is the text for one message. ## Next * [Chat History — Quick Start](/sdk/history/quick-start): build the thread list and the open thread. * [Chat History — Citation Links](/sdk/history/citation-links): the citations in the answers. * [``](/sdk/elements/miso-threads): the list of threads. # `` The search results. Hybrid Search shows them under the answer, and loads more as the reader scrolls: ```html ``` ## Containers | Container | Default layout | Fields from | | ---------------------------------------------------------- | ------------------------------ | -------------------------------- | | [``](/sdk/elements/miso-hybrid-search) | `list`: one result on each row | `fl` on `client.ui.hybridSearch` | To change the results, call `useLayouts` on `client.ui.hybridSearch`, under the role `products`. ## Layouts Give the layout type before the options: ```javascript Results as cards client.ui.hybridSearch.useLayouts({ products: ["cards", { link: { open: false } }], }); ``` | Type | What the reader sees | Class | | ------- | -------------------------------- | ------------ | | `list` | One result on each row. | `miso-list` | | `cards` | Results side by side, in a grid. | `miso-cards` | `carousel` and `horizontal` also draw the results, but they do not load more as the reader scrolls. Use them only when the first page of results is enough. ## Options Your options are merged over the defaults, so set only what you change. | Option | What it does | | ------------------- | -------------------------------------------------------------------------------------------------- | | `link` | Where the links open. `{ open: false }` opens them in the same tab. Also takes `target` and `rel`. | | `className` | The class of the layout, in place of the one in the table above. | | `templates.product` | The markup of one result. | ## Write the markup of a result Give your own function as the `product` template. It returns the HTML of one result. This one shows the image, the title and the description: ```javascript Image, title and description function renderProduct(layout, state, data, meta) { const { tagPair, escapeHtml } = layout.templates.helpers; const [openTag, closeTag] = tagPair(layout, data); const image = data.cover_image ? `` : ""; return openTag + image + `
${escapeHtml(data.title)}
` + `
${escapeHtml(data.description || "")}
` + closeTag; } client.ui.hybridSearch.useLayouts({ products: { templates: { product: renderProduct } }, }); ``` | Argument | What it holds | | -------- | ---------------------------------------------------------------------------------------------------- | | `layout` | The layout. `layout.templates.helpers` has `tagPair` and `escapeHtml`. | | `state` | The state of the whole list. | | `data` | The result. It holds only the fields that `fl` asks for, with `product_id` and `title` always there. | | `meta` | `meta.index` is the position of the result, counted from 0. | * **Start with `tagPair`.** It returns the opening and closing tag of the item, which link to the article and record clicks on it. * **Ask for the fields you show.** `description` is not in the default `fl`. Add it with `useApi`, as [Write the markup of a result](/sdk/hybrid-search/results#write-the-markup-of-a-result) shows. * **Escape every value from the record** with `escapeHtml`. * **Style your own classes** in your CSS. ## Next * [Hybrid Search — Results and Sources](/sdk/hybrid-search/results): the link, layout and markup changes, with complete samples. * [Hybrid Search — Facets](/sdk/hybrid-search/facets): the filters next to the results. * [Hybrid Search — API Configuration](/sdk/hybrid-search/api-config): the number of results, and which articles they come from. # `` The box where the reader types a question. Pressing Enter or selecting the button sends it: ```html ``` ## Containers What the box does with the question depends on its container: | Container | On submit | Placeholder | Button | | ---------------------------------------------------------- | ------------------------------------------ | ---------------- | ------------- | | [``](/sdk/elements/miso-ask) | Asks the question. | "Ask a question" | `send` icon | | [``](/sdk/elements/miso-hybrid-search) | Searches, and answers the question. | None | `search` icon | | [``](/sdk/elements/miso-explore) | Opens the page that `useLink` returns. | "Ask a question" | `search` icon | | [``](/sdk/elements/miso-conversation) | Asks the next question in the open thread. | "Ask a question" | `send` icon | To change the box, call `useLayouts` on the workflow of the container, under the role `query`. For Ask, use `client.ui.asks`, the context, so that the box of each follow-up gets the change too. ## Options Your options are merged over the defaults, so set only what you change. ```javascript Placeholder and button text client.ui.asks.useLayouts({ query: { placeholder: "Ask about this week's news", templates: { buttonText: "Ask", buttonIcon: "" }, }, }); ``` | Option | What it does | | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `placeholder` | The text in the empty box. | | `templates.buttonText` | The text of the button, before the icon. A string, or a function that gets `(layout)`. Empty by default. | | `templates.buttonIcon` | The icon of the button: an icon name from the list below, your own HTML, or a function that gets `(layout)`. `""` removes the icon. | | `clearOnSubmit` | `true` empties the box after the question is sent. | | `blurOnSubmit` | `false` keeps the focus in the box after the question is sent. | | `disableWhenOngoing` | `true` turns the button off, and blocks Enter, while an answer is still on its way. | | `className` | The class of the box, in place of `miso-search-box`. | `` sets `clearOnSubmit`, `blurOnSubmit: false` and `disableWhenOngoing` by default, so the reader can type one question after another. The other containers set none of them. The icon names are `send`, `search`, `triangle`, `triangle-eq`, `chevron`, `chevron-negative`, `bulb`, `dots-vertical`, `plus`, `pencil`, `bell`, `bell-fill` and `trash`. ## Write the markup yourself Put your own markup inside ``. When the element has children, the SDK keeps them and does not draw its own box: ```html Your own box
``` * **Mark the field with `data-role="input"`.** The SDK reads the question from the first element with it. * **Mark the button.** A click on an element with `type="submit"` or `data-role="submit"` sends the question. Pressing Enter in the field sends it too. * **Give the button `data-role="submit"`** if you use `disableWhenOngoing`. That is the button the SDK turns off. * **Leave out `
`.** The SDK does not stop a form from submitting, so the page reloads. The `placeholder` and `templates` options have no effect on your own markup. ## Autocomplete Since 1.13.1 In ``, the box can suggest questions as the reader types. Turn it on for every unit on the page: ```javascript client.ui.explores.autocomplete.enable(); ``` To turn it on for one unit, call `autocomplete.enable()` on that unit, such as `client.ui.explore` for the `default` unit. The suggestions come from the [query suggestion API](/api/reference/tag/explore-apis) after the reader stops typing for 300 ms. Selecting one sends it as the question. To change the wait, set `autocomplete.debounce`, in milliseconds: ```javascript client.ui.explores.useLayouts({ query: { autocomplete: { debounce: 150 } }, }); ``` The suggestions show in an element with the class `miso-autocomplete`. Set `autocomplete.className` to use your own class. ## Next * [Ask — Quick Start](/sdk/ask/quick-start): a box and an answer on one page. * [Explore — Quick Start](/sdk/explore/quick-start): a box that sends the reader to your answers page. * [``](/sdk/elements/miso-answer): the answer to the question. # `` The questions related to the page. Each question is a link to your answers page: ```html ``` ## Containers The element works in [``](/sdk/elements/miso-explore). To change the list, call `useLayouts` on the workflow of the unit, under the role `related_questions`. `client.ui.explore` is the `default` unit, and `client.ui.explores` reaches every unit on the page. Call it before `start()`. The page that a question opens comes from `useLink`, not from the layout. See [Related Questions](/sdk/explore/related-questions#open-the-answers-page-in-the-same-tab). ## Options Your options are merged over the defaults, so set only what you change. | Option | What it does | | -------------------- | ----------------------------------------------- | | `className` | The class of the list, in place of `miso-list`. | | `templates.question` | The markup of one question. | ## Write the markup of a question Give your own function as the `question` template. It returns the HTML of one question. This one adds an arrow after the question: ```javascript An arrow after each question function renderQuestion(layout, state, data) { const { tagPair, escapeHtml } = layout.templates.helpers; const [openTag, closeTag] = tagPair(layout, data); return openTag + `${escapeHtml(data.text)}` + '' + closeTag; } client.ui.explores.useLayouts({ related_questions: { templates: { question: renderQuestion } }, }); ``` | Argument | What it holds | | -------- | ---------------------------------------------------------------------- | | `layout` | The layout. `layout.templates.helpers` has `tagPair` and `escapeHtml`. | | `state` | The state of the whole list. | | `data` | The question. `data.text` is its text. | * **Start with `tagPair`.** It returns the opening and closing tag of the item, which open your answers page and record clicks on it. Without them, a question does nothing when the reader selects it. * **Escape the text** with `escapeHtml`. * **Style your own classes** in your CSS. ## Next * [Explore — Related Questions](/sdk/explore/related-questions): where a question takes the reader, and a complete `question` template. * [Explore — Trending Questions](/sdk/explore/trending-questions): the same list, filled with the questions readers ask most. * [Explore — Events](/sdk/explore/events): run your own code when the reader picks a question. # `` More articles on the topic of the question. Ask shows them under the answer: ```html ``` The answer does not cite these articles, so they have no numbers. For the articles it cites, use [``](/sdk/elements/miso-sources). ## Containers | Container | Default layout | Fields from | | -------------------------------------- | ------------------------------- | ----------------------------------------- | | [``](/sdk/elements/miso-ask) | `list`: one article on each row | `related_resource_fl` on `client.ui.asks` | To change the list, call `useLayouts` on `client.ui.asks`, the context, under the role `related_resources`. Follow-up answers then get the change too. ## Layouts Give the layout type before the options: ```javascript Related resources as a carousel client.ui.asks.useLayouts({ related_resources: "carousel", }); ``` | Type | What the reader sees | Class | | ------------ | -------------------------------------------- | ----------------- | | `list` | One article on each row. | `miso-list` | | `cards` | Articles side by side, in a grid. | `miso-cards` | | `carousel` | One row of articles, with buttons to scroll. | `miso-carousel` | | `horizontal` | One row of small cards. | `miso-horizontal` | ## Options Your options are merged over the defaults, so set only what you change. | Option | What it does | | ------------------- | ------------------------------------------------------------------------------------------------------ | | `link` | Where the links open. `{ open: false }` opens them in the same tab. Also takes `target` and `rel`. | | `className` | The class of the layout, in place of the one in the table above. | | `templates.date` | The date format: options for `toLocaleDateString` with `locale` added, a locale string, or a function. | | `templates.article` | The markup of one article. | To change the date format, give `templates.date` the options of `toLocaleDateString`, with `locale` added: ```javascript 5 March 2026 client.ui.asks.useLayouts({ related_resources: { templates: { date: { locale: "en-GB", year: "numeric", month: "long", day: "numeric" }, }, }, }); ``` ## Write the markup of an article Give your own function as the `article` template. It returns the HTML of one article. This one shows the cover image and the title: ```javascript Image and title function renderArticle(layout, state, data, meta) { const { tagPair, escapeHtml } = layout.templates.helpers; const [openTag, closeTag] = tagPair(layout, data); const image = data.cover_image ? `` : ""; return openTag + image + `
${escapeHtml(data.title)}
` + closeTag; } client.ui.asks.useLayouts({ related_resources: { templates: { article: renderArticle } }, }); ``` | Argument | What it holds | | -------- | ---------------------------------------------------------------------------------------------------------------------- | | `layout` | The layout. `layout.templates.helpers` has `tagPair` and `escapeHtml`. | | `state` | The state of the whole list. | | `data` | The article. It holds only the fields that `related_resource_fl` asks for, with `product_id` and `title` always there. | | `meta` | `meta.index` is the position of the article, counted from 0. | * **Start with `tagPair`.** It returns the opening and closing tag of the item, which link to the article and record clicks on it. * **Escape every value from the record** with `escapeHtml`. * **Style your own classes** in your CSS. ## Next * [Ask — Sources and Related Resources](/sdk/ask/sources): the link, date, layout and markup changes, with complete samples. * [Ask — API Configuration](/sdk/ask/api-config): filter the articles, or change them before Ask draws them. # `` The articles that an answer cites, numbered so that each citation in the answer points to one of them: ```html ``` ## Containers | Container | Default layout | Fields from | | ---------------------------------------------------------- | ----------------------------------------- | --------------------------------------- | | [``](/sdk/elements/miso-ask) | `list`: one article on each row | `source_fl` on `client.ui.asks` | | [``](/sdk/elements/miso-hybrid-search) | `horizontal`: one row of small cards | `source_fl` on `client.ui.hybridSearch` | | `` | `horizontal`, under a **Sources** heading | `source_fl` on `client.ui.conversation` | You do not write `` yourself. [``](/sdk/elements/miso-messages) puts one in each message of the open thread, with a `` in it. To change the sources, call `useLayouts` on the workflow of the container, under the role `sources`. For Ask, use `client.ui.asks`, the context, so that follow-up answers get the change too. ## Layouts Give the layout type before the options: ```javascript Sources as cards client.ui.asks.useLayouts({ sources: ["cards", { link: { open: false } }], }); ``` | Type | What the reader sees | Class | | ------------ | -------------------------------------------- | ----------------- | | `list` | One article on each row. | `miso-list` | | `cards` | Articles side by side, in a grid. | `miso-cards` | | `carousel` | One row of articles, with buttons to scroll. | `miso-carousel` | | `horizontal` | One row of small cards. | `miso-horizontal` | A new type keeps the other options of the default. The small cards of Hybrid Search and of the chat panel keep their compact markup when you change them to `list`. ## Options Your options are merged over the defaults, so set only what you change. | Option | What it does | | ------------------- | ------------------------------------------------------------------------------------------------------ | | `link` | Where the links open. `{ open: false }` opens them in the same tab. Also takes `target` and `rel`. | | `className` | The class of the layout, in place of the one in the table above. | | `templates.date` | The date format: options for `toLocaleDateString` with `locale` added, a locale string, or a function. | | `templates.article` | The markup of one article. | To change the date format, give `templates.date` the options of `toLocaleDateString`, with `locale` added: ```javascript 5 March 2026 client.ui.asks.useLayouts({ sources: { templates: { date: { locale: "en-GB", year: "numeric", month: "long", day: "numeric" }, }, }, }); ``` ## Write the markup of an article Give your own function as the `article` template. It returns the HTML of one article. This one shows the number, the title and the date: ```javascript Number, title and date function renderArticle(layout, state, data, meta) { const { tagPair, escapeHtml } = layout.templates.helpers; const [openTag, closeTag] = tagPair(layout, data); const date = data.published_at ? new Date(data.published_at).toLocaleDateString("en-US", { dateStyle: "medium" }) : ""; return openTag + `` + `
${escapeHtml(data.title)}
` + `
${date}
` + closeTag; } client.ui.asks.useLayouts({ sources: { templates: { article: renderArticle } }, }); ``` For Hybrid Search, set it on `client.ui.hybridSearch`. For the messages of the chat panel, set it on `client.ui.conversation`. | Argument | What it holds | | -------- | ------------------------------------------------------------------------------------------------------------ | | `layout` | The layout. `layout.templates.helpers` has `tagPair` and `escapeHtml`. | | `state` | The state of the whole list. | | `data` | The article. It holds only the fields that `source_fl` asks for, with `product_id` and `title` always there. | | `meta` | `meta.index` is the position of the article, counted from 0. | * **Start with `tagPair`.** It returns the opening and closing tag of the item, which link to the article and record clicks on it. * **Keep the `miso-citation-index` element** with `meta.index + 1`. It draws the number that the citations in the answer point to. * **Escape every value from the record** with `escapeHtml`. * **Style your own classes** in your CSS. ## Next * [Ask — Sources and Related Resources](/sdk/ask/sources): the link, date, layout and markup changes, with complete samples. * [Hybrid Search — Results and Sources](/sdk/hybrid-search/results): the same for Hybrid Search. * [Ask — Citation Links](/sdk/ask/citation-links): the citations in the answer that point to the sources. # `` The list of the reader's chat threads, newest first. When the reader selects a thread, it opens in ``: ```html ``` ## Containers | Container | Layout | | ---------------------------------------------- | --------- | | [``](/sdk/elements/miso-history) | `threads` | `threads` is the only layout for this element. The options below go to `useLayouts` on `client.ui.history`, under the role `threads`. ## Items Each thread is a `` with the title of the thread and a menu. The menu opens from the three dots on the item, and holds **Rename**, **Subscribe** or **Unsubscribe**, and **Delete**. A thread with no title shows **Untitled**. The SDK puts these attributes on each ``, so you can style the items from your CSS: | Attribute | On a thread that | | ---------------- | ------------------------------------------------------------------------------------- | | `data-selected` | Is open in ``. | | `data-unread` | Is subscribed, and has an answer update. | | `data-thread-id` | Has a thread ID. The value is the ID. A thread that is still being created has no ID. | ```css Unread threads in bold miso-thread-item[data-unread] .miso-threads__title { font-weight: 600; } ``` The menu items are elements of the thread, so you change their labels on `client.ui.history` by their own roles: ```javascript Menu labels client.ui.history.useLayouts({ rename: { text: "Edit title" }, subscription: { text: "Follow", checkedText: "Unfollow" }, delete: { text: "Remove" }, }); ``` ## Loading The list loads 100 threads at a time. When the reader scrolls to the end of the list, it loads the next page. To change the page size, see [Number of threads](/sdk/history/api-config#number-of-threads). A reader with no threads sees an empty list. To show a line in its place, put an element with `visible-when="ready+empty"` next to it. See [Chat History — UI Customization](/sdk/history/ui-customization#show-a-part-at-the-right-moment). ## Errors When the list cannot load, a notice takes its place: | Cause | Text | | ------------------------------------ | ------------------------------------------------- | | The session has expired (status 401) | "Your session has expired. Please sign in again." | | Any other failure | "Your conversations could not be loaded." | The `errorMessage` template returns the text. It gets `(layout, error)`, and `error.status` is the HTTP status: ```javascript Error text client.ui.history.useLayouts({ threads: { templates: { errorMessage: (layout, error) => error && error.status === 401 ? "Sign in again to see your chats." : "We could not load your chats.", }, }, }); ``` ## Next * [Chat History — Quick Start](/sdk/history/quick-start): build the thread list and the open thread. * [``](/sdk/elements/miso-messages): the messages of the open thread. # MisoClient The entry point of Miso SDK. Create an instance with your API key to access Miso APIs. When loaded from the CDN, the class is available as `window.MisoClient`. To run code once the SDK is ready, push a function to `window.misocmd`: ```javascript const misocmd = window.misocmd || (window.misocmd = []); misocmd.push(async () => { const client = new MisoClient({ apiKey: "..." }); const response = await client.api.search.search({ q: "shoes" }); }); ``` With the full SDK, plugins also add features to each instance, such as `client.ui` (UI elements and layouts) and `client.workflows` (Ask, Search, etc.). ```javascript import MisoClient from "@miso.ai/client-sdk"; const client = new MisoClient({ apiKey: "..." }); client.context.user_id = "user-123"; ``` ## Constructor ```javascript new MisoClient(options) ``` | Parameter | Type | Description | | ------------------------- | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `options` | `Object` or `string` | Client options, or just the API key as a string. | | `options.apiKey` | `string` | Your Miso publishable API key. Required. | | `options.apiHost` | `string` | Shorthand to set both `dataEndpoint` and `eventEndpoint`. Optional. | | `options.dataEndpoint` | `string` | Base URL for data APIs (Ask, Search, Recommendation). Defaults to `https://api-edge.askmiso.com/v1`. Optional. | | `options.eventEndpoint` | `string` | Base URL for the Interactions API. Defaults to `https://api.askmiso.com/v1`. Optional. | | `options.request` | `Object` | Default settings applied to every API request. Optional. | | `options.request.timeout` | `number` | Request timeout in milliseconds. Optional. | | `options.request.retry` | `number` | Number of retries on network errors, timeouts, and 5xx responses. Off by default, as retrying a non-idempotent call (such as posting a question) may not be safe. Can also be set per request. Default `0`. Optional. | Throws `Error`: If no API key is given. ## Static properties ### `MisoClient.cmdDone` Resolves after all functions pushed to `window.misocmd` before the SDK loaded have run. Type: `Promise` ### `MisoClient.helpers` Utility functions. Type: `Object` ### `MisoClient.instances` All client instances created so far. Type: `MisoClient[]` ### `MisoClient.plugins` Manage plugins, which add optional features to the SDK. * `use(id, options)` activates a plugin, or reconfigures it if already active. * `install(id, options)` is like `use()`, but loads standard (`std:`) plugins from the CDN if needed, and returns a promise of the installed plugin. * `register(PluginClass)` makes a custom plugin class available by its `id`. * `whenInstalled(id)` returns a promise that resolves when the plugin is installed. Type: `Object` ```javascript MisoClient.plugins.use("std:debug"); await MisoClient.plugins.install("std:analytics"); ``` ### `MisoClient.version` The SDK version. Type: `string` ## Static methods ### `MisoClient.any()` Get the first client instance, waiting for one to be created if there is none yet. Returns `Promise`. ### `MisoClient.attach()` Assign `MisoClient` to `window.MisoClient`. The default entry point does this automatically; call it only when you import from a `detached` entry point. If `window.MisoClient` already holds a different SDK copy, it is left untouched and a warning is logged. ### `MisoClient.debug(...args)` Log debug messages. Does nothing unless the `std:debug` plugin is in use. | Parameter | Type | Description | | --------- | ---- | ----------- | | `...args` | `*` | | ### `MisoClient.on(name, callback)` Listen to SDK-level events. For example, `'create'` fires with each new client instance, including the ones created before you started listening. | Parameter | Type | Description | | ---------- | ---------- | ----------- | | `name` | `string` | Event name. | | `callback` | `function` | | Returns `function`: A function to remove the listener. ### `MisoClient.once(name)` Wait for the next occurrence of an SDK-level event. | Parameter | Type | Description | | --------- | -------- | ----------- | | `name` | `string` | Event name. | Returns `Promise<*>`. ## Instance properties ### `client.api` Miso APIs, grouped by `ask`, `search`, `recommendation`, and `interactions`. ```javascript const response = await client.api.recommendation.userToProducts({ rows: 5 }); await client.api.interactions.upload({ type: "click", product_ids: ["P1"] }); ``` ### `client.context` User and site context sent along with API requests, such as `user_id`, `user_hash`, `anonymous_id`, and `site`. Set these to identify the current user. Type: `Object` ### `client.options` The options passed to the constructor, after normalization. Read-only. Type: `Readonly` ### `client.version` The SDK version. Type: `string` # client.api Miso APIs, available as `client.api`, grouped by `ask`, `search`, `recommendation`, and `interactions`. For request payloads and responses, see the Miso API docs. Each API method takes a request payload and optional request options, and returns a promise of the response data. Request options include: * `timeout` - Request timeout in milliseconds. Defaults to `options.request.timeout` of the client. * `retry` - Number of retries on network errors, timeouts, and 5xx responses. Defaults to `options.request.retry` of the client, which is 0. * `bulk` - Send the request with others in a single bulk request. Some Ask APIs return an [`IterableApiStub`](/sdk/javascript/api-iterable-stub) instead, for answers that are generated over time. ## Groups * [`client.api.ask`](/sdk/javascript/api-ask) * [`client.api.ask.userHistory`](/sdk/javascript/api-user-history) * [`client.api.interactions`](/sdk/javascript/api-interactions) # client.api.ask Ask APIs, available as `client.api.ask`. ## Instance properties ### `client.api.ask.userHistory` User history APIs, for the user's past conversation threads. Type: [`UserHistory`](/sdk/javascript/api-user-history) ## Instance methods ### `client.api.ask.answers(payload, [options])` Get the answers of multiple questions at once, as they are generated. Each iteration yields an array of the answers that were still unfinished, so a finished answer is not polled again. Once all are finished, the iteration yields `undefined` and ends. Pass an array of question IDs as a shortcut of `{ question_ids }`. | Parameter | Type | Description | | --------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------- | | `payload` | `Object` or `string[]` | Request payload, or an array of question IDs. | | `options` | `Object` | Request options, including the polling options of [`IterableApiStub`](/sdk/javascript/api-iterable-stub). Optional. | Returns `Promise<`[`IterableApiStub`](/sdk/javascript/api-iterable-stub)`>`. ### `client.api.ask.autocomplete(payload, [options])` Get autocomplete suggestions for a partial question. | Parameter | Type | Description | | --------- | -------- | -------------------------- | | `payload` | `Object` | | | `options` | `Object` | Request options. Optional. | Returns `Promise`. ### `client.api.ask.querySuggestion(payload, [options])` Get query suggestions. | Parameter | Type | Description | | --------- | -------- | -------------------------- | | `payload` | `Object` | | | `options` | `Object` | Request options. Optional. | Returns `Promise`. ### `client.api.ask.questions(payload, [options])` Ask a question, and get the answer as it is generated. Pass a question ID instead of a payload to follow an existing question, without asking again. | Parameter | Type | Description | | --------- | -------------------- | ------------------------------------------------------------------------------------------------------------------- | | `payload` | `Object` or `string` | Request payload, or a question ID. | | `options` | `Object` | Request options, including the polling options of [`IterableApiStub`](/sdk/javascript/api-iterable-stub). Optional. | Returns `Promise<`[`IterableApiStub`](/sdk/javascript/api-iterable-stub)`>`: The answer, which has a `questionId` property. ```javascript const answer = await client.api.ask.questions({ question: "What is Miso?" }); for await (const response of answer) { console.log(response.answer); } ``` ### `client.api.ask.relatedQuestions(payload, [options])` Get questions related to a given question. | Parameter | Type | Description | | --------- | -------- | -------------------------- | | `payload` | `Object` | | | `options` | `Object` | Request options. Optional. | Returns `Promise`. ### `client.api.ask.search(payload, [options])` Search with a query, with an answer generated over time. If the response comes with a question ID, it is returned as an [`IterableApiStub`](/sdk/javascript/api-iterable-stub) with the response fields (such as the search results) on it, to follow the answer. Otherwise the response is returned as is. Pass a question ID instead of a payload to follow an existing search. | Parameter | Type | Description | | --------- | -------------------- | ------------------------------------------------------------------------------------------------------------------- | | `payload` | `Object` or `string` | Request payload, or a question ID. | | `options` | `Object` | Request options, including the polling options of [`IterableApiStub`](/sdk/javascript/api-iterable-stub). Optional. | Returns `Promise<`[`IterableApiStub`](/sdk/javascript/api-iterable-stub)` | Object>`. ### `client.api.ask.searchAutocomplete(payload, [options])` Get autocomplete suggestions for a partial search query. | Parameter | Type | Description | | --------- | -------- | -------------------------- | | `payload` | `Object` | | | `options` | `Object` | Request options. Optional. | Returns `Promise`. ### `client.api.ask.trendingQuestions(payload, [options])` Get trending questions. | Parameter | Type | Description | | --------- | -------- | -------------------------- | | `payload` | `Object` | | | `options` | `Object` | Request options. Optional. | Returns `Promise`. # client.api.ask.userHistory User history APIs, available as `client.api.ask.userHistory`, for the current user's past conversation threads. ## Instance methods ### `client.api.ask.userHistory.deleteAllThreads([options])` Delete all of the user's threads. | Parameter | Type | Description | | --------- | -------- | -------------------------- | | `options` | `Object` | Request options. Optional. | Returns `Promise`. ### `client.api.ask.userHistory.deleteThread(threadId, [options])` Delete a thread. | Parameter | Type | Description | | ---------- | -------- | -------------------------- | | `threadId` | `string` | | | `options` | `Object` | Request options. Optional. | Returns `Promise`. ### `client.api.ask.userHistory.deleteThreads(payload, [options])` Delete multiple threads. | Parameter | Type | Description | | --------- | -------- | -------------------------- | | `payload` | `Object` | | | `options` | `Object` | Request options. Optional. | Returns `Promise`. ### `client.api.ask.userHistory.dismissNotifications([options])` Dismiss all notifications. | Parameter | Type | Description | | --------- | -------- | -------------------------- | | `options` | `Object` | Request options. Optional. | Returns `Promise`. ### `client.api.ask.userHistory.getNotifications([options])` Get notifications of updates to the user's threads. | Parameter | Type | Description | | --------- | -------- | -------------------------- | | `options` | `Object` | Request options. Optional. | Returns `Promise`. ### `client.api.ask.userHistory.getThread(threadId, [payload], [options])` Get a thread, with the IDs of its questions. | Parameter | Type | Description | | ---------- | -------- | -------------------------- | | `threadId` | `string` | | | `payload` | `Object` | Optional. | | `options` | `Object` | Request options. Optional. | Returns `Promise`. ### `client.api.ask.userHistory.getThreads(payload, [options])` List the user's threads. | Parameter | Type | Description | | --------- | -------- | -------------------------- | | `payload` | `Object` | | | `options` | `Object` | Request options. Optional. | Returns `Promise`. ### `client.api.ask.userHistory.markThreadAsRead(threadId, [options])` Mark a thread as read, dismissing its notifications. | Parameter | Type | Description | | ---------- | -------- | -------------------------- | | `threadId` | `string` | | | `options` | `Object` | Request options. Optional. | Returns `Promise`. ### `client.api.ask.userHistory.subscribeThread(threadId, [options])` Subscribe to updates of a thread. | Parameter | Type | Description | | ---------- | -------- | -------------------------- | | `threadId` | `string` | | | `options` | `Object` | Request options. Optional. | Returns `Promise`. ### `client.api.ask.userHistory.unsubscribeThread(threadId, [options])` Unsubscribe from updates of a thread. | Parameter | Type | Description | | ---------- | -------- | -------------------------- | | `threadId` | `string` | | | `options` | `Object` | Request options. Optional. | Returns `Promise`. ### `client.api.ask.userHistory.updateThread(threadId, payload, [options])` Update a thread, such as its title. | Parameter | Type | Description | | ---------- | -------- | -------------------------- | | `threadId` | `string` | | | `payload` | `Object` | | | `options` | `Object` | Request options. Optional. | Returns `Promise`. # client.api.interactions Interactions APIs, available as `client.api.interactions`. ## Instance methods ### `client.api.interactions.upload(payload, [options])` Upload interaction events, such as clicks and add-to-carts. Pass an interaction object, or an array of them. By default the request is sent with `navigator.sendBeacon()`, so it survives page navigation but its response is not available. Set `useBeacon: false` in the request options to send it with `fetch()` instead. | Parameter | Type | Description | | --------- | ---------------------- | -------------------------------------------- | | `payload` | `Object` or `Object[]` | An interaction, or an array of interactions. | | `options` | `Object` | Request options. Optional. | Returns `Promise`. # IterableApiStub A handle on an answer that the server generates over time, returned by APIs such as `client.api.ask.questions()`, `client.api.ask.search()`, and `client.api.ask.answers()`. Iterate it with `for await` to receive the response as it progresses. The stub polls the server in the background, and each iteration yields the latest full response, not a delta. When the consumer is slower than the polling, intermediate responses are skipped. The iteration ends once the response is finished (`finished: true`). To read the response just once without polling, call `get()`. Polling can be tuned by the request options passed to the API method: * `pollingInterval` - Milliseconds between polls. Defaults to 1000. * `stallTimeout` - Milliseconds without progress before polling gives up with an error. Defaults to 120000. * `signal` - An `AbortSignal` to stop the polling. Polling also stops when `abort()` is called. If the abort reason is an `Error` (including the default `AbortError` when no reason is given), the iteration throws it; with any other reason, the iteration just ends. The iteration also throws when polling fails more than 10 times in a row. ```javascript const answer = await client.api.ask.questions({ question: "What is Miso?" }); for await (const response of answer) { render(response.answer); } ``` ```javascript // stop polling, e.g. when the user navigates away answer.abort(); ``` ## Instance methods ### `answer[Symbol.asyncIterator]()` Start polling, yielding the latest response until it is finished. Returns `AsyncIterator`. ### `answer.abort([reason])` Stop polling. An ongoing iteration throws `reason` if it is an `Error`, or an `AbortError` if no reason is given; otherwise the iteration just ends. | Parameter | Type | Description | | --------- | ---- | ----------- | | `reason` | `*` | Optional. | ### `answer.get([options])` Fetch the current response once, without polling. | Parameter | Type | Description | | --------- | -------- | ------------------------------------------------------------------------ | | `options` | `Object` | Request options, merged over the ones given to the API method. Optional. | Returns `Promise`. # Reader type Tell Miso which kind of reader is asking. `user_type` labels every question with the kind of reader who asked it: a signed-out visitor, a registered reader, a subscriber, or your own staff. Below we set it, and show what breaks when it is missing. Miso uses the label for two things: - **Entitlements.** Each type maps to a tier, and the tier decides how many answers the reader gets. See [Metering & Entitlements](/operate/metering). - **The record.** The label is stored with the question, so your own reporting can separate the groups later. ## Set it in the browser `user_type` lives on the client context, beside the reader's id: ```js On sign-in const misocmd = window.misocmd || (window.misocmd = []); misocmd.push(async () => { const client = new MisoClient("YOUR_PUBLISHABLE_KEY"); client.context.user_id = "u-10293"; // your own stable id client.context.user_type = "subscriber"; await client.ui.ready; }); ``` Set it as early as you know it, and before the first question. Every later question carries it. When a reader signs in or out during the visit, assign the new values. The next request picks them up: ```js The reader signs in client.context.user_id = "u-10293"; client.context.user_type = "registered"; ``` ## `user_type` needs `user_id` > **CAUTION: a reader with only an `anonymous_id` sends no `user_type`.** The > SDK drops it. There is no error, and the question arrives unlabelled. The two fields travel together, so set both: ```js What actually goes out client.context.anonymous_id = "anon-abc"; client.context.user_type = "internal"; // → { "anonymous_id": "anon-abc" } user_type is gone client.context.user_id = "staff-42"; client.context.user_type = "internal"; // → { "user_id": "staff-42", "user_type": "internal" } ``` A signed-out visitor is `anonymous` to Miso whatever you set, which is the right answer: you have no identity to label. ## The values | Value | Tier | Use it for | | --- | --- | --- | | `anonymous` | anon | A signed-out visitor. | | `registered` | reg | A reader with an account and no subscription. | | `subscriber` | sub | A paying reader. | | `internal` | sub | Your own staff. | | `free` | reg | The same as `registered`. | | `paid` | sub | The same as `subscriber`. | The list is fixed. A value outside it is rejected. **`internal` carries subscriber entitlements.** Your staff get the subscriber allowance, and their questions stay labelled `internal`. That is usually what you want: the team is not metered like a reader, and their questions stay recognisable in the record. ## Where it applies `user_type` rides along on the answer endpoints: questions, hybrid search and summaries. It is **removed** from search and recommendation requests. Those endpoints rank by behaviour rather than by tier, so the label has no job there. This is automatic, and it is not a fault to debug. ## Check it is working Open the network panel and look at the body of a `POST /v1/ask/questions`: ```json A labelled question { "user_id": "staff-42", "user_type": "internal", "question": "…" } ``` If `user_type` is missing, check `user_id` first. That is the cause almost every time. ## Next - [Metering & Entitlements](/operate/metering) — how each type maps to a tier, what happens at the limit, and how to set the allowances. - [Answer API](/api/genai/answer) — the field on the endpoint itself. - [SDK Overview](/sdk/overview) — the parts of the SDK. # Filtering (fq) Set the rules your product enforces, from the browser. `fq` restricts what the SDK can return. It runs before ranking, so it decides **what is eligible**, never the order of what is left. Use it for the rules your product sets: one section of the site, free articles only, nothing older than a year. Below we set one, then change it while the page runs. `fq` is the outer boundary. It removes content globally, for every request. Inside what is left, a reader narrows further with [facets](/sdk/hybrid-search/facets), which the SDK handles for you. See [Filter Syntax (fq)](/api/fq) for the filter language itself: field matches, ranges, and the boolean operators. ## Set it once `fq` is part of the request, so it goes in `useApi()`: ```js A fixed filter const misocmd = window.misocmd || (window.misocmd = []); misocmd.push(async () => { const client = new MisoClient("YOUR_PUBLISHABLE_KEY"); const workflow = client.ui.hybridSearch; workflow.useApi({ fq: 'custom_attributes.premium:"false"', }); await client.ui.ready; }); ``` Every request from that workflow now carries the filter. You do not repeat it per query. **Put it on the context when the feature has one.** For Ask, a follow-up answer is a new workflow, so a filter set on `client.ui.ask` never reaches it. Set it on `client.ui.asks` instead. See [Ask — API Configuration](/sdk/ask/api-config). | Workflow | Where the filter goes | | --- | --- | | Ask | `client.ui.asks.useApi({ fq })` | | Hybrid Search | `client.ui.hybridSearch.useApi({ fq })` | | Search | `client.ui.search.useApi({ fq })` | ## Change it while the page runs Call `useApi()` again and run the query again. The new filter replaces the old one: ```js Switch the filter on a tab click document.querySelector("#tab-tech").addEventListener("click", () => { workflow.useApi({ fq: 'tags:"Science and technology"' }); workflow.query({ q: currentQuery }); }); ``` This is the pattern for section tabs, a "free articles only" toggle, or a date range control. `clearApi()` drops everything you set, so keep a base object if you use it. ## What a filter also changes **Facet counts follow the filter.** Facets count the results that match, and `fq` decides what matches. A tag showing 48 results with no filter shows 21 once `fq: custom_attributes.word_count:[300 TO *]` applies. The counts a reader sees always describe the results they can actually reach. **Answers narrow with it.** On Ask and Hybrid Search, `fq` also restricts the passages the answer can cite, so the answer and the result list stay consistent. ## fq and reader filters work together A reader picking a facet does not replace your `fq`. The two travel in different fields and both apply: ```json One request, both filters { "q": "linux", "fq": "custom_attributes.word_count:[300 TO *]", "facet_filters": { "tags": { "terms": ["Computing"] } } } ``` A reader cannot widen past your filter. See [Facets](/sdk/hybrid-search/facets). ## Common filters ```text Keep paid content out custom_attributes.premium:"false" ``` ```text One section only tags:"Science and technology" ``` ```text This year published_at:[2026-01-01T00:00:00Z TO *] ``` ```text Everything except one tag NOT tags:Sponsored ``` > **Quote any value with a space.** `tags:Science and technology` returns > nothing and reports no error, because the space ends the value. Write > `tags:"Science and technology"`. See [Filter Syntax (fq)](/api/fq). ## Next - [Filter Syntax (fq)](/api/fq) — the full language, with worked examples. - [Facets](/sdk/hybrid-search/facets) — let readers filter for themselves. - [Hybrid Search — Results and Sources](/sdk/hybrid-search/results) — change what each result looks like. # API Overview The conventions every Miso endpoint shares. Miso is one REST API on `https://api.askmiso.com`. You send JSON. You get JSON back. You authenticate with an API key. You give Miso your content. Miso indexes it and atomizes it. You then ask questions against it, search it, recommend from it, or let an AI agent read it. Miso records every call, so you can measure what people ask and what they read. ## How Miso fits together ```mermaid %%{init: {'theme':'base','themeVariables':{ 'fontFamily':'IBM Plex Sans, ui-sans-serif, system-ui','fontSize':'14px', 'lineColor':'#9aa3c0','clusterBkg':'transparent','clusterBorder':'#d3d8e8','titleColor':'#8b93ad' },'flowchart':{'curve':'basis','nodeSpacing':20,'rankSpacing':78,'padding':12}}}%% flowchart LR subgraph SRC["YOUR SIDE"] direction TB CMS["`Your content REST · SFTP · crawler · webhook`"] SITE["`Your site Miso SDK or your own frontend`"] end subgraph MISO["MISO"] direction TB DATA(["Data APIs"]) IDX["`Index text · embeddings`"] ATOM["`Atomize knowledge graph`"] SERVE(["Serving APIs"]) end subgraph OUT["WHAT YOU BUILD"] direction TB ASK["Answers"] SEARCH["Search & Explore"] REC["Recommendation"] FEED["News Feed"] SUM["Summary"] LB["LightBox"] MCP["MCP for AI agents"] end CMS --> DATA SITE --> DATA DATA --> IDX --> SERVE DATA --> ATOM --> SERVE SERVE --- ASK SERVE --- SEARCH SERVE --- REC SERVE --- FEED SERVE --- SUM SERVE --- LB SERVE --- MCP classDef src fill:#f6f7fa,stroke:#c9cfe0,color:#454c69 classDef hub fill:#3148be,stroke:#3148be,color:#ffffff,stroke-width:0px classDef core fill:#e8ecfb,stroke:#b9c2ea,color:#22307a classDef outbox fill:#f4effc,stroke:#cdbcf0,color:#40277a class CMS,SITE src class DATA,SERVE hub class IDX,ATOM core class ASK,SEARCH,REC,FEED,SUM,LB,MCP outbox ``` Miso does two things with each record, and they run in parallel: - **Index.** Miso stores the full text and computes embeddings. This is what makes hybrid search and retrieval work. - **Atomize.** Miso extracts the entities, the topics, and the relations between them into a knowledge graph. This is what lets Miso reason across many articles instead of one at a time. *** ## Integrate in three steps ### 1. Send your content Upload your catalog with the [Data APIs](/api/reference/tag/product-content-apis). Most customers `POST` to `/v1/products` from their CMS. Miso also accepts SFTP drops, a crawler, and webhooks. See [Integrating Your Data](/data/integrating-your-data) for each option. ### 2. Put Miso on your site Deploy the [Miso SDK](/sdk/overview). It gives you the front-end components **and** it captures interactions for you. This is the fastest path, and it is what most customers use. If you build your own front end, call the API directly and send the interactions yourself with `POST /v1/interactions`. That endpoint is the only one a publishable key can reach, so you can call it from the browser. ### 3. Check your data in Dojo Open your [Dojo dashboard](https://dojo.askmiso.com/). Dojo shows what Miso holds for you, how your answers perform, and where users click. You also configure your app there. See [Answer Metrics](/operate/answer-metrics). *** ## What is in the API | Group | What it does | Where to start | | --- | --- | --- | | **Data APIs** | Upload and delete products, users, and interactions. | [Integrating Your Data](/data/integrating-your-data) · [Product Schema](/data/product-schema) | | **GenAI APIs** | Answers, summaries, tagging, user history, and Explore. | [Explore Questions](/api/genai/explore) | | **Search & Rec APIs** | Search, recommendations, and bulk reads, without an answer. | [Search & Recommendation](/api/search-rec/overview) | | **Experiment APIs** | Report experiment events back to Miso. | [API Reference](/api/reference) | News Feed and LightBox are built on these same APIs. Ask your Miso representative how to enable them for your app. *** ## Quick example Ask a question against your content with a single call (authenticate with `?api_key=YOUR_SECRET_KEY` or the `X-API-KEY` header): ```bash Request curl -X POST "https://api.askmiso.com/v1/ask/questions" \ -H "X-Api-Key: YOUR_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "anonymous_id": "visitor-8f3a1c", "question": "What are the latest rate-cut expectations?" }' ``` ```json Response { "message": "success", "data": { "question_id": "0e1f2a3b-4c5d-6e7f-8a9b-0c1d2e3f4a5b" } } ``` Then poll `GET /v1/ask/questions/{question_id}/answer` for the result. See [Getting started](/start/getting-started) for the full flow. *** ## API conventions The same rules apply to every endpoint. ### Two hostnames Miso answers on two hostnames. They serve the same API, the same data and the same keys. | Hostname | Use it for | | --- | --- | | `https://api.askmiso.com` | Calls from your own servers. | | `https://api-edge.askmiso.com` | Calls from a reader's browser, and anything where latency shows. | `api-edge` is behind a CDN. The connection and the TLS handshake finish at a point of presence near the reader rather than at the origin, which is the part of a browser request you cannot optimise from your own code. Your server sits in one place and usually sits near the origin already, so it gains little. **The SDK already does this.** It sends reads to `api-edge` and interactions to `api.askmiso.com`: ```js What the SDK uses by default DATA_ENDPOINT = "https://api-edge.askmiso.com/v1" // search, answers, questions EVENT_ENDPOINT = "https://api.askmiso.com/v1" // POST /v1/interactions ``` To point either one somewhere else, pass an options object rather than a bare key. The option is `apiKey`, and `apiHost` is a shorthand that sets both endpoints at once: ```js Override the hosts const client = new MisoClient({ apiKey: "YOUR_PUBLISHABLE_KEY", dataEndpoint: "https://api-edge.askmiso.com/v1", eventEndpoint: "https://api.askmiso.com/v1", }); ``` An id is not tied to the hostname that created it. A `question_id` or a `tagging_id` from one host polls on the other. ### Two keys, two jobs Send your key in the `X-API-KEY` header, or as an `api_key` query parameter. | Key | Where it belongs | What it can reach | | --- | --- | --- | | **Publishable** | Browser code. It is expected to be visible. | `POST /v1/interactions` only. | | **Secret** | Your server. Never ship it to a browser. | Every endpoint. | A publishable key on any other endpoint returns `403`. Miso also refuses a publishable key that arrives with a robot user-agent. See [Authentication](/api/authentication). ### Every response has the same shape A successful call returns a `message` and a `data` field: ```json Success { "message": "success", "data": {} } ``` An error keeps `message` and explains what went wrong. A failed upload also carries `errors`, and puts one entry per bad record in `data`. The GenAI APIs use a second shape for a malformed request body. It comes from the request validator, and it names the field: ```json 422 — malformed request body { "detail": [ { "loc": ["body", "__root__"], "msg": "Either 'template' or 'instructions' or 'task_id' must be provided", "type": "value_error" } ] } ``` Read `detail` when it is present, and `message` otherwise. | Code | What it means | | --- | --- | | `200` | Success. On an upload, still read `errors` in the body. | | `401` | The key is missing or wrong. | | `403` | A publishable key on a secret-key endpoint, or a blocked robot. | | `404` | Unknown id. A question that belongs to another app is also `404`. | | `422` | The records did not pass validation. `data` lists each problem. | | `429` | Too many requests. Slow down and retry. | | `500` | A fault on Miso's side. Retry, then contact Miso. | ### Uploads validate as a batch If one record fails validation, Miso rejects the whole batch and returns `422`. Nothing is written. Fix the records that `data` names, then send the batch again. One rule catches most failures: Miso rejects any **top-level** field it does not define. Everything of your own belongs in `custom_attributes`. Add `dry_run=1` to validate a batch without writing it. ### Uploads are asynchronous `POST /v1/products` and `POST /v1/users` return a task id: ```json Upload accepted { "message": "success", "data": { "task_id": "b3BhcXVlLXRhc2staWQtYWJvdXQtMTQwLWNoYXJhY3RlcnMtbG9uZw…" } } ``` Poll `GET /v1/products/_status/{task_id}` (or `/v1/users/_status/{task_id}`) until it stops reporting `pending`. Allow at least a minute: a single-record batch takes about 51 seconds to finish. Interactions do not work this way. `POST /v1/interactions` answers immediately, so you can call it on every click. ### Answers are asynchronous too Ask a question, then poll for the answer: 1. `POST /v1/ask/questions` returns a `question_id`. 2. `GET /v1/ask/questions/{question_id}/answer` returns the answer so far. 3. Stop when `finished` is `true`. **Poll on `finished`. Do not test `answer_stage`.** `answer_stage` is a sentence for a reader, such as `"Doing more research, this may take a little longer"`, and Miso translates it into the language of your app. Its wording changes. The `finished` flag does not. Poll every 1 to 2 seconds. Answers finish in about 12 to 14 seconds. ### Miso does not call you back There are no webhooks and no streaming endpoint for answers. Every result is retrieved by a poll, as described above. ### Rate limits Miso limits requests per API key. Over the limit, you get `429`. Retry with an exponential backoff. Bulk endpoints have a tighter limit than the rest. Your exact limit depends on your plan and your region, so ask your Miso representative before you build a large backfill. # Authentication Two keys. Which one to use, and where each belongs. Every Miso request carries an API key. Which key you use decides what the request can reach, so start here before you write any integration code. You get two keys per environment: | Key | Where it belongs | What it reaches | | --- | --- | --- | | **Secret** | Your server | Every endpoint, including uploads and deletes. | | **Publishable** | The browser | `POST /v1/interactions`, and read-only calls. | The secret key trusts the caller completely, so it never leaves your back end. The publishable key travels to the browser, so Miso limits what it can do. > **Which hostname?** Browser code calls `https://api-edge.askmiso.com`, which > is behind a CDN. Server code calls `https://api.askmiso.com`. Both take the > same keys. See [Two hostnames](/api/overview#two-hostnames). ## API Keys Miso uses API keys to authenticate requests. You can view and manage your API keys in the [Dojo Dashboard](https://dojo.askmiso.com/docs/api-browser). Each environment has its own set of keys: one secret key and one publishable key. Pass the appropriate key with every API request. *** ## Environments There are three environments in Miso: * **Playground** — A read-only tutorial environment pre-loaded with sample data. Use this to explore Miso's APIs without affecting your own data. * **Development** — For staging, QA, and experimentation. Use this environment to test your integration before going live. * **Production** — Your live environment. Use this for all requests that serve real users. *** ## Secret API Key The secret API key grants full access to all Miso API endpoints, including data ingestion and engine queries. **Keep this key private.** Never expose it in client-side code or public repositories. If the key is compromised, revoke it in the [Dojo Dashboard](https://dojo.askmiso.com/docs/api-browser) and generate a new one. You can pass the secret key in either of two ways: **As a request header:** ```http Header X-API-KEY: YOUR_SECRET_KEY ``` **As a query parameter:** ```http Query parameter GET /v1/recommendation/user_to_products?api_key=YOUR_SECRET_KEY ``` *** ## Publishable API Key The publishable API key is intended for use in front-end code (for example, browser JavaScript). Use it to stream interactions from the browser, and to retrieve read-only search, recommendation and answer results. Most of what it reaches works for a signed-out visitor, on an `anonymous_id`. You prove who the reader is only when the request **claims** a `user_id`. Send a signed JWT for that. The reader's own history, under `/v1/ask/user_history/…`, always needs one. Below is the signed-in path. A signed-out visitor skips steps 1 to 3 and sends the publishable key on its own. ```mermaid %%{init: {'theme':'base','themeVariables':{ 'fontFamily':'IBM Plex Sans, ui-sans-serif, system-ui','fontSize':'14px', 'actorBkg':'#3148be','actorBorder':'#3148be','actorTextColor':'#ffffff', 'actorLineColor':'#9aa3c0','signalColor':'#9aa3c0','signalTextColor':'#6b7392', 'labelBoxBkgColor':'#f4effc','labelBoxBorderColor':'#cdbcf0', 'labelTextColor':'#40277a','noteBkgColor':'#e8ecfb','noteBorderColor':'#b9c2ea', 'noteTextColor':'#22307a','sequenceNumberColor':'#ffffff' }}}%% sequenceDiagram autonumber participant B as Browser participant S as Your server participant M as Miso B->>S: the reader signs in S->>S: sign a short-lived JWT with your secret key S-->>B: publishable key plus that JWT B->>M: API call with both M->>M: verify the JWT M-->>B: only this reader's data Note over S,M: the secret key never leaves your server ``` Pass the publishable key as a query parameter: ```http Publishable key POST /v1/interactions?api_key=YOUR_PUBLISHABLE_KEY ``` *** ## JWT (user authentication) An API key says which **app** is calling. A JWT says which **reader**. Send one when a request speaks for a signed-in person, so Miso can trust the `user_id` even though the call comes from a browser holding a publishable key. Where it matters: - **The reader's own history.** Every `POST /v1/ask/user_history/…` endpoint requires an authenticated user. With a publishable key and no token, they answer `401 Authenticated user_id is required`. - **Answers tied to a person.** `POST /v1/ask/questions` honours the token and takes the `user_id` from it. - **Metering.** The token can also carry `user_type`, so the reader's tier comes from your server and a page cannot change it. See [Metering and `user_type`](#metering-and-usertype) below. A secret key already carries that trust, so server-side calls need no token. ### Sign the token **HS256, and the signing secret is your Secret API Key** — the one in Dojo for that environment. There is no separate JWT secret to configure, and no RS256 or JWKS. Rotating the secret key invalidates every token signed with the old one. Mint tokens on your server, where the secret already lives. Keep them short, 15 minutes to an hour, and refresh as the reader keeps browsing. ```javascript Node import jwt from "jsonwebtoken"; const token = jwt.sign( { user_id: "user-123", user_type: "subscriber", // optional, for metering exp: Math.floor(Date.now() / 1000) + 15 * 60, }, process.env.MISO_SECRET_API_KEY, // your Secret API Key { algorithm: "HS256" } ); ``` ```python Python import jwt, time token = jwt.encode( { "user_id": "user-123", "user_type": "subscriber", # optional, for metering "exp": int(time.time()) + 900, }, MISO_SECRET_API_KEY, algorithm="HS256", ) ``` ### The claims | Claim | Notes | | --- | --- | | `user_id` | The reader. Preferred. | | `sub` | The same job, for tokens you already issue. `user_id` wins when both appear. | | `user_type` | The reader's tier, for [metering](#metering-and-usertype). | | `exp` | Unix seconds. Checked when present. Recommended on every token. | | `nbf` | Checked when present. | | `iat`, `iss`, `aud` | Accepted, and not validated. | Any other claim rides along. On `POST /v1/ask/questions` the extras merge into the request `metadata`, so a subscription tier in the token reaches your analytics. **Put nothing secret in a token.** It travels to the browser, and anyone holding it can read it. ### Metering and `user_type` [Metering](/operate/metering) gives each reader tier its own question allowance, and `user_type` names the tier. Put it in the token next to `user_id`, so the tier comes from your server. In the following token, we mark the reader as a subscriber: ```json title="Claims" { "user_id": "user-123", "user_type": "subscriber", "exp": 1789500000 } ``` The values are `anonymous`, `registered`, `free`, `subscriber`, `paid` and `internal`. Anything else is `401 Invalid JWT token: unknown user_type …`. A reader can be a subscriber today and lapse tomorrow, so mint the token on each visit, after your own session check, and keep `exp` short. > **NOTE:** The request body also accepts `{ "user_type": "subscriber" }`. If > you send it and the token carries `user_type` too, the two must match, or the > request is `401 Token does not match the user_type`. ### Send the token Either way works, and the header wins when you send both: ```http Authorization header POST /v1/ask/questions?api_key=YOUR_PUBLISHABLE_KEY Authorization: Bearer Content-Type: application/json { "question": "What changed in the 2026 budget?" } ``` Or as a `jwt_token` field in the request body: ```http jwt_token in the body POST /v1/ask/questions?api_key=YOUR_PUBLISHABLE_KEY Content-Type: application/json { "question": "What changed in the 2026 budget?", "jwt_token": "" } ``` Leave `user_id` and `user_type` out of the body and Miso takes them from the token. Send a field both ways and the two must match. Miso strips the token from the request before anything is logged. ### What comes back when it fails | Status | Message | Cause | | --- | --- | --- | | `401` | `Invalid JWT token` | Bad signature, or a malformed token. | | `401` | `JWT token expired (exp=…)` | `exp` is in the past. | | `401` | `JWT token not yet valid` | `nbf` is in the future. | | `401` | `Token does not match the user` | The body `user_id` differs from the token's. | | `401` | `Token does not match the user_type` | The body `user_type` differs from the token's. | | `401` | `Invalid JWT token: unknown user_type …` | The `user_type` claim is outside the allowed list. | | `401` | `Authenticated user_id is required` | The endpoint needs a reader, and no token arrived. | ## Next - [API Overview](/api/overview) — conventions shared by every endpoint. - [Errors & Rate Limits](/api/errors) — what a `401` and a `403` mean here. - [User History](/api/genai/user-history) — the browser flow, with a signed JWT. # Errors & Rate Limits What each status code means, and which ones to retry. Every Miso endpoint reports failure the same way. ## Error shapes Most errors carry a `message`: ```json Error { "message": "invalid api key." } ``` A failed **upload** adds `errors`, and puts one entry per bad record in `data`: ```json 422 — upload { "errors": true, "message": "None of the records were inserted because at least one of them contained schema errors. Please see the `data` field for details.", "data": [ "data.1.published_at (not-a-date) is invalid. The attribute does not match any of the subschemas. (id: x)" ] } ``` A malformed **request body** on a GenAI endpoint comes from the request validator, and names the field instead: ```json 422 — request body { "detail": [ { "loc": ["body", "__root__"], "msg": "Either 'template' or 'instructions' or 'task_id' must be provided", "type": "value_error" } ] } ``` Read `detail` when it is present, and `message` otherwise. ## Status codes | Code | Meaning | What to do | | --- | --- | --- | | `200` | Success. | On an upload, still read `errors` in the body. | | `400` | The request is malformed. | Read `message`. | | `401` | The key is missing or wrong. | Check the header name (`X-API-KEY`) and the key. | | `403` | A publishable key on a secret-key endpoint, or a blocked robot. | Use the secret key from your server. | | `404` | Unknown id. | A `question_id` from another app is also `404`. So is a deleted product. | | `422` | Validation failed. | Read `data` or `detail` for the field. | | `429` | Over the rate limit. | Back off, then retry. | | `500` | A fault on Miso's side. | Retry, then contact Miso. | ## The errors you will actually hit **`403` on a product upload.** You used the publishable key. It reaches `POST /v1/interactions` and nothing else: ```json { "message": "Publishable key is not allowed for this endpoint; use the secret key" } ``` **`422` on a whole batch because of one record.** Uploads are all-or-nothing. Nothing is written. The `data` array names each problem by index, so `data.1.published_at` is the second record in the batch you sent. **`422` for a field Miso does not define.** Any unknown top-level field is rejected. Everything of your own belongs in `custom_attributes`. See [Product Schema](/data/product-schema). **`404` from the status endpoint.** The task id is unknown or it expired. Task ids do not live forever. Read the status while the load runs, not the next day. **`404` "engine is not found".** Search and recommendation run on an engine that Miso creates for your app. Answers and hybrid search do not. If those work and `/v1/search/*` does not, ask Miso to create the engine. **`404` "no such index" from `/v1/users/*`.** The user index is created by your first user upload. Before that, reading user ids or aggregations returns this. **`404` "field is not found" from `_aggregations`.** Miso aggregates fields it holds in the schema, such as `published_at`. A field no record carries is not there to aggregate, and not every custom attribute can be reached this way. **`403` on interactions from a server.** A publishable key is meant for a browser, so Miso refuses it when the request looks automated: ```json { "message": "Request is denied due to bot blocking. Please only access this API from a real browser or use Secret API Key instead." } ``` Use the secret key from your back end, and keep the publishable key in the browser. ## Rate limits Miso limits requests per API key. Over the limit you get `429`. Three things to plan for: - **Bulk endpoints are stricter** than the rest. - **Your limit depends on your plan and your region.** Ask your Miso representative before you build a large backfill. - **Retry with an exponential backoff.** Start at a few seconds and double it. ```python Retry on 429 import time, requests def post(url, headers, body, attempts=5): delay = 2 for _ in range(attempts): res = requests.post(url, headers=headers, json=body) if res.status_code != 429: return res time.sleep(delay) delay *= 2 return res ``` A steady upload of about 100 records per call runs inside the limit without a backoff. A full load of 20,901 records in 210 calls hits no `429` at all. ## When the call succeeds but nothing happens An upload returns `200` when Miso **accepts** the batch, not when the records are searchable. Poll the task, and expect it to take up to a minute. See [Integrating Your Data](/data/integrating-your-data). An answer that refuses is not an error either. `finish_reason` is `success`, `sources` is empty, and the text explains that Miso found nothing. Check that the catalog holds the article, and that the upload finished. # Async Results & Polling One polling contract for Answer, Summary and Content Tagging. Three Miso endpoints do their work in the background. You submit a request, get an id, and poll until the job is over. Below we show what to read, what to retry, and the loop that does both. | API | Submit | Poll | You read | | --- | --- | --- | --- | | [Answer](/api/genai/answer) | `POST /v1/ask/questions` | `GET /v1/ask/questions/{question_id}/answer` | `answer`, `sources` | | [Summary](/api/genai/summary) | `POST /v1/ask/summary` | `GET /v1/ask/summaries/{question_id}/summary` | `answer`, `sources` | | [Content Tagging](/api/genai/tagging) | `POST /v1/ask/tagging/{tag_set}` | `GET /v1/ask/tagging/{tag_set}/{tagging_id}` | `tags` | They report progress the same way, so one polling client serves all three. --- ## `finished` and `finish_reason` `finished` says the job is over. `finish_reason` says whether it worked. > **Do not branch on the progress label.** `answer_stage` on Answer and Summary, > and `stage` on Tagging, are written for a person reading the response. They do > not mark the end of the job. A successful tagging leaves `stage` at `"Done"`, > and only a failure sets `"Failed"`. New stage names can appear at any time. ## Is the job over? | `finished` | What it means | What to do | | --- | --- | --- | | `false` | The job is still running. | Poll again. | | `true` | The job is over. | Read `finish_reason`. | A `404` on an early poll is not a failure. A new id takes a moment to become queryable. Wait 2 to 4 seconds before your first poll. Treat a `404` in the first 10 seconds as "not ready yet". After that window, a `404` means Miso lost the job. Submit the original request again rather than giving up: the id came from your own submit, so it was valid when you got it. ## Did it succeed? | Value | Meaning | Retry | | --- | --- | --- | | `not_finished` | The job is still running. | Poll again. | | `success` | The result is complete. | Not needed. | | `error` | The pipeline failed. | Yes. Bounded retry, same payload. | | `forbidden` | Miso withheld the result. `blocked_reason` says why. | No. | `forbidden` is not a fault on your side or on Miso's. It is the rate limit, the query check, or metering turning the request down, and `blocked_reason` names which one. Show the reader the text in `answer`. Treat any value you do not know as a failure. ## What an empty result means `finish_reason` tells you how to read the result, so read it first. | `finish_reason` | Result | What it means | | --- | --- | --- | | `success` | Filled | The normal case. | | `success` | Empty | The job worked, and Miso found nothing to return. | | A failure value | Anything | The job failed. The result is absent or partial. | An empty result on `success` is complete. The same request returns the same thing, so there is nothing to gain from asking again. ## If the job never finishes If `finished` is still `false` after **3 minutes**, treat the job as lost and submit the original request again. Set your own limit above the slowest request you see in practice. A summary with `rules`, or one over a large article set, runs longer than a plain one. ## HTTP status | Status | Meaning | Retry | | --- | --- | --- | | `200` | The poll worked. Read `finished` and `finish_reason`. | — | | `401` | The API key is missing or wrong. | No. | | `404` | Not ready yet inside the grace window. A lost job after it. | Yes. Submit the request again. | | `422` | The request body is invalid. Read `detail`. | No. Fix the body. | | `429` | Over the rate limit. | Yes. Back off first. | | `500` | A fault on Miso's side. | Yes. Bounded retry. | See [Errors & Rate Limits](/api/errors) for the error body itself. ## A polling loop One function submits, polls, and submits again when the job is lost. It either returns the result or gives up. ```text Submit, poll, resubmit repeat 3 times: id = submit the request wait 3 seconds start = now loop: GET the poll endpoint 404, under 10 seconds wait 2 seconds, poll again # not ready yet 404, after that leave the loop, submit again # the job is gone 429 or 5xx wait, poll again # Miso is busy not finished, under 3 min wait 2 seconds, poll again not finished, over 3 min leave the loop, submit again finish_reason "success" return the result, even when empty finish_reason "error" leave the loop, submit again finish_reason "forbidden" give up, read blocked_reason give up ``` Only `forbidden` ends it on the spot. Everything else is worth another submit, bounded by the attempt count. Each version takes a `submit` callback and the poll URL. ```python Python def get_result(submit, poll_url, api_key, attempts=3): """Submit, poll, and submit again when the job is lost. Returns the finished `data`, or None when it is not worth asking again. """ session = requests.Session() session.headers["X-Api-Key"] = api_key for _ in range(attempts): job_id = submit() time.sleep(3) # a new id is not queryable at once start = time.monotonic() while True: response = session.get(poll_url(job_id), timeout=30) waited = time.monotonic() - start if response.status_code == 404: if waited < 10: time.sleep(2) # not ready yet, not lost continue break # the job is gone, submit it again if response.status_code == 429 or response.status_code >= 500: time.sleep(5) # Miso is busy continue data = response.json()["data"] if not data["finished"]: if waited > 180: break # lost, submit it again time.sleep(2) continue if data["finish_reason"] == "success": return data # accept it, even when empty if data["finish_reason"] == "error": break # a fault, submit it again return None # forbidden, read blocked_reason return None # out of attempts ``` ```javascript JavaScript // Submit, poll, and submit again when the job is lost. // Returns the finished `data`, or null when it is not worth asking again. async function getResult(submit, pollUrl, apiKey, attempts = 3) { const wait = (ms) => new Promise((r) => setTimeout(r, ms)); for (let attempt = 0; attempt < attempts; attempt++) { const jobId = await submit(); await wait(3000); // a new id is not queryable at once const start = Date.now(); let lost = false; while (!lost) { const response = await fetch(pollUrl(jobId), { headers: { "X-Api-Key": apiKey }, }); const waited = Date.now() - start; if (response.status === 404) { if (waited < 10_000) { // not ready yet await wait(2000); continue; } lost = true; continue; // the job is gone, submit it again } if (response.status === 429 || response.status >= 500) { await wait(5000); // Miso is busy continue; } const { data } = await response.json(); if (!data.finished) { if (waited > 180_000) { // submit again lost = true; continue; } await wait(2000); continue; } if (data.finish_reason === "success") { // even when empty return data; } if (data.finish_reason === "error") { lost = true; continue; } return null; // forbidden, read data.blocked_reason } } return null; // out of attempts } ``` ```bash Bash # Submit, poll, and submit again when the job is lost. # Prints the finished `data`. Exit 1 means it is not worth asking again. get_result() { # get_result local attempt job_id waited start status out=$(mktemp) for attempt in 1 2 3; do job_id=$($1) # your submit command prints the new id sleep 3 # a new id is not queryable at once start=$SECONDS while :; do status=$(curl -sS -o "$out" -w '%{http_code}' -H "X-Api-Key: $KEY" "$2/$job_id") waited=$(( SECONDS - start )) case $status in 404) (( waited < 10 )) && { sleep 2; continue; } # not ready yet break ;; # gone, submit again 429|5??) sleep 5; continue ;; # Miso is busy esac if [ "$(jq -r .data.finished "$out")" != true ]; then (( waited > 180 )) && break # lost, submit again sleep 2; continue fi case $(jq -r .data.finish_reason "$out") in success) jq .data "$out"; return 0 ;; # even when empty error) break ;; # submit again *) return 1 ;; # forbidden esac done done return 1 # out of attempts } ``` The grace window keeps an early `404` from ending the job. The stall guard keeps a lost job from hanging your worker. Backing off on a `429` keeps a busy minute from turning into a failed document. ## How long to wait between polls | API | Typical run | Poll every | | --- | --- | --- | | Answer | About 12 seconds | 1 to 2 seconds | | Summary | About 16 seconds for 3 bullets over 10 articles | 1 to 2 seconds | | Content Tagging | 30 to 50 seconds for one news article | 2 to 3 seconds | Answer and Summary fill the body as the model writes, so a short interval lets you render the text while it arrives. Tagging returns nothing until it is done, so a short interval only costs you requests. ## Get the result in one call Every one of these endpoints takes `?wait_for_answer=true` on the `POST`. The request then blocks and returns the finished result. Use it in a script or a test. In production, poll. The connection can time out after about 60 seconds, and the slowest requests run longer than that. ## Next - [Answer API](/api/genai/answer) — the fields an answer carries. - [Summary API](/api/genai/summary) — `rules`, and what they do to the result. - [Content Tagging](/api/genai/tagging) — the shape of a tag result. - [Errors & Rate Limits](/api/errors) — status codes across every endpoint. # Filter Syntax (fq) Filter what an endpoint can return, with worked counts. `fq` restricts which products an endpoint can consider. It runs before ranking, so it changes **what is eligible**, never the order of what is left. Below we build filters against one catalog, and show the count each one returns. The syntax is Lucene query syntax: `field:value`, ranges in brackets, and the boolean operators. The same rule works on every endpoint that takes `fq` — search, recommendation, hybrid search, summaries, and answers. > Every count on this page comes from the same catalog of 20,901 news > articles, so you can compare what each construct does. ## Match a field ```text field:value tags:Internet ``` The baseline query matches 2,359 articles. With that filter, 403. Use the field name exactly as you uploaded it. A custom attribute uses its dotted path: ```text a custom attribute custom_attributes.source:wikinews ``` ### Quote any value with a space An unquoted space ends the value, so the rest of it is read as more query: | Filter | Matches | | --- | --- | | `custom_attributes.license:"CC BY 2.5"` | 2,359 | | `custom_attributes.license:CC BY 2.5` | **0** | | `tags:"Science and technology"` | 1,807 | | `tags:Science and technology` | **0** | Neither form is an error. The unquoted one returns nothing, quietly. ### Values are case sensitive A tag or a category is matched exactly, as stored: | Filter | Matches | | --- | --- | | `tags:Computing` | 332 | | `tags:computing` | **4** | | `tags:COMPUTING` | **0** | The 4 in the middle row is the whole lesson. Those 4 articles carry the tag in lower case, and they are the only ones `tags:computing` can find. The other 332 are invisible to it. Text fields behave differently. `title` is analyzed, so `title:software` matches 25 articles whatever the case of the word in the headline. Keyword fields, such as `tags`, `categories` and custom attributes, need the exact value. ### Match anything in a field ```text the field is present custom_attributes.word_count:* ``` That matches all 2,359, because every record carries it. Use it to find records that have a field at all. A wildcard also works inside a value: ```text prefix tags:Comput* ``` 339 articles, against 332 for the exact tag. ## Match a range The bracket decides whether the bound itself is included. | Form | Bounds | Meaning | | --- | --- | --- | | `[100 TO 200]` | both included | 100 and 200 match | | `{100 TO 200}` | both excluded | 101 to 199 match | | `[100 TO 200}` | low included, high excluded | 100 matches, 200 does not | | `{100 TO 200]` | low excluded, high included | 100 does not match, 200 does | The catalog holds 7 articles of exactly 150 words and 9 of exactly 250. That is enough to see each bracket work: | Filter | Matches | | | --- | --- | --- | | `custom_attributes.word_count:[150 TO 250]` | 702 | | | `custom_attributes.word_count:{150 TO 250]` | 695 | 702 − 7 | | `custom_attributes.word_count:[150 TO 250}` | 693 | 702 − 9 | | `custom_attributes.word_count:{150 TO 250}` | 686 | 702 − 7 − 9 | Use `*` for an open end, and mix the brackets as you need: ```text open ends custom_attributes.word_count:[150 TO *] // 2,123, includes 150 custom_attributes.word_count:{150 TO *] // 2,116, excludes 150 ``` Comparison operators do the same job, and follow the same rule: | Operator | Same as | Matches | | --- | --- | --- | | `custom_attributes.word_count:>=150` | `[150 TO *]` | 2,123 | | `custom_attributes.word_count:>150` | `{150 TO *]` | 2,116 | Dates take the same brackets, in ISO-8601: ```text dates published_at:[2005-01-01T00:00:00Z TO 2005-12-31T23:59:59Z] // 332 published_at:[2020-01-01T00:00:00Z TO *] // 78 ``` ## Group with parentheses > **CAUTION: Put parentheses around every mix of `AND` and `OR`.** Without > them, the filter runs, returns a result, and quietly ignores part of your > condition. Lucene's boolean rule works like this: - `AND`, and a **plain space**, make a clause **required**. Miso sets the default operator to `AND`, so `tags:Internet tags:Computing` means both, and returns 164 articles rather than the 571 in either. - `OR` makes the clauses it joins **optional**. - **When a query holds any required clause, the optional ones stop restricting the result.** They only change the score, and a filter throws the score away. - When a query holds no required clause, at least one optional clause must match. Compare three filters. `A` is `tags:Internet` (403 articles), `B` is `tags:Computing` (332), and `C` is `custom_attributes.word_count:[300 TO *]` (1,147): | Filter | Matches | Why | | --- | --- | --- | | `A OR B AND C` | **132** | The `OR` makes `A` and `B` optional, then the `AND` makes `B` and `C` required. `A` stays optional, so it no longer restricts. | | `(A OR B) AND C` | 253 | The brackets make the pair one required clause. | | `A OR (B AND C)` | 465 | Two optional clauses, so either side can match. | `B AND C` on its own also returns 132, which is what the first row really ran. It reports no error. `NOT` follows the same rule: | Filter | Matches | Why | | --- | --- | --- | | `NOT A OR B` | **168** | No required clause, so `B` must match, and `A` must not. | | `NOT (A OR B)` | 1,788 | Neither tag. | | `(NOT A) OR B` | 2,120 | Not A, plus all of B. | The last figure checks out: 1,956 articles are not tagged Internet, 332 are tagged Computing, and 168 of those are in both sets. 1,956 + 332 − 168 = 2,120. ### Test one field against several values Brackets after a field name are shorter, and mean the same thing: ```text these are identical, 571 articles each tags:(Internet OR Computing) tags:Internet OR tags:Computing ``` Parentheses nest, so build the condition you mean and keep it explicit: ```text nested ((tags:Internet OR tags:Computing) AND custom_attributes.word_count:[300 TO *]) AND NOT custom_attributes.premium:"true" ``` ## What a filter cannot do - **It does not rank.** `fq` decides what is eligible. To lift results instead of removing them, use `boost_fq`, which takes the same syntax. - **It does not create fields.** A filter on a field you never uploaded matches nothing. `custom_attributes.nope:1` returns 0, not an error. - **It does not search text.** Use `q` for that, and `fq` to narrow it. ## Errors A filter that does not parse returns `422`, and the message names `fq`: ```json 422 { "detail": [ { "loc": ["body", "fq"], "msg": "Syntax error in input : unexpected end of expression (maybe due to unmatched parenthesis) at the end!", "type": "value_error.parsesyntax" } ] } ``` An empty `fq` is legal. It filters nothing. Two failures are silent, and both return `0` instead of an error: an unquoted value with a space, and a value with the wrong case. When a filter returns nothing, test those two first. ## Common filters ```text keep paid content out of free answers custom_attributes.premium:"false" ``` ```text this year only published_at:[2026-01-01T00:00:00Z TO *] ``` ```text one section, long reads only custom_attributes.section:markets AND custom_attributes.word_count:[800 TO *] ``` ```text everything except one tag NOT tags:Sponsored ``` ## Where to use it | Endpoint | What `fq` limits | | --- | --- | | `POST /v1/ask/questions` | The passages an answer can cite. | | `POST /v1/ask/search` | The results, and the passages behind the answer. | | `POST /v1/ask/summary` | The articles the summary reads. | | `POST /v1/search/search` | The search results. | | `POST /v1/recommendation/*` | The candidates for a unit. | See [Search & Recommendation](/api/search-rec/overview) and [Product Schema](/data/product-schema). # Answer API Ask a question, poll, and render the answer with its sources. The endpoint behind Answers. You send a question, Miso builds an answer from your catalog, and you poll for it. Below we ask one question and follow it through to the finished answer. Base URL `https://api.askmiso.com`. Authenticate with the `X-API-KEY` header, or `?api_key=`. See [Authentication](/api/authentication). ```mermaid %%{init: {'theme':'base','themeVariables':{ 'fontFamily':'IBM Plex Sans, ui-sans-serif, system-ui','fontSize':'14px', 'actorBkg':'#3148be','actorBorder':'#3148be','actorTextColor':'#ffffff', 'actorLineColor':'#9aa3c0','signalColor':'#9aa3c0','signalTextColor':'#6b7392', 'labelBoxBkgColor':'#f4effc','labelBoxBorderColor':'#cdbcf0', 'labelTextColor':'#40277a','noteBkgColor':'#e8ecfb','noteBorderColor':'#b9c2ea', 'noteTextColor':'#22307a','sequenceNumberColor':'#ffffff' }}}%% sequenceDiagram autonumber participant A as Your app participant M as Miso A->>M: POST /v1/ask/questions M-->>A: question_id, and nothing else Note over M: the answer does not exist yet loop every 1 to 2 seconds A->>M: GET /v1/ask/questions/{question_id}/answer M-->>A: finished false, answer_stage, the text so far Note over A: render the partial answer while you wait end A->>M: GET /v1/ask/questions/{question_id}/answer M-->>A: finished true, answer, sources, follow-ups Note over A,M: about 12 seconds end to end ``` ## Ask a question `POST /v1/ask/questions` | Field | Type | Notes | | --- | --- | --- | | `question` | string | **Required.** What the reader asked. | | `anonymous_id` | string | The visitor. Send the same value for the same person. | | `user_id` | string | The signed-in reader. Send this instead of `anonymous_id`. From the browser, prove it with a [JWT](/api/authentication#jwt-user-authentication). | | `user_type` | string | The tier, for [metering](/operate/metering). Without it, metering never runs. | | `parent_question_id` | UUID | The previous question, to continue a thread. | | `fq` | string | Restrict the passages the answer can use. See [Filter Syntax](/api/fq). | | `metadata` | object | Your own values, stored with the request and returned with the answer. | ```bash Ask curl -X POST "https://api.askmiso.com/v1/ask/questions" \ -H "X-Api-Key: YOUR_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "anonymous_id": "visitor-8f3a1c", "question": "What did Wikinews report about the Linux operating system?" }' ``` The response carries the id and nothing else. The answer does not exist yet: ```json 200 { "message": "success", "data": { "question_id": "08608817-f178-4898-95b6-5849667ac03b" } } ``` ## Poll for the answer `GET /v1/ask/questions/{question_id}/answer` Poll every 1 to 2 seconds until `finished` is `true`. The body grows as Miso works, so you can render the answer while it is written. ```bash Poll curl "https://api.askmiso.com/v1/ask/questions/$QUESTION_ID/answer" \ -H "X-Api-Key: YOUR_SECRET_KEY" ``` **Stop on `finished`. Never test `answer_stage`.** It is a sentence for a reader, and Miso translates it into the language of your app. A typical answer moves through these stages in about 12 seconds: ```text answer_stage, in order "" queued "Researching different sources" "Doing more research, this may take a little longer" "Generating summary" finished: true ``` ## What you get back ```json Answer lineNumbers { "message": "success", "data": { "finished": true, "finish_reason": "success", "blocked_reason": "none", "question": "What did Wikinews report about the Linux operating system?", "answer": "Red Hat announced in December 2020 that it would move focus away from CentOS Linux in favour of CentOS Stream [1][2]…", "sources": [ { "product_id": "wikinews-2911067", "title": "Red Hat to move focus away from CentOS in favour of Stream", "url": "https://en.wikinews.org/wiki/…", "date": "2020-12-14T00:00:00+00:00", "snippet": "Red Hat announced the end of CentOS Linux as a rebuild…", "highlight_text": "CentOS Stream", "boosted": false, "_attribution_length": 4845, "_attribution_length_percentage": 29.96 } ], "followup_questions": ["What is Rocky Linux, and who started it?"] } } ``` | Field | What it is | | --- | --- | | `answer` | The text, in Markdown, with `[1]` markers that point at `sources`. | | `sources` | The articles the answer cites, in citation order. | | `followup_questions` | Suggested next questions. Render them as links. | | `finish_reason` | `success` when the pipeline completed. | | `blocked_reason` | `metering` when a limit stopped the answer. `none` otherwise. | Every field is listed in [Answer Response Fields](/api/genai/answer-fields), which also explains the attribution percentages. ## A refusal is not an error When Miso finds nothing relevant, it returns `200`, `finish_reason: "success"`, an empty `sources`, and text that says so: > Unfortunately, I couldn't find relevant information in my knowledge base to > answer that question. Check the catalog before you check your code. The usual causes are an upload that has not finished, or a question outside your content. ## Follow-up questions Send `parent_question_id` to continue a thread. Miso reads the earlier turns, so the reader can write "and after that?" without repeating the subject. Threads are stored, and a reader can return to them later. See [User History](/api/genai/user-history). ## Next - [Answer Response Fields](/api/genai/answer-fields) — every field in the answer. - [Source Attribution](/api/genai/source-attribution) — what the percentage on each source measures. - [Filter Syntax (fq)](/api/fq) — restrict what an answer can cite. - [Metering & Entitlements](/operate/metering) — limit answers per reader. - [Ask — Quick Start](/sdk/ask/quick-start) — the SDK that does all of this for you. # Answer Response Fields Every field an answer carries, and what to render. The fields returned by `GET /v1/ask/questions/{question_id}/answer`, and inside the Hybrid Search response. | Field | Type | What it is | | --- | --- | --- | | `question` | string | The question as asked. | | `question_id` | UUID | Stable id for this question/answer. | | `parent_question_id` | UUID? | Set for follow-up questions in a thread. | | `answer` | string | The generated answer (Markdown/HTML per request). | | `answer_stage` | string | The progress message. Read it with `finished` to stream. | | `finished` | boolean | Whether the answer is complete. | | `finish_reason` | enum | Why generation stopped. Read it with `finished`. See below. | | `blocked_reason` | enum | Set when an answer was withheld (safety/no-source). | | `sources` | object[] | Cited source documents shown to the user. | | `sources_in_prompt` | object[]? | Sources actually fed to the model. | | `related_resources` | object[] | Additional suggested content. | | `followup_questions` | string[]? | **Suggested follow-up questions** to render under the answer. | | `reasoning` | string? | The model's reasoning trace — the **"thought box"**. | | `short_reasoning` | string[]? | Condensed reasoning steps. | | `reasoning_finished` | boolean? | Whether the reasoning trace is complete. | | `images` | object[]? | Image results. | | `affiliation_products` | object[]? | Affiliate products. | | `created_at` | datetime | When the question was asked. | | `metadata` | object | Extra data for the answer. Holds `miso_generated_by: "answer_update_monitor"` when the answer is a generated [Answer Update](/api/genai/user-history). Also carries any `metadata` you sent with the question. | ### Example response ```json Response lineNumbers { "data": { "question_id": "0e1f2a3b-4c5d-6e7f-8a9b-0c1d2e3f4a5b", "question": "How do interest rate cuts affect mortgages?", "finished": true, "finish_reason": "success", "answer": "Lower rates make mortgages cheaper. [1]", "sources": [ { "product_id": "rates-and-mortgages", "title": "What rate cuts mean for your mortgage", "url": "https://example.com/money/mortgages" } ], "related_resources": [ { "product_id": "fixed-vs-variable", "title": "Fixed vs variable: which is right for you?" } ], "followup_questions": [ "When is the next central-bank meeting?", "Should I fix my mortgage now?" ], "short_reasoning": [ "Found the rates-and-mortgages explainer", "Extracted the impact on repayments" ], "created_at": "2026-06-12T10:15:03Z" } } ``` ### Reading `finished` and `finish_reason` `finished` says the job is over. `finish_reason` says whether it worked. **Do not branch on `answer_stage`.** It is a progress label for the reader, and it does not mark the end of generation. `finished` does. `finish_reason` is one of `not_finished`, `success`, `error` or `forbidden`. `forbidden` is not a fault: it is the rate limit, the query check, or metering turning the answer down, and `blocked_reason` names which one. Show the reader the message in `answer`. See [Async results and polling](/api/async-results) for the retry rules, the grace window, the stall guard, the status codes, and a polling loop. ## Building the answer UI - **Reasoning trace.** `reasoning` and `short_reasoning` show how the engine reached the answer. To hide that panel, do not render them. - **Suggested follow-ups.** These come from `followup_questions`. Render each one as a button that asks the question. - **Citations.** Render `sources` as the citations. `related_resources` are softer "see also" links. - **No-answer states.** Read `blocked_reason` and `finish_reason` to show the right empty state. ## Answer feedback Send a thumbs-up or thumbs-down through the Interaction API. The feedback record holds these fields: | Field | Type | Notes | | --- | --- | --- | | `question_id` | string | The answer being rated. | | `result_type` | string | What was rated, e.g. `"answer"`. | | `value` | enum | One of **`helpful`**, **`not helpful`**, or **`unselected`** (cleared). | *** ## Source attribution Every source carries `_attribution_length` and `_attribution_length_percentage`. What they measure, and what they do not, is its own topic: see [Source Attribution](/api/genai/source-attribution). # Source Attribution What the percentage on a source counts, and what it does not. Every source in an answer carries a percentage. Below we show what it counts, and why a high number does not mean a source mattered more. | Field | What it is | | --- | --- | | `_attribution_length` | The length, in characters, of the passage Miso sent to the model for this source. | | `_attribution_length_percentage` | That length as a share of every **cited** passage. Two decimal places. | Together they answer one question: **of all the material behind this answer, how much came from this source?** For the rest of the answer payload, see [Answer Response Fields](/api/genai/answer-fields). Every entry in `sources` carries two extra fields: | Field | What it is | | --- | --- | | `_attribution_length` | The length, in characters, of the passage Miso sent to the model for this source. | | `_attribution_length_percentage` | That length as a share of every **cited** passage. Two decimal places. | Together they answer one question: **of all the material behind this answer, how much came from this source?** ```mermaid %%{init: {'theme':'base','themeVariables':{ 'fontFamily':'IBM Plex Sans, ui-sans-serif, system-ui','fontSize':'14px', 'lineColor':'#9aa3c0','clusterBkg':'transparent','clusterBorder':'#d3d8e8', 'titleColor':'#8b93ad' },'flowchart':{'curve':'basis','nodeSpacing':20,'rankSpacing':60,'padding':12}}}%% flowchart LR Q["`**The question**`"] S["`Search your catalog`"] C10["`10 candidates sent to the model`"] C3["`**3 cited** they become sources`"] C7["`7 not cited ignored`"] PCT["`Percentages over the cited 3 only`"] Q --> S --> C10 C10 --> C3 --> PCT C10 --> C7 classDef q fill:#f6f7fa,stroke:#c9cfe0,color:#454c69 classDef work fill:#e8ecfb,stroke:#b9c2ea,color:#22307a classDef cited fill:#f4effc,stroke:#cdbcf0,color:#40277a classDef drop fill:#f6f7fa,stroke:#d8d8e2,color:#8b93ad class Q q class S,C10 work class C3,PCT cited class C7 drop ``` ## How an answer is built Miso does not answer from memory. It reads your content first, in three steps: 1. **Search.** Miso finds the passages that relate to the question. 2. **Send.** Miso sends the best passages to the model. Each one is a candidate. 3. **Cite.** The model writes the answer, and cites the candidates it used. A candidate the model cites becomes a **source**. The others are dropped. ## Sent is not the same as cited This distinction controls the whole calculation. | Stage | Counted? | | --- | --- | | Passages the search found | No | | Passages Miso sent to the model | No, not on their own | | **Passages the model cited** | **Yes** | Send 10 candidates, and the model cites 3. Those 3 become sources, their percentages add up to 100, and the other 7 add nothing. ## The calculation 1. Take the cited sources. Ignore every other candidate. 2. For each one, measure the passage Miso sent to the model. 3. Add the lengths together. 4. Divide each length by the total, then multiply by 100. See the worked example below for a real one. ## A worked example The example below uses the [Wikinews example](/start/example-news-site) catalogue. The question: > What did Wikinews report about the Linux operating system? Miso answered from three articles: > Wikinews reported extensively on the major shift in the CentOS ecosystem > following Red Hat's December 2020 announcement to move focus away from CentOS > Linux in favor of CentOS Stream… The `sources` array beside it, trimmed to the fields that matter here: ```json sources [ { "product_id": "wikinews-2911293", "title": "Gregory Kurtzer discusses plans for Rocky Linux with Wikinews", "date": "2020-12-18T00:00:00+00:00", "_attribution_length": 9588, "_attribution_length_percentage": 59.28 }, { "product_id": "wikinews-2911067", "title": "Red Hat to move focus away from CentOS in favour of Stream", "date": "2020-12-14T00:00:00+00:00", "_attribution_length": 4845, "_attribution_length_percentage": 29.96 }, { "product_id": "wikinews-2911401", "title": "Wikinews 2020: An 'Original reporting' year in review", "date": "2021-01-01T00:00:00+00:00", "_attribution_length": 1741, "_attribution_length_percentage": 10.76 } ] ``` Check it yourself. The three passages add up to 9588 + 4845 + 1741 = **16,174** characters, and each percentage is that source's share: | Source | Sent | Share | Percentage | | --- | --- | --- | --- | | Rocky Linux interview | 9,588 | 9588 ÷ 16174 | **59.28%** | | Red Hat moves away from CentOS | 4,845 | 4845 ÷ 16174 | **29.96%** | | Year in review | 1,741 | 1741 ÷ 16174 | **10.76%** | | **Total** | **16,174** | | **100%** | Rounding to two decimal places means the total can read `100.01` or `99.99` on another answer. Do not test for exactly 100. Note what the numbers do **not** say. The interview scored 59.28% because it is a long interview, not because it settled the question. The year-in-review article scored 10.76% because Miso sent a short passage from it. The percentage follows the length of the passage, not how much of it the model used. ## Which text is measured Three lengths exist for one source. Miso measures the middle one: | Text | Measured? | | --- | --- | | The full article on your site | No | | **The passage sent to the model** | **Yes** | | The short extract shown on screen | No | Miso removes the layout markup before it measures. ## How to read it The percentage measures **how much material a source supplied**. The model can read a long passage and take one fact from it. Three consequences follow: - **Length shapes the number.** A longer passage scores higher than a short one. - **A short source can carry the key fact.** Its percentage stays small, because the percentage follows the length of the passage. - **The number of citations does not change it.** One citation or five, the passage length is the same. Take a reader who asks for the date of a court decision: | Source | What it supplied | Sent | Percentage | | --- | --- | --- | --- | | A background feature | Context the answer mentions in passing | 8,000 characters | 88.89% | | A court notice | The date itself, which is the answer | 1,000 characters | 11.11% | Both figures are correct. They describe volume. The feature supplied most of the material, and the notice supplied the decisive fact. Read the percentage with the answer text and the citation markers to see how each source was used. ## In short | Question | Answer | | --- | --- | | What does it measure? | The passage sent to the model, as a share of all cited passages. | | Which sources count? | Only the ones the model cited. | | Are uncited candidates counted? | No. They are ignored, even though the model received them. | | What is the unit? | Percent of characters, to two decimal places. | | Does it measure importance? | No. It measures supplied material. | | Is it a quality score? | No. | # Explore Questions Suggest the questions your readers have not thought of yet. Explore generates the questions your readers see before they think of their own: **related questions** under an article, and **trending questions** on a homepage or a section front. Both endpoints return a list of strings. You render each one as a link into your answers page. The questions come from your own catalog, so each one leads to an answer your content supports. Below we call both endpoints and render what comes back. Base URL `https://api.askmiso.com`. Authenticate with the `X-API-KEY` header, or `?api_key=`. See [Authentication](/api/authentication). ## Which one do I want? | Where the reader is | Endpoint | Anchored to | | --- | --- | --- | | An article page | `POST /v1/ask/related_questions` | The article you name | | A homepage, a section front, a search page | `POST /v1/ask/trending_questions` | The whole app, or one brand | Neither endpoint generates an answer, so both return fast enough to call while the page renders. Send the question the reader picks to [the Answer API](/api/genai/answer). ## Related questions `POST /v1/ask/related_questions` | Field | Type | Default | Notes | | --- | --- | --- | --- | | `product_id` | string | *required* | The article to generate questions for. | | `rows` | integer | `5` | How many questions to return. | | `version` | string | — | Pin a related-questions model version. | | `fq` | string | — | Restrict the candidates. See [Filter Syntax (fq)](/api/fq). | ```bash Request curl -X POST "https://api.askmiso.com/v1/ask/related_questions" \ -H "X-Api-Key: YOUR_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "product_id": "wikinews-2911067", "rows": 5 }' ``` ```json Response { "message": "success", "data": { "related_questions": [ "Why did Red Hat shift its investment to CentOS Stream?", "What is the difference between CentOS Stream and CentOS Linux?" ], "version": 8, "miso_id": "d02603ab-d544-42b4-8b6c-696c5c4dc5c5" } } ``` | Field | What it is | | --- | --- | | `related_questions` | The questions, ready to render. | | `version` | The model version that produced them. `null` when Miso has none for that article. | | `miso_id` | The request id. Send it back on an interaction to attribute the click. | `product_id` is required. Without it the call returns `422 {"message": "product_id is required"}`. ## Trending questions `POST /v1/ask/trending_questions` | Field | Type | Default | Notes | | --- | --- | --- | --- | | `rows` | integer | `10` | How many questions to return. | | `_meta.site` | string | — | Limit to one site or brand, for a multi-brand app. | ```bash Request curl -X POST "https://api.askmiso.com/v1/ask/trending_questions" \ -H "X-Api-Key: YOUR_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "rows": 10, "_meta": { "site": "markets" } }' ``` ```json Response { "message": "success", "data": { "related_questions": [ "What did Red Hat change about CentOS?", "Which Linux distributions replaced CentOS?" ], "_ver": "v2", "miso_id": "c1fb45f7-2c5f-4fc8-82f7-0ae63d05b0c0" } } ``` > **The key is `related_questions` here too.** Trending questions come back > under the same name as the article-level ones. Read `data.related_questions` > for both endpoints, and keep one render function for the two. ## An empty list is a normal answer Both endpoints return `200` with an empty `related_questions` when Miso has nothing to offer: ```json 200 — nothing available { "message": "success", "data": { "related_questions": [], "version": null, "miso_id": "f1bc004b-b349-432f-bf7a-c79de9a511cd" } } ``` Three things produce it, and none of them is an error: - **The article is new.** Miso has not generated questions for it yet. - **The id is unknown.** A `product_id` that no record carries returns an empty list and a `null` version, not a `404`. - **The app has no model yet.** A new app returns an empty list until Miso trains one. So render the block only when the list has entries. A heading above an empty rail is the most common bug on this endpoint. ## Report what the reader picked Send an interaction when a reader opens one of the questions, and pass the `miso_id` from the response. Miso then learns which questions earn clicks: ```bash Report a click curl -X POST "https://api.askmiso.com/v1/interactions" \ -H "X-Api-Key: YOUR_PUBLISHABLE_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": [ { "type": "click", "user_id": "u-10293", "miso_id": "d02603ab-d544-42b4-8b6c-696c5c4dc5c5", "timestamp": "2026-08-04T10:15:00Z" } ] }' ``` ## Next - [Explore SDK workflow](/sdk/explore/quick-start) — calls both endpoints and renders the questions for you. Use the API directly when you build your own front end. - [Answer API](/api/genai/answer) — ask the question the reader picked. - [Filter Syntax (fq)](/api/fq) — restrict which articles the questions cover. # Hybrid Search API Keyword results and an AI answer, from one call. One call returns keyword results **and** starts an AI answer over the same catalog. It is the endpoint behind the [Hybrid Search SDK workflow](/sdk/hybrid-search/quick-start). Below we run one search, then narrow it with facets and filters. **This is the search to use for content.** Articles, video and documents bring readers who ask in sentences and want an answer, not only a list. For a product catalog, where traffic is heavy and every query must render at once, use the [Search API](/api/search-rec/overview) instead. Base URL `https://api.askmiso.com`. Authenticate with the `X-API-KEY` header, or `?api_key=`. See [Authentication](/api/authentication). ## Search (+ answer) `POST /v1/ask/search` | Field | Type | Default | Notes | | --- | --- | --- | --- | | `q` | string | *required* | The user's query. | | `answer` | boolean \| `"AUTO"` | `true` | Run the answer pipeline. `"AUTO"` decides per query. | | `rows` | integer | `10` | Number of search results. | | `start` | integer | `0` | Result offset. | | `fl` | string[] | `["title"]` | Product fields to return (any uploaded field, incl. `custom_attributes`). | | `source_fl` | string[] | `["title"]` | Fields returned for answer sources. | | `stemming` | boolean | `true` | Reduce query words to their root form. | | `facets` | (string \| object)[] | `[]` | Fields to count, such as `tags`. Returned in `facet_counts`. See below. | | `order_by` | string \| object[] | `relevance` | `relevance`, `published_at` (newest first), `-published_at` (oldest first), or your own fields. See below. | | `fq` | string | — | Filter, for example `tags:Computing`. See [Filter Syntax (fq)](/api/fq). | | `user_id` / `anonymous_id` | string | — | For personalization. | ```bash Request curl -X POST "https://api.askmiso.com/v1/ask/search" \ -H "X-Api-Key: YOUR_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "q": "interest rate cuts 2026", "answer": "AUTO", "rows": 5, "fl": ["title", "url", "cover_image"], "fq": "section:\"markets\"" }' ``` ```json Response lineNumbers { "message": "success", "data": { "took": 731, "total": 3, "question_id": "064bda22-1e30-4411-b735-9370a8e48aa4", "miso_id": "85d792d9-50a2-43dc-9…", "products": [ { "product_id": "wikinews-2911293", "title": "Gregory Kurtzer discusses plans for Rocky Linux with Wikinews…", "url": "https://en.wikinews.org/wiki/Gregory_Kurtzer_discusses_plans…" } ], "facet_counts": { "facet_fields": { "tags": [["Computing", 2], ["FLOSS", 2]] } }, "parsed_query": null, "suggestion": null } } ``` **The answer is not in this response.** You get `question_id`, and you poll the same endpoint the Ask workflow uses: ```text Two steps POST /v1/ask/search -> products now, plus question_id GET /v1/ask/questions/{question_id}/answer -> the answer, when finished ``` The search returns in about **2 seconds**, and the answer follows about **5 seconds** later with 7 sources. Render the results first, then fill the answer in when it arrives. | Field | What it is | | --- | --- | | `took` | Search time in milliseconds. | | `total` | Matching products, before `rows` is applied. | | `products` | The results. `fl` decides which fields each one carries. | | `question_id` | Poll this for the answer. | | `facet_counts.facet_fields` | Counts per value, for each field in `facets`. | | `miso_id` | The request id. Send it back on an interaction to attribute the click. | | `parsed_query`, `suggestion` | Query understanding and a spelling suggestion. `null` when there is nothing to report. | *** ```mermaid %%{init: {'theme':'base','themeVariables':{ 'fontFamily':'IBM Plex Sans, ui-sans-serif, system-ui','fontSize':'14px', 'actorBkg':'#3148be','actorBorder':'#3148be','actorTextColor':'#ffffff', 'actorLineColor':'#9aa3c0','signalColor':'#9aa3c0','signalTextColor':'#6b7392', 'labelBoxBkgColor':'#f4effc','labelBoxBorderColor':'#cdbcf0', 'labelTextColor':'#40277a','noteBkgColor':'#e8ecfb','noteBorderColor':'#b9c2ea', 'noteTextColor':'#22307a','sequenceNumberColor':'#ffffff' }}}%% sequenceDiagram autonumber participant A as Your page participant M as Miso A->>M: POST /v1/ask/search (q, answer true) M-->>A: products, facets, and a question_id Note over A: render the results now, about 2 seconds loop until finished A->>M: GET /v1/ask/questions/{question_id}/answer M-->>A: the answer so far end Note over A,M: the answer finished about 5 seconds later A-->>A: fill the answer in above the results ``` The search and the answer come back separately. Render the results as soon as they arrive, and let the answer appear when it is ready. ## How Miso reads the query `q` is a search query, and these operators work on it. The counts below come from a catalog of 20,901 news articles. | You write | You get | Matched | | --- | --- | --- | | `linux kernel` | Both words. Miso joins bare words with **AND**. | 8 | | `"linux kernel"` | The exact phrase, in that order. | 5 | | `linux AND kernel` | The same as the first row. | 8 | | `software OR hardware` | Either word. | 438 | | `kernel NOT linux` | The first word, without the second. | 8 | | `comput*` | Any word that starts with `comput`. | 958 | Three details: - **A bare space means AND.** `linux kernel` and `linux AND kernel` both return 8. A reader who types more words gets fewer results, not more. - **`NOT` subtracts.** `kernel` alone matches 16 articles, 8 of which also say `linux`, so `kernel NOT linux` leaves 8. - **Quotes narrow.** `"open source"` returns 100, the loose form 317. ### How Miso repairs a query A broken quote never fails the search. Miso normalizes the query before it runs: | Input | What Miso does | | --- | --- | | `“linux kernel”` | Curly quotes become straight ones. It matched the same 5 articles as the straight form. | | `"linux kernel` | An odd number of quotes: the unmatched one is removed. It matched 8, the same as no quotes. | | `AT&T`, `m&a`, `west-bank` | A word joined by `&`, `-` or `@` is quoted for you, so it survives as one term. | | CJK text | Miso adds the phrase boundaries, because the words carry no spaces. | A malformed query therefore returns results rather than an error. *** ## Order the results `order_by` takes a shorthand string, or a list of objects for your own fields. The default is `relevance`. | Value | Order | | --- | --- | | `relevance` | Best match first. The default. | | `published_at` | **Newest first.** | | `-published_at` | **Oldest first.** | > **The minus sign does not mean descending here.** `published_at` is already > newest first, and `-published_at` reverses it to oldest first. It reads > backwards, so check it against your own data before you ship a sort control. Against a catalog of 20,901 news articles: ```text order_by: published_at 2023-05-01 Microsoft, Nware sign 10-year cloud gaming deal 2023-03-09 Netherlands set to further restrict semiconductor technology exports 2021-07-05 Ransomware attack hits over 200 US companies ``` ```text order_by: -published_at 2004-11-15 Big Linux Beta 3 released 2004-11-16 Longhorn for 2006, according to Gates 2004-11-29 Lycos launches screensaver to increase spammers' bills ``` **A record with no `published_at` sorts by `updated_at`.** It is not pushed to the end. In the run above, three undated articles appeared in the middle of the list, each in the position its `updated_at` earned. ### Sort on your own fields Send a list instead of a string. Each entry names a field, and Miso applies them in order: ```json order_by { "q": "technology", "order_by": [ { "field": "custom_attributes.word_count" }, { "field": "_search_score" } ] } ``` | Key | What it does | | --- | --- | | `field` | Any numeric or boolean field in your catalog, or `_search_score`, or `published_at`. | | `default_value` | The value to use when a record does not have that field. Default `0.0`. | | `tie_breaker` | What to sort on when two records tie. | ## Facet the results `facets` returns counts per value, for the products that match the query. Use them to build filters. The short form is a list of field names: ```json Request { "q": "technology", "facets": ["tags"] } ``` ```json Response { "facet_counts": { "facet_fields": { "tags": [ ["Science and technology", 1807], ["United States", 1010], ["North America", 903], ["Europe", 484] ] } } } ``` Each entry is `[value, count]`, sorted by count, largest first. The default is the **10** most common values. ### Control the facet The long form is an object: | Key | What it does | | --- | --- | | `field` | The field to count. A custom attribute uses its dotted path. | | `size` | How many values to return. Default `10`. | | `alias` | The key to use in the response. Needed when you facet one field twice. | | `include` | A regular expression. Keep only values that match. | | `exclude` | A regular expression. Drop values that match. | | `ranges` | Buckets for a numeric or date field, each with a `key`. | ```json size and alias { "facets": [ { "field": "tags", "alias": "topics", "size": 3 } ] } ``` ```json Response { "facet_counts": { "facet_fields": { "topics": [ ["Science and technology", 1807], ["United States", 1010], ["North America", 903] ] } } } ``` The alias replaces the field name as the key, so two facets on one field do not collide. `include` and `exclude` are **case sensitive**, and they match anywhere in the value unless you anchor them: ```json include { "facets": [ { "field": "tags", "size": 5, "include": "Comp.*" } ] } ``` That returns `Computing` (332), `Computron (Wikinewsie)` (6), `Computer Fraud and Abuse Act` (3), and `Computron (WWC2013)` (2). Neither option changes the search results, only the facet values. ### Filter by a facet A count next to an option is there so a reader can judge the click before they make it. "Computing 48" is worth a click. "Computing 2" is not. That sets a rule for what happens after the click. Every shop with a filter rail in the sidebar behaves the same way, and readers arrive expecting it: 1. The results narrow to the value they picked. 2. **Every other group updates.** Its counts now describe what is still reachable, so a dead end is visible before they hit it. 3. **The group they picked from does not count its own filter.** The other options in it stay judgeable, and the reader can switch or go back. Point 3 is the one that is easy to get wrong. A group that counts its own filter collapses its other options to the overlap with the current choice, and a reader loses both the comparison and the way back. Miso does this for you. Send the selection in `facet_filters`, keyed by the field the facet reads: ```json A reader picks Computing { "q": "linux", "facets": [ { "field": "tags", "size": 4 }, { "field": "custom_attributes.word_count", "ranges": [{ "to": 200, "key": "short" }, { "from": 200, "to": 600, "key": "medium" }, { "from": 600, "key": "long" }] } ], "facet_filters": { "tags": { "terms": ["Computing"] } } } ``` The rule is one line. **Each group counts with every filter applied except its own.** Two groups over the same catalog of 78 articles, one on `tags` and one on `custom_attributes.word_count`: | Ticked | Topic counts | Length counts | Results | | --- | --- | --- | --- | | Nothing | 48, 46, 46, 43 | 42, 22, 14 | 78 | | Topic `Computing` | 48, 46, 46, 43 | 27, 12, 9 | 48 | | Length `long` | 9, 8, 6, 5 | 42, 22, 14 | 14 | | Both | 9, 8, 6, 5 | 27, 12, 9 | 9 | The last row is the rule at work. Topic reads 9, 8, 6, 5, which is the `long` row, because Topic applies Length and skips itself. Length reads 27, 12, 9, which is the `Computing` row, for the same reason in reverse. That is what makes the panel usable. With both ticked, the results are 9, and Topic still offers `FLOSS` at 8. The reader can see the size of the swap before they make it. Neither request names a facet to leave alone. The key on the filter does that. ![A filter panel beside a result list. topic=Computing is ticked. Topic is labelled "you filtered here" and holds 48, 46, 46 and 43. Length is labelled "counts updated" and falls to 27, 12 and 9.](/images/facet-panel-topic.png) ![The same panel with length=long ticked instead. The two labels have swapped. Length holds 42, 22 and 14, and Topic falls to 9, 8, 6 and 5.](/images/facet-panel-length.png) ![Both ticked. Each group is labelled "you filtered here", and each one counts the other group's filter only. Topic reads 9, 8, 6 and 5 against length=long. Length reads 27, 12 and 9 against topic=Computing. The result list is 9 articles.](/images/facet-panel-both.png) #### Several values at once Put more than one value in `terms` and they widen the group. Add a second group and the two narrow together: | Selection | Results | | --- | --- | | `Computing` | 48 | | `FLOSS` | 46 | | `Computing` and `FLOSS`, one group | 59 | | `Computing`, plus `long` in Length | 9 | Values inside one group are an `OR`, because a reader ticking a second box wants more results. Separate groups are an `AND`, because each one is a different question about the same article. #### Keep `fq` for your own rules `fq` narrows everything, including the group the reader is working in. Once `Computing` pulls the other topics down to their overlap with it, the panel can no longer show the size of a switch to `FLOSS`. Keep `fq` for the rules your product enforces, such as hiding paid content from a signed-out visitor. See [Filter Syntax (fq)](/api/fq). ### Range facets Group a numeric or date field into buckets you name: ```json Request { "facets": [ { "field": "custom_attributes.word_count", "ranges": [ { "to": 200, "key": "short" }, { "from": 200, "to": 600, "key": "medium" }, { "from": 600, "key": "long" } ] } ] } ``` ```json Response { "facet_counts": { "facet_fields": { "custom_attributes.word_count": [["medium", 1495], ["long", 538], ["short", 535]] } } } ``` `from` is inclusive, `to` is exclusive, and each bucket needs at least one of them. The response uses your `key`, and still sorts by count. # Summary API Turn a set of your articles into a brief you specify. The Summary API writes a summary from a **set of your articles**. You choose the articles with a filter. You tell Miso what to write with your own instructions. Below we write one, then shape it with rules. Although the name says "summary", the API can generate many kinds of content from your articles: - A newsletter or a daily brief. - A summary of a search result page. - A topic or company roundup page. - Key takeaways for a single article. - Structured JSON for your own front end. The API is asynchronous. You submit a request, then you poll for the result. --- ## How article selection works You do **not** send the article text. Miso reads the articles from your own catalog, the same index the Answer API uses. You select them with `fq`, a filter query. ```text Filter examples published_at:[now-7d TO *] the last 7 days section:"markets" one section product_id:("id-1" OR "id-2") specific articles brand:"Architects Journal" AND type:"news" combined ``` If you need to include text that is **not** in your catalog, pass it as a [virtual article](#adding-your-own-text). > If no article matches your `fq`, Miso returns `404` and creates nothing. --- ## Authentication Every request needs your **API key**. Pass it as `?api_key=YOUR_KEY` or in the `X-Api-Key` header. Base URL: `https://api.askmiso.com`. --- ## Write a summary ### 1. Submit the request `POST /v1/ask/summary` You must supply **at least one** of `instructions`, `template`, or `task_id`. Most integrations use `instructions`. ```bash cURL curl -X POST "https://api.askmiso.com/v1/ask/summary" \ -H "X-Api-Key: $KEY" \ -H "Content-Type: application/json" \ -d '{ "instructions": "Summarize the latest news in 3 bullet points.", "fq": "published_at:[now-7d TO *]", "max_articles": 10 }' ``` ```javascript JavaScript const res = await fetch("https://api.askmiso.com/v1/ask/summary", { method: "POST", headers: { "X-Api-Key": KEY, "Content-Type": "application/json", }, body: JSON.stringify({ instructions: "Summarize the latest news in 3 bullet points.", fq: "published_at:[now-7d TO *]", max_articles: 10 }), }); const data = (await res.json()).data; ``` ```python Python import requests res = requests.post( "https://api.askmiso.com/v1/ask/summary", headers={"X-Api-Key": KEY}, json={ "instructions": "Summarize the latest news in 3 bullet points.", "fq": "published_at:[now-7d TO *]", "max_articles": 10 }, ) data = res.json()["data"] ``` ```json Response { "message": "success", "data": { "question_id": "0e1f2a3b-4c5d-6e7f-8a9b-0c1d2e3f4a5b", "pipeline_version": "v2" } } ``` ### 2. Poll for the summary `GET /v1/ask/questions/{question_id}/answer` Poll until `finished` is `true`. ```bash cURL curl "https://api.askmiso.com/v1/ask/summaries/$QUESTION_ID/summary" \ -H "X-Api-Key: $KEY" ``` ```javascript JavaScript const res = await fetch( "https://api.askmiso.com/v1/ask/summaries/$QUESTION_ID/summary", { headers: { "X-Api-Key": KEY } } ); const data = (await res.json()).data; ``` ```python Python import requests res = requests.get( "https://api.askmiso.com/v1/ask/summaries/$QUESTION_ID/summary", headers={"X-Api-Key": KEY}, ) data = res.json()["data"] ``` ```json Response { "message": "success", "data": { "question_id": "0e1f2a3b-4c5d-6e7f-8a9b-0c1d2e3f4a5b", "finished": true, "finish_reason": "success", "answer": "- Rates are expected to fall twice this year. [1]", "sources": [ { "product_id": "art-20260612-rates", "title": "Central bank signals 2026 cuts", "url": "https://example.com/markets/rates" } ] } } ``` > **Wait 2–4 seconds before your first poll.** A brand-new request is not > queryable immediately, and an early poll returns `404`. ### Get the result in one call Add `?wait_for_answer=true` to the POST. The request then blocks and returns the finished summary. Use this only for short summaries. The connection can time out after about 60 seconds, and a summary with `rules` or a large article set often takes longer. **For production, use polling.** --- ### What the flow looks like A topic summary filtered with `fq`: ```json Request { "anonymous_id": "doc-test", "instructions": "Summarize the news about the Linux operating system in 3 bullets.", "fq": "tags:Computing", "max_articles": 10 } ``` `POST` returns only a question id. Poll `GET /v1/ask/summaries/{question_id}/summary` until `finished` is `true`: ```text answer_stage, in order "Initializing" "Generating summary" finished: true ``` That request finishes in about **10 seconds** and returns 3 sources. The body is the same shape as an answer, so `answer`, `sources`, `followup_questions`, `finish_reason` and `blocked_reason` all behave as they do on [Answer response fields](/api/genai/answer-fields). Miso writes the citation as a markdown link inside the summary text, so render the text as markdown. ## Request fields ### Selecting the articles | Field | Type | Default | Notes | | --- | --- | --- | --- | | `fq` | string | — | Filter query that selects the articles. | | `max_articles` | integer | `20` | Articles to retrieve (`1`–`200`). | | `fl` | string[] | `[]` | Extra fields to return for each source. | | `relevance_instruction` | string | — | Drop articles that do not match this description. Adds cost and time. | > Miso retrieves up to `max_articles`, but sends only the **first 25** to the > model. A larger `max_articles` widens the pool for filtering. It does not make > the summary longer. ### Telling Miso what to write | Field | Type | Default | Notes | | --- | --- | --- | --- | | `instructions` | string | — | Your prompt. The main control. | | `rules` | string[] | `[]` | Conditions the output must meet. Miso checks the summary and rewrites it up to 3 times. | | `format` | string | `markdown` | `markdown`, `html`, or `json`. | | `enable_citations` | boolean | `true` | Set `false` to remove citation links from the text. | | `url_template` | string | `""` | Rewrite every link, for click tracking. | | `template` | string | — | A ready-made prompt: `newsletter_v1` or `newsvault`. | | `template_parameters` | object | `{}` | Parameters for that template. | --- ## Response fields | Field | What it is | | --- | --- | | `answer` | The summary, in the format you asked for. | | `finished` | `true` when generation is complete. Poll on this. | | `finish_reason` | `not_finished`, `success`, `error`, or `forbidden`. Read it once `finished` is `true`. | | `sources` | The articles the summary cites, in citation order. | | `sources_in_prompt` | The articles that were sent to the model. | | `question_id` | The id you poll with. | | `metadata` | Holds `rule_check_results` when you use `rules`. | Citations appear in the text as markdown links to the article URL. The `sources` array lists those articles in the order they are first cited. ## Read the result The Summary API is asynchronous. `finished` says the job is over, and `finish_reason` says whether it worked. Do not branch on `answer_stage`, which is a progress label only. See [Async results and polling](/api/async-results) for the value list, the grace window, the stall guard, the status codes, and a polling loop. **An `fq` that matches no article fails at the `POST`.** Miso returns `404` and creates nothing, so there is no id to poll. This is the one `404` that is terminal straight away. **`rules` never fail the request.** Miso rewrites the summary up to 3 times to satisfy them. If a rule still fails on the last attempt, you get `finish_reason: "success"` and that attempt. The verdict is in `metadata.rule_check_results`, which holds the iteration count and a `rule`, `passed` and `reason` for each rule. Gate on `passed` yourself if a failed rule must block publication. *** ## Instructions and rules `instructions` decide what Miso writes. `rules` decide what the result must satisfy before Miso returns it. The difference is easiest to see on one topic, run twice over the same catalog. **Instructions only.** 34 seconds, **846 words**, 6 sources: ```json Request { "instructions": "Summarize the main technology news.", "fq": "tags:Computing", "max_articles": 10 } ``` ```markdown Result # Technology News Summary ## Microsoft Expands Cloud Gaming Partnerships Amid Regulatory Scrutiny Microsoft signed a 10-year agreement with Spanish platform Nware to stream Microsoft gaming titles, [as reported by Wikinews](https://en.wikinews.org/wiki/Microsoft%2C_Nware_sign_10-year_cloud_gaming_deal). The deal came days after UK regulators blocked Microsoft's planned acquisition… ``` **The same request, with one rule.** 42 seconds, **58 words**, 3 sources: ```json Request { "instructions": "Summarize the main technology news.", "fq": "tags:Computing", "max_articles": 10, "rules": ["The summary must be under 60 words."] } ``` ```markdown Result ## Technology News Summary Microsoft signed a [10-year cloud gaming deal with Spanish platform Nware](https://en.wikinews.org/…), aiming to reassure regulators amid its contested Activision acquisition. The Netherlands moved to [restrict semiconductor exports](https://en.wikinews.org/…) on national security grounds… ``` The rule cut the output from 846 words to 58. Two details are worth your attention. ```mermaid %%{init: {'theme':'base','themeVariables':{ 'fontFamily':'IBM Plex Sans, ui-sans-serif, system-ui','fontSize':'14px', 'lineColor':'#9aa3c0','clusterBkg':'transparent','clusterBorder':'#d3d8e8', 'titleColor':'#8b93ad' },'flowchart':{'curve':'basis','nodeSpacing':20,'rankSpacing':60,'padding':12}}}%% flowchart LR REQ["`**Your request** instructions · fq · rules`"] PICK["`Pick the articles fq, then max_articles`"] GEN["`Write the summary`"] JUDGE{"`Every rule satisfied?`"} OUT["`**Return the summary**`"] GIVE["`Return it anyway after 3 attempts`"] REQ --> PICK --> GEN --> JUDGE JUDGE -- yes --> OUT JUDGE -- "no, and attempts left" --> GEN JUDGE -- "no, 3 attempts used" --> GIVE classDef req fill:#f6f7fa,stroke:#c9cfe0,color:#454c69 classDef work fill:#e8ecfb,stroke:#b9c2ea,color:#22307a classDef done fill:#f4effc,stroke:#cdbcf0,color:#40277a class REQ req class PICK,GEN,JUDGE work class OUT,GIVE done ``` A language model decides whether each rule passed, and the failures are fed back into the next attempt. That loop is why a ruled request takes longer, and why a word count lands close rather than exact. ### What rules are good at Rules work best on **word choice, formatting, and style** — the things a careful reader can check by looking. Miso judges each rule with a language model, so a rule you can hand to a sub-editor works. A rule that needs counting is weaker. This request carried three rules: ```json Request { "instructions": "Summarize the main technology news.", "fq": "tags:Computing", "max_articles": 6, "rules": [ "Write only bullet points. Do not write paragraphs.", "Do not write an introduction or a conclusion.", "Always write 'open source', never 'open-source'." ] } ``` All three held. The result was 7 bullet points and **no** paragraphs, it opened on the first item with no preamble, and the hyphenated spelling did not appear: ```markdown Result - **Microsoft cloud gaming deal**: Microsoft and Spanish platform Nware signed a 10-year agreement allowing Nware to stream Microsoft gaming titles, [reports Wikinews](https://en.wikinews.org/…); the deal extends to Activision titles if Microsoft's acquisition succeeds… - **Netherlands semiconductor export curbs**: The Dutch government announced plans to restrict exports of advanced chip-making equipment… ``` **Expect this to hold most of the time, not every time.** The same three rules against the same articles do not always give the same result. A summary can come back with a stray paragraph among the bullets, or with the spelling the rule bans. Check the output, or ask again, when a rule really matters. Write house style this way: banned and preferred terms, the shape of the output, what to leave out, the tone. ### A word count is only approximate A number is the weak case. The rule below asks for **under 60 words**, and the summary comes back at **57**, **58** or **62** words: close each time, over the line often enough to matter: ```json { "rules": ["The summary must be under 60 words."] } ``` Miso does not count the words. It asks a language model whether the rule passes, and when the answer is no, it feeds the failure back and writes the summary again, up to **3 times**. That retry is why the ruled request takes about 42 seconds against 34. So a length rule pulls the summary to roughly the size you asked for, from 846 words down to 58, but it does not hold an exact ceiling. If you need one, cut the text on your side. **A rule that cannot be judged is silently passed.** If the check itself fails, Miso keeps the summary rather than blocking it. Rules make the summary better. They do not guarantee it. *** ## What the other fields do Each example below uses the same catalog. ### `fq` chooses the articles `fq` is the filter that decides which articles Miso reads. It is the same syntax the search endpoints use, so `tags:Computing` here means what it means there. See [Filter Syntax (fq)](/api/fq). Miso then reads up to `max_articles` of them, newest and most relevant first. ### `format` changes the markup `format: "html"` returns HTML instead of Markdown: ```html format: html

Technology News Summary

Microsoft Signs 10-Year Cloud Gaming Deal

Microsoft and Spanish streaming platform Nware reached a 10-year agreement to allow Nware to stream Microsoft gaming titles, reports Wikinews.

``` ### `url_template` rewrites every link Put `{url}` where the article address belongs, and Miso rewrites each citation through it: ```json Request { "url_template": "https://example.com/track?to={url}&utm_source=miso" } ``` ```markdown Result [reports Wikinews](https://example.com/track?to=https%3A%2F%2Fen.wikinews.org%2Fwiki%2FMicrosoft%252C_Nware_sign_10-year…&utm_source=miso) ``` The article URL is percent-encoded for you, so it survives as one parameter. ### `enable_citations: false` removes the links The same request without citations returns plain prose: ```text enable_citations: false Microsoft launched a program to pay businesses for switching to its Windows Live Search engine, reports Wikinews. The initiative offers companies between $2 and $10 per computer annually, plus $25,000 just for enrolling. ``` Use it when your front end adds its own links, or when you asked for JSON. ### `virtual_articles` adds text that is not in your catalog Send up to 10 articles inline. Miso treats them like catalog articles, and they can be cited: ```json Request { "instructions": "Summarize what is new, and mention the editor's note.", "fq": "tags:Computing", "max_articles": 3, "virtual_articles": [ { "title": "Editor's note: our technology coverage", "description": "Wikinews will publish hands-on reviews of new Linux releases.", "url": "https://example.com/editors-note" } ] } ``` The summary then cites four sources: the three catalog articles, and the editor's note. Each virtual article needs `description` **or** `html`. Without one, the request fails: ```json 422 { "detail": [ { "loc": ["body", "virtual_articles", 0, "__root__"], "msg": "At least one of 'html' or 'description' must be provided", "type": "value_error" } ] } ``` ## Examples ### Simple: a weekly brief ```json Request body { "instructions": "Write a 5-bullet brief of this week's top stories.", "fq": "published_at:[now-7d TO *]", "max_articles": 20 } ``` ### Key takeaways for one article Scope the filter to a single article, and turn citations off because the reader is already on that page. ```json Request body { "instructions": "List the 3 key takeaways for a busy reader.", "fq": "product_id:(\"art-20260612-rates\")", "enable_citations": false } ``` ### Structured JSON for your front end Ask for `json` and describe the exact shape you want. The result arrives as a **JSON string** in `answer`, so parse it on your side. ```json Request body lineNumbers { "instructions": "Return short_summary and long_summary keys.", "fq": "section:\"football\" AND published_at:[now-1d TO *]", "format": "json", "rules": [ "short_summary must be 200 characters or fewer", "long_summary must be 350 words or fewer", "Output must be valid JSON with exactly those two keys" ] } ``` ### Enforcing house style with rules ```json Request body { "instructions": "Summarize the latest coverage of this company.", "fq": "companyName:\"Example Corp\"", "max_articles": 100, "rules": [ "Every bullet point must name the company", "Each section must have at least one bullet point", "There must be no introduction and no closing text" ] } ``` ### Writing in another language There is no language field. State the language in your instructions, and add a rule to enforce it. ```json Request body { "instructions": "Fasse die aktuellen Meldungen in drei Punkten zusammen.", "fq": "published_at:[now-1d TO *]", "rules": ["Die gesamte Ausgabe muss auf Deutsch sein."] } ``` ### Adding your own text Use `virtual_articles` for text that is not in your catalog: a press release, a data feed, or an unpublished draft. Miso treats them like catalog articles for citations and sources. They do not count toward `max_articles`. The limit is 10. | Field | Type | Notes | | --- | --- | --- | | `title` | string | Required. | | `url` | string | Required. Used for citations. | | `html` or `description` | string | Required. Supply at least one. | | `authors` | string[] | Optional. | | `published_at` | string | Optional. ISO format. | ```json Request body { "instructions": "Summarize all of the provided articles.", "virtual_articles": [ { "title": "Quantum computing breakthrough", "url": "https://example.com/quantum", "html": "

Researchers achieved 1000-qubit stability.

" } ] } ``` --- ## Ready-made templates Two templates ship with the API. Both are opinionated. For most cases, your own `instructions` give a better result. | Template | What it writes | | --- | --- | | `newsletter_v1` | A newsletter-style brief with headlines. | | `newsvault` | A legal-editorial brief. | ```json Request body { "template": "newsletter_v1", "fq": "published_at:[now-7d TO *]", "template_parameters": { "briefing_name": "Markets Brief", "focus_topic": "interest rates", "max_headlines": 5, "tone": "professional" } } ``` `newsletter_v1` accepts `briefing_name`, `focus_topic`, `max_headlines` (`1`–`20`), `target_audience`, `tone`, `include_quick_hits`, and `opening_style`. `newsvault` accepts `summary_type` and `focus_topic`. --- ## Notes and limits - **The model sees 25 articles.** `max_articles` controls how many are retrieved, not how many are summarized. - **`rules` cost time.** Each failed check triggers a rewrite, up to 3 times. A request with rules can take longer than a synchronous wait allows. - **`format: "json"` always runs a rule check**, because valid JSON is itself a rule. - **Unknown fields are ignored.** The request still runs. - **Some features are enabled per app.** Scheduled refresh of permanent summaries, saved task configurations, and pregenerated related questions are set up by Miso. Contact your Miso representative to enable them. # Content Tagging Classify a document against IPTC and IAB taxonomies. The Tagging API classifies a document against standard content taxonomies. You send a title and body text. Miso returns the topics, entities, and keywords for that document. Below we tag one article end to end. Common uses: - Add IPTC or IAB categories to an article. - Route content to the right section or feed. - Build topic pages and related-content links. The API is stateless. You pass the text you want to tag. Miso does not read your content index, and it does not store the document. --- ## Tag sets A **tag set** is a named group of taxonomies. The URL path selects it: `/v1/ask/tagging/{tag_set}`. Miso ships with one tag set, `iptc_iab`. It tags against two industry taxonomies: - **IPTC Media Topics** — a subject taxonomy for news and media. - **IAB Content Taxonomy** (v3.1) — a taxonomy for content and advertising. The API key on a request controls access and usage only. It does not change the tag set or the result. --- ## Authentication Every request needs your **API key**. Pass it as `?api_key=YOUR_KEY` or in the `X-Api-Key` header. Base URL: `https://api.askmiso.com`. --- ## Tag a document Tagging is a two-step flow. First you submit the document. Then you poll for the result. ### 1. Submit the document `POST /v1/ask/tagging/{tag_set}` | Field | Type | Default | Notes | | --- | --- | --- | --- | | `title` | string | *required* | The document title. | | `content` | string | *required* | The document body, as plain text. | ```bash cURL curl -X POST "https://api.askmiso.com/v1/ask/tagging/iptc_iab" \ -H "X-Api-Key: $KEY" \ -H "Content-Type: application/json" \ -d '{ "title": "Central bank signals two rate cuts in 2026", "content": "The central bank said it expects two cuts..." }' ``` ```javascript JavaScript const res = await fetch("https://api.askmiso.com/v1/ask/tagging/iptc_iab", { method: "POST", headers: { "X-Api-Key": KEY, "Content-Type": "application/json", }, body: JSON.stringify({ title: "Central bank signals two rate cuts in 2026", content: "The central bank said it expects two cuts..." }), }); const data = (await res.json()).data; ``` ```python Python import requests res = requests.post( "https://api.askmiso.com/v1/ask/tagging/iptc_iab", headers={"X-Api-Key": KEY}, json={ "title": "Central bank signals two rate cuts in 2026", "content": "The central bank said it expects two cuts..." }, ) data = res.json()["data"] ``` You get back a `tagging_id` to poll: ```json Response { "message": "success", "data": { "tagging_id": "0e1f2a3b-4c5d-6e7f-8a9b-0c1d2e3f4a5b" } } ``` If the `{tag_set}` does not exist, Miso returns `404`. > To get the result in one call, add `?wait_for_answer=true` to the POST. The > request then blocks until tagging is complete and returns the result directly. ### 2. Get the tags `GET /v1/ask/tagging/{tag_set}/{tagging_id}` Poll this endpoint until `finished` is `true`. ```bash cURL curl "https://api.askmiso.com/v1/ask/tagging/iptc_iab/$TAGGING_ID" \ -H "X-Api-Key: $KEY" ``` ```javascript JavaScript const res = await fetch( "https://api.askmiso.com/v1/ask/tagging/iptc_iab/$TAGGING_ID", { headers: { "X-Api-Key": KEY } } ); const data = (await res.json()).data; ``` ```python Python import requests res = requests.get( "https://api.askmiso.com/v1/ask/tagging/iptc_iab/$TAGGING_ID", headers={"X-Api-Key": KEY}, ) data = res.json()["data"] ``` ```json Response lineNumbers { "message": "success", "data": { "tag_set": "iptc_iab", "stage": "Done", "finished": true, "finish_reason": "success", "tags": { "tag_set": "iptc_iab", "taxonomies": [ { "taxonomy": "iptc", "themes": [ { "code": "medtop:20000350", "label": "economy, business and finance", "confidence": 0.91, "model_agreement": "3/3" } ] }, { "taxonomy": "iab", "themes": [ { "code": "432", "label": "Personal Finance", "confidence": 0.78, "model_agreement": "2/3" } ] } ], "entities": [ { "name": "Federal Reserve", "kind": "organization", "relevance": 0.9, "role": "primary", "model_agreement": "3/3" } ], "keywords": [ { "keyword": "interest rates", "relevance": 0.85, "model_agreement": "3/3" } ] } } } ``` --- ## Read the result Tagging is asynchronous. `finished` says the job is over, and `finish_reason` says whether it worked. Do not branch on `stage`, which is a progress label: a successful tagging leaves it at `"Done"`, and only a failure sets `"Failed"`. See [Async results and polling](/api/async-results) for the value list, the grace window, the stall guard, the status codes, and a polling loop. **A poll returns `404` in three cases.** The `tagging_id` does not exist, it belongs to a different app, or the `{tag_set}` does not match the one that created the id. Inside the first 10 seconds, a `404` means "not ready yet". After that, it means Miso lost the job, so submit the document again. **An empty result is a real "no tags".** `finish_reason: "success"` with empty `taxonomies`, `entities` and `keywords` means the job worked and Miso found nothing above the threshold. With a failure value, empty tags mean the job failed instead. **One article takes 30 to 50 seconds.** Poll every 2 to 3 seconds. Tagging returns nothing until it is done, so a shorter interval only costs you requests. --- ## Result fields The `tags` object holds three lists: `taxonomies`, `entities`, and `keywords`. ### Themes (per taxonomy) Each entry in `taxonomies` has a `taxonomy` name and a list of `themes`. | Field | What it is | | --- | --- | | `code` | The taxonomy code or id for the topic. | | `label` | The topic name in plain words. | | `confidence` | A score from 0 to 1. It is the mean confidence over the models that agreed. | | `model_agreement` | The vote, as `/`. `2/3` means 2 of the 3 models that returned data agreed. | ### Entities | Field | What it is | | --- | --- | | `name` | The entity name. | | `kind` | `person`, `organization`, or `location`. | | `relevance` | A score from 0 to 1. It shows how central the entity is to the document. | | `role` | `primary` or `secondary`. | | `model_agreement` | Same meaning as above. | ### Keywords | Field | What it is | | --- | --- | | `keyword` | The keyword. | | `relevance` | A score from 0 to 1. | | `model_agreement` | Same meaning as above. | --- ## How the tags are chosen Miso sends the document to several models. Each model tags it against the taxonomy on its own. Miso then merges the results with a cross-vote. - Miso keeps a topic when enough models agree on it. - `confidence` is the mean over the models that agreed. - `model_agreement` shows the vote, for example `3/3`. Miso validates every code against the taxonomy. If a code is a near-miss, Miso corrects it to the closest valid code. If a code has no match, Miso drops it. Miso extracts entities and keywords once, then votes across the models. It normalizes entity names and drops social-platform handles. If a keyword repeats an entity, Miso removes the keyword. --- ## Caching Miso caches each result against the tag set, the title, and the content. A repeat request for an unchanged document returns the cached tags, so you can call the API again safely. Re-tagging is automatic. Miso classifies the document again when you edit the title or the body, and when Miso updates the tag set. # User History Save a reader's questions, and let them reopen the thread. User History saves every question a signed-in reader asks. The reader can reopen past conversations. Miso can also tell the reader when it has a **fresh answer** to an earlier question. Below we build a history page, then a fresh-answer indicator. Two capabilities, one API: - **User History** — Miso saves each question a signed-in user asks and groups the follow-ups into conversation threads. You can list, reopen, rename, and delete them. - **Answer Updates** — a user can subscribe to a thread. Miso then watches that topic. When Miso finds important new content, it appends a fresh follow-up answer and raises an **unread indicator**. > **Availability.** Miso enables User History and Answer Updates per app. To turn > them on for your app, contact your Miso representative. All endpoints use `POST`. Pass the API key as `?api_key=YOUR_KEY` or in the `X-Api-Key` header. Base URL: `https://api.askmiso.com`. --- ## When the feature is off User history is enabled per app. Until Miso turns it on, every endpoint on this page returns `403`, and no history is recorded: ```json 403 { "message": "user history is not enabled for this app" } ``` Ask your Miso representative to enable it. A `403` here is a setting, not your key: the same key reaches the rest of the API. ## How records are created You do not write history yourself. Miso does it automatically. When a signed-in user asks a question through the [Answer API](/api/genai/explore) (`POST /v1/ask/questions`), Miso records it in the background. - Only the **first question** of a conversation becomes a history row (a *thread*). Miso attaches the follow-ups to that thread and moves it to the top of the list. - Miso records only questions from an **authenticated user**. It never saves an anonymous question to history. ### Exclude a question from history To keep a question out of history, pass `log_user_history: false` on `POST /v1/ask/questions`. Miso then does not save that question. Use this for a per-question "private mode" toggle. The default is `true`. ```json Request body { "user_id": "alice", "question": "How do interest rate cuts affect mortgages?", "log_user_history": false } ``` This controls only the saved history for the user. Your usage analytics do not change. --- ## Authentication Every User History endpoint needs your **API key** and an **authenticated user**. You authenticate the user in one of two ways. The method depends on which key you use. | Key type | Where the user comes from | JWT | | --- | --- | --- | | **Publishable key** (browser) | the JWT | **Required** | | **Secret key** (server) | `user_id` in the request body | Optional | - **Secret key (server-side).** The key authenticates the caller. You pass `user_id` in the body, and Miso trusts it. - **Publishable key (browser).** This key is safe to put in the browser. It must carry a signed **JWT** that proves who the user is. Pass the JWT as `Authorization: Bearer ` (preferred) or in a `jwt_token` body field. Sign the JWT with your app's secret key and the **HS256** algorithm. Its `user_id` (or `sub`) claim is the authenticated user. If a request supplies `user_id` in **both** the JWT and the body, the two values must match. If they do not match, Miso returns `401`. See [JWT (user authentication)](/api/authentication#jwt-user-authentication) for the claims Miso reads and what each `401` means. ### Create a browser JWT (server-side) Sign a short-lived token on your server with your secret key. Then send the token to the browser. ```python Sign a browser JWT import hmac, hashlib, base64, json, time def b64(d): return base64.urlsafe_b64encode(d).rstrip(b"=").decode() secret = "YOUR_SECRET_API_KEY" # sign with your app's SECRET key header = b64(json.dumps({"alg": "HS256", "typ": "JWT"}).encode()) claims = {"user_id": "alice", "exp": int(time.time()) + 3600} payload = b64(json.dumps(claims).encode()) signing = f"{header}.{payload}".encode() sig = b64(hmac.new(secret.encode(), signing, hashlib.sha256).digest()) jwt = f"{header}.{payload}.{sig}" ``` --- ## Read and manage history ```mermaid %%{init: {'theme':'base','themeVariables':{ 'fontFamily':'IBM Plex Sans, ui-sans-serif, system-ui','fontSize':'14px', 'actorBkg':'#3148be','actorBorder':'#3148be','actorTextColor':'#ffffff', 'actorLineColor':'#9aa3c0','signalColor':'#9aa3c0','signalTextColor':'#6b7392', 'labelBoxBkgColor':'#f4effc','labelBoxBorderColor':'#cdbcf0', 'labelTextColor':'#40277a','noteBkgColor':'#e8ecfb','noteBorderColor':'#b9c2ea', 'noteTextColor':'#22307a','sequenceNumberColor':'#ffffff' }}}%% sequenceDiagram autonumber participant R as Reader participant A as Your app participant M as Miso R->>A: asks a question A->>M: POST /v1/ask/questions (user_id) Note over M: recorded as a new thread, its id is the thread_id R->>A: asks a follow-up A->>M: POST /v1/ask/questions (parent_question_id) Note over M: appended to the same thread R->>A: opens the history sidebar A->>M: POST /v1/ask/user_history/list M-->>A: threads, each with has_new, plus has_more R->>A: picks one thread A->>M: POST …/user_history/thread (thread_id) M-->>A: the question ids, in order A->>M: POST /v1/ask/answers (question_ids) M-->>A: every answer in one call A-->>R: the conversation R->>A: renames or deletes it A->>M: POST …/thread/rename or …/user_history/delete ``` A thread is a root question plus the follow-ups that hang off it. The root question id **is** the `thread_id`. Reading a thread is two calls: `…/thread` for the ids, then `/v1/ask/answers` for the answers in one round trip. > **Every timestamp on this page is UTC, and carries no time zone.** `time` and > `favorited_at` come back as `2026-06-12T10:15:00.482913`, with no `Z` and no > offset. Most date parsers read a string in that shape as **local** time, so a > reader outside UTC sees the wrong hour. In JavaScript, append the `Z` > yourself: > > ```js > new Date(row.time + 'Z') // correct > new Date(row.time) // shifts by the reader's offset > ``` > > Convert to the reader's zone for display. ### List a user's threads `POST /v1/ask/user_history/list` | Field | Type | Default | Notes | | --- | --- | --- | --- | | `user_id` | string | *required* | The signed-in user. | | `rows` | integer | `100` | Page size, `1`–`200`. | | `start` | integer | `0` | Pagination offset. | | `order` | string | `desc` | `desc` = newest thread first. `asc` = oldest first. | | `before` | datetime | — | Return only threads before this time (cursor paging). | | `favorite` | boolean | — | Omit for every thread. `true` returns only starred threads, `false` only unstarred. | The response is an object, and it tells you whether another page exists: ```json Response { "message": "success", "data": { "threads": [ { "time": "2026-06-12T10:15:00.482913", "thread_id": "0e1f2a3b-4c5d-6e7f-8a9b-0c1d2e3f4a5b", "title": "How do interest rate cuts affect mortgages?", "subscribed": true, "has_new": false, "favorite": true, "favorited_at": "2026-06-12T11:02:44.120000" } ], "has_more": true, "start": 0, "rows": 20 } } ``` ```bash cURL curl -X POST "https://api.askmiso.com/v1/ask/user_history/list" \ -H "X-Api-Key: $KEY" \ -H "Content-Type: application/json" \ -d '{ "user_id": "alice", "rows": 20 }' ``` ```javascript JavaScript const res = await fetch("https://api.askmiso.com/v1/ask/user_history/list", { method: "POST", headers: { "X-Api-Key": KEY, "Content-Type": "application/json", }, body: JSON.stringify({ user_id: "alice", rows: 20 }), }); const data = (await res.json()).data; ``` ```python Python import requests res = requests.post( "https://api.askmiso.com/v1/ask/user_history/list", headers={"X-Api-Key": KEY}, json={ "user_id": "alice", "rows": 20 }, ) data = res.json()["data"] ``` | Field | What it is | | --- | --- | | `thread_id` | The thread. Pass it to every other endpoint on this page. | | `title` | The thread's display name. Render it as the row label. Miso writes it from the first question, and [rename](#rename-a-thread) replaces it. | | `time` | The last activity. The list shows the most recent first. | | `subscribed` | Whether this thread subscribes to Answer Updates. | | `has_new` | The **thread-level unread indicator**. An unseen update is ready. | | `favorite` | Whether the reader starred this thread. | | `favorited_at` | When they starred it, or `null` when they did not. | ### Read a thread `POST /v1/ask/user_history/thread` Returns the `question_id` values in a thread, in order. The root question comes first, then the follow-ups. | Field | Type | Default | Notes | | --- | --- | --- | --- | | `thread_id` | UUID | *required* | The thread's root question id. | | `user_id` | string | *required* | Miso confirms that this user owns the thread. | | `rows` | integer | `30` | Page size (max `100`). | | `after` | UUID | — | Cursor — return the questions **after** this id. | | `order` | string | `asc` | `asc` = root → newest. `desc` = newest → root. | > **Send `user_id` on every call.** Miso checks that the thread belongs to > that reader, and answers `404 {"message": "Thread not found"}` when it does > not. A thread that does not exist answers the same `404`, on purpose: a > separate status confirms which thread ids are real. **To open a long thread at the newest answer**, send `order: "desc"`. The first page then holds the most recent questions, and `after` pages **backwards** toward the root. This is what a chat view wants: render the newest turn at once, and fetch the older ones as the reader scrolls up. ```json Response { "message": "success", "data": { "question_ids": [ "0e1f2a3b-4c5d-6e7f-8a9b-0c1d2e3f4a5b", "1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d" ], "has_more": false } } ``` **Paging.** To get the next page, pass the **last** `question_id` of the current page as `after`. Repeat until `has_more` is `false`. ### Fetch answers in bulk `POST /v1/ask/answers` After you have the `question_id` values of a thread, fetch all their answers in **one** request. This is faster than one call per question. This endpoint reads existing answers only. It does not re-run the answer pipeline. | Field | Type | Notes | | --- | --- | --- | | `question_ids` | UUID[] | The ids to fetch (`1`–`50`). | ```bash cURL curl -X POST "https://api.askmiso.com/v1/ask/answers" \ -H "X-Api-Key: $KEY" \ -H "Content-Type: application/json" \ -d '{ "question_ids": [ "0e1f2a3b-4c5d-6e7f-8a9b-0c1d2e3f4a5b", "1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d" ] }' ``` ```javascript JavaScript const res = await fetch("https://api.askmiso.com/v1/ask/answers", { method: "POST", headers: { "X-Api-Key": KEY, "Content-Type": "application/json", }, body: JSON.stringify({ question_ids: [ "0e1f2a3b-4c5d-6e7f-8a9b-0c1d2e3f4a5b", "1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d" ] }), }); const data = (await res.json()).data; ``` ```python Python import requests res = requests.post( "https://api.askmiso.com/v1/ask/answers", headers={"X-Api-Key": KEY}, json={ "question_ids": [ "0e1f2a3b-4c5d-6e7f-8a9b-0c1d2e3f4a5b", "1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d" ] }, ) data = res.json()["data"] ``` ```json Response { "message": "success", "data": [ { "question_id": "0e1f2a3b-…", "question": "…", "answer": "…", "sources": [] }, null ] } ``` - The `data` array matches your input. `data[i]` corresponds to `question_ids[i]`. - An id that does not exist, or does not belong to your app, returns `null`. As a result, answers never leak across apps. - Each entry matches the `data` of `GET /v1/ask/questions/{question_id}/answer` (see [Answer response fields](/api/genai/answer-fields)). - To render a whole thread, use this endpoint instead of many single fetches. It makes one round trip, not many. ### Rename a thread `POST /v1/ask/user_history/thread/rename` | Field | Type | Notes | | --- | --- | --- | | `thread_id` | UUID | The thread's root question id. | | `user_id` | string | Required. | | `title` | string | The new display title (max 1000 chars). | Miso echoes the new name: ```json Response { "message": "success", "data": { "thread_id": "0e1f2a3b-4c5d-6e7f-8a9b-0c1d2e3f4a5b", "title": "Rocky Linux — renamed" } } ``` The list endpoint then returns it as each row's `title`. If the thread does not exist, the call returns `404`. > Miso titles a thread from its first question. If the question is longer than > about 60 characters, Miso generates a short title. ### Favorite a thread `POST /v1/ask/user_history/thread/favorite` Stars a thread, so a reader can keep the conversations they want to come back to. | Field | Type | Default | Notes | | --- | --- | --- | --- | | `thread_id` | UUID | *required* | The thread's root question id. | | `user_id` | string | *required* | The signed-in reader who owns the thread. | | `favorite` | boolean | `true` | `true` stars the thread. `false` removes the star. | **Send the state you want, not a toggle.** The call is idempotent, so a retry or a double tap cannot turn the star back off. ```json Response { "message": "success", "data": { "thread_id": "0e1f2a3b-4c5d-6e7f-8a9b-0c1d2e3f4a5b", "question_id": "0e1f2a3b-4c5d-6e7f-8a9b-0c1d2e3f4a5b", "favorite": true, "favorited_at": "2026-06-12T11:02:44.120000" } } ``` Unstarring returns `"favorite": false` and `"favorited_at": null`. ```bash cURL curl -X POST "https://api.askmiso.com/v1/ask/user_history/thread/favorite" \ -H "X-Api-Key: $KEY" \ -H "Content-Type: application/json" \ -d '{ "thread_id": "0e1f2a3b-4c5d-6e7f-8a9b-0c1d2e3f4a5b", "user_id": "alice" }' ``` ```javascript JavaScript const res = await fetch( "https://api.askmiso.com/v1/ask/user_history/thread/favorite", { method: "POST", headers: { "X-Api-Key": KEY, "Content-Type": "application/json", }, body: JSON.stringify({ thread_id: "0e1f2a3b-4c5d-6e7f-8a9b-0c1d2e3f4a5b", user_id: "alice", }), } ); const data = (await res.json()).data; ``` ```python Python import requests res = requests.post( "https://api.askmiso.com/v1/ask/user_history/thread/favorite", headers={"X-Api-Key": KEY}, json={ "thread_id": "0e1f2a3b-4c5d-6e7f-8a9b-0c1d2e3f4a5b", "user_id": "alice" }, ) data = res.json()["data"] ``` To build a "Favorites" tab, pass `favorite: true` to [the list endpoint](#list-a-users-threads). Every row also carries `favorite`, so one listing renders both the tab and the star on each row. | Status | Meaning | | --- | --- | | `400` | `user_id` is missing. | | `404` | `Thread not found`. The thread does not exist, or it belongs to another reader. | > **The star reaches the list a moment later.** Listing reads a replica, so a > newly starred thread takes up to a minute or two to appear under > `favorite: true`. The response above is immediate and authoritative, so drive > the star in your interface from it rather than from a fresh listing. ### Delete specific threads `POST /v1/ask/user_history/delete` | Field | Type | Notes | | --- | --- | --- | | `thread_ids` | UUID[] | The threads to delete. | | `user_id` | string | Required. | ```json Request { "user_id": "alice", "thread_ids": ["2b3c4d5e-6f7a-8b9c-0d1e-2f3a4b5c6d7e"] } ``` `thread_ids` holds the same value as `/thread`, `/thread/rename` and the update endpoints, so one identifier covers the whole API. **Deleting works per thread, not per question.** A thread is one row of history, and only the root question is written there. A follow-up's question id matches nothing, and the call returns `200` with `deleted_count: 0`. Send the `thread_id` the list endpoint gives you. Read `deleted_count` and compare it with the number of ids you sent: ```json Response { "message": "success", "data": { "deleted_count": 2 } } ``` ### An empty list means no history A read that fails now answers `500`. It no longer returns an empty list, and a delete that fails no longer answers `deleted_count: 0`. That matters for what you render. An empty `threads` array means the reader has no history, so draw the empty state. Before, a storage fault looked exactly the same, so a reader with a full sidebar watched it come back blank. Treat `500` as "try again", and keep whatever you already had on screen. ### Delete all history `POST /v1/ask/user_history/delete_all` | Field | Type | Notes | | --- | --- | --- | | `user_id` | string | Required. | Every delete is a soft delete. Miso can reverse it. But the record disappears from every read immediately. --- ## Putting it together A typical front-end flow: 1. **On load** — call `…/user_history/list` for the sidebar. Read each thread's `has_new` field for its own indicator, and `has_more` to page. 2. **Open a thread** — call `…/thread` with its `thread_id`, then `…/answers` to fetch every answer in one call. 3. **Let users manage history** — `…/rename`, `…/delete`, and `…/delete_all`. ## Next [Answer Updates](/api/genai/answer-updates) is the next step. It covers how a reader subscribes to a thread, how Miso appends a fresh answer when the story moves on, and how the indicators clear. # Answer Updates Tell a reader when an old question has a better answer. News moves fast. A question from last week can have a better answer today. Answer Updates let a reader **subscribe** to a conversation. Miso watches that topic, appends a fresh follow-up answer when it finds important new content, and raises an indicator your interface can show. Below we subscribe a reader, then show them what arrived. This builds on [User History](/api/genai/user-history), because a thread has to exist before a reader can subscribe to it. Read that page first. > **History is enabled per app.** Miso records a question in history only for > apps that have the feature switched on. On an app without it, > `POST /v1/ask/user_history` returns an empty list, and `subscribe` answers > `404 "Thread not found"` — the thread it looks for was never recorded. Ask > your Miso representative to enable it before you build against these > endpoints. News moves fast. A question from last week can have a better answer today. **Answer Updates** let a reader *subscribe* to a conversation. Miso then watches that topic. When Miso finds important new content, it appends a fresh follow-up answer to the thread and raises a notification. ```mermaid %%{init: {'theme':'base','themeVariables':{ 'fontFamily':'IBM Plex Sans, ui-sans-serif, system-ui','fontSize':'14px', 'actorBkg':'#3148be','actorBorder':'#3148be','actorTextColor':'#ffffff', 'actorLineColor':'#9aa3c0','signalColor':'#9aa3c0','signalTextColor':'#6b7392', 'labelBoxBkgColor':'#f4effc','labelBoxBorderColor':'#cdbcf0', 'labelTextColor':'#40277a','noteBkgColor':'#e8ecfb','noteBorderColor':'#b9c2ea', 'noteTextColor':'#22307a','sequenceNumberColor':'#ffffff' }}}%% sequenceDiagram autonumber participant R as Reader participant A as Your app participant M as Miso participant W as Update monitor R->>A: asks a question A->>M: POST /v1/ask/questions Note over M: the answer becomes the root of a thread A->>M: POST …/thread/updates/subscribe Note over M,W: the thread is now watched W->>W: new article published W->>M: append a follow-up answer, stamp the thread Note over M: metadata.miso_generated_by = "answer_update_monitor" A->>M: POST …/thread/updates M-->>A: has_new: true A-->>R: show the indicator R->>A: opens the thread A->>M: POST …/thread, then …/answers M-->>A: the turns, including the generated one A->>M: POST …/thread/updates/dismiss_thread Note over A,M: the indicator clears ``` ## Two levels of unread indicator Miso reports two booleans. Most interfaces render them as a dot or a badge, but the API only tells you whether an unseen update exists. | Indicator | Question it answers | How you read it | | --- | --- | --- | | **Account level** | Does this user have *any* unseen update? | Poll `POST /v1/ask/user_history/thread/updates` | | **Thread level** | Does *this* thread have an unseen update? | The `has_new` field on the history list | Miso calculates both values at read time. It compares the time of the last update with the time the user last dismissed that level. Miso does not store a separate flag. ## Every endpoint, and what it returns Each call takes `user_id`, and the per-thread calls also take `thread_id` (the **root** question of the thread). These are the exact bodies, from a live run: | Endpoint | Body | Response | | --- | --- | --- | | `…/thread/updates` | `user_id` | `{"message": "success", "data": {"has_new": false}}` | | `…/thread/updates/subscribe` | `user_id`, `thread_id` | `{"message": "success"}`, or `404 {"message": "Thread not found"}` | | `…/thread/updates/unsubscribe` | `user_id`, `thread_id` | `{"message": "success"}`, or `404 {"message": "Thread not found"}`. Idempotent. | | `…/thread/updates/dismiss_thread` | `user_id`, `thread_id` | `{"message": "success"}`, or `404 {"message": "Thread not found"}`. Idempotent. | | `…/thread/updates/dismiss_overall` | `user_id` | `{"message": "success"}` | | `…/thread/updates/touch` | `user_id`, `thread_id` | `{"message": "success", "data": {"touched": 0}}` | Only two calls return a `data` object. The poll returns `has_new`, and `touch` returns `touched`, **the number of subscriptions it stamped**. `touched: 0` means no live subscription matches, so nothing lights up. Use it to check your test setup before you blame the front end. With `generate: true`, `touch` also writes the update, and names it: ```json touch with generate { "message": "success", "data": { "generated": true, "question_id": "0e1f2a3b-4c5d-6e7f-8a9b-0c1d2e3f4a5b", "touched": 1 } } ``` That `question_id` is a new turn at the end of the thread. Read it with the single-answer endpoint, the same way you read any other turn. Every one of these requires `user_id`. Without it you get `400 {"message": "user_id is required"}`. **A thread that belongs to another reader answers `404 "Thread not found"`**, on `subscribe`, `unsubscribe` and `dismiss_thread` alike. A thread that does not exist answers the same `404`. Both stay idempotent otherwise: unsubscribing your own thread that was never subscribed is a quiet success. ## Subscribe a thread `POST /v1/ask/user_history/thread/updates/subscribe` | Field | Type | Notes | | --- | --- | --- | | `user_id` | string | The subscriber. | | `thread_id` | UUID | The thread's root question id. | This call is idempotent. If the user does not own the thread, Miso returns `404`. ## Unsubscribe Subscribe answers `404 "Thread not found"` when that `thread_id` is not a thread of that `user_id`. Two causes, in this order: history is not enabled for the app, or the `user_id` does not match the one that asked the question. `POST /v1/ask/user_history/thread/updates/unsubscribe` uses the same body (`user_id`, `thread_id`). This call is idempotent. ## Poll the account-level indicator `POST /v1/ask/user_history/thread/updates` takes the body `user_id`. Your UI polls this endpoint to show or clear the account-level indicator, for example every 60 seconds. ```json Response { "data": { "has_new": true } } ``` ## Dismiss | Endpoint | Body | Effect | | --- | --- | --- | | `…/thread/updates/dismiss_thread` | `user_id`, `thread_id` | Clears one thread. If no other thread has an unseen update, the account-level indicator clears too. | | `…/thread/updates/dismiss_overall` | `user_id` | Clears the **account-level** indicator only. Each thread keeps its own. | **How each value is decided:** ```text Indicator rules thread has_new = an update arrived after you last dismissed that thread account has_new = some subscribed, visible thread has an unseen update that is newer than your last "dismiss all" ``` If the user dismisses every thread, the account-level indicator clears on its own. `dismiss_overall` clears only the account level. Each thread keeps its own indicator for the user to review. ## How updates are generated - Miso monitors subscribed threads **periodically**, not on every request. By default, a thread produces at most one generated update per day. - Miso counts only content **published after the thread's last activity** as an update. Older articles can appear only as clearly-labeled background. - Miso judges the importance of the content before it appends. If nothing important is new, Miso creates **no update and no indicator**. - Generation is asynchronous. The new follow-up answer streams like any other answer. To read it, reopen the thread or fetch the new `question_id`. - Miso titles the follow-up like *"Latest developments since July 7, 2026 regarding: <thread title>"*. ## What a generated update looks like Miso writes the question for the reader, from the thread's **title**. A subscribed thread titled "Rocky Linux" produces a turn like this: ```json The generated turn { "question": "Latest developments since July 31, 2026 regarding: Rocky Linux", "metadata": { "miso_generated_by": "answer_update_monitor" }, "answer": "There are no new updates on Rocky Linux in the knowledge base since July 31, 2026. This topic will continue to be monitored for any future developments." } ``` Renaming a thread changes the wording of its later updates, because the title is the subject. An update is written even when there is nothing new, so the reader can see that the topic was checked. Show the indicator, and let them read the turn. ## Telling a generated update from a reader's question A generated update is appended to the thread as an ordinary follow-up, so `parent_question_id` does **not** separate the two — both have one. Miso marks every generated update instead. Read the answer and check `metadata`: ```json A generated update { "data": { "question_id": "7c8d9e0f-1a2b-3c4d-5e6f-7a8b9c0d1e2f", "question": "Latest developments since July 7, 2026 regarding: …", "answer": "…", "metadata": { "miso_generated_by": "answer_update_monitor" } } } ``` A question the reader typed carries no such key. ```javascript Classify each answer const isGeneratedUpdate = (answer) => answer.metadata?.miso_generated_by === "answer_update_monitor"; ``` The key appears on both routes that create an update: the automatic monitor, and `touch` with `generate: true`. It reaches you through the single-answer poll and through the bulk `/v1/ask/answers` endpoint. > **Treat this as an origin hint only.** `metadata` is > client-writable, so a caller can send the same key on a typed question. That > misleads only that caller's own interface, and it grants no extra access. Do > not use it to gate anything. ## Trigger an update on demand (advanced, server-side) `POST /v1/ask/user_history/thread/updates/touch` This endpoint is optional. It marks a thread's subscriptions as updated now. Use it for server-side integrations and end-to-end tests. | Field | Type | Notes | | --- | --- | --- | | `thread_id` | UUID | The thread to mark as updated. | | `user_id` | string | Optional (secret key). Narrows the change to one subscriber. | | `generate` | boolean | If `true`, also appends a generated follow-up answer. | - **Secret key:** marks every live subscription of the thread. The `user_id` field narrows the change to one subscriber. - **Publishable key:** limited to the caller's own subscription. You can light set the indicator only for yourself. - The API key determines the `app_id`. As a result, a key can mark only the threads of its own app. ```json Response { "data": { "generated": true, "question_id": "…", "touched": 1 } } ``` > **CAUTION:** `touch` appends and stamps without any check. If the thread has no > new content, `generate: true` produces a sourceless "no new updates" card. The > automatic monitor judges the content first and never does this. Use > subscriptions for the real user experience. Use `touch` only for tests or > explicit server-side triggers. --- ## Putting it together 1. **On load** — poll `…/thread/updates` for the account-level indicator, and read each thread's `has_new` from the history list. 2. **Open a thread** — fetch it, then call `…/dismiss_thread` to clear that thread's indicator. 3. **Offer updates** — call `…/subscribe` on the threads a reader cares about, and keep polling for fresh answers. 4. **Tell the two apart** — check `metadata.miso_generated_by` before you render a turn as the reader's own question. # Search & Recommendation Results without an answer: grids, rails and type-ahead. These endpoints return results without an AI answer: a product grid, a "related articles" rail, a trending list, a type-ahead box. Below we call each one and show what it returns. **Pick the right search for your catalog.** | Your catalog | Use | Why | | --- | --- | --- | | **Articles, video, documents** | [Hybrid Search](/api/genai/hybrid-search) | A reader asks in words, and wants an answer as much as a list. Hybrid Search returns both from one call. | | **Products, listings, inventory** | The **Search API** on this page | A shopper wants the matching items, fast, at high volume. No answer is generated, so nothing waits on a model. | The Search API is built for the e-commerce shape of the problem: heavy concurrent traffic, short queries, and a results page that has to render now. Hybrid Search is built for the content shape: fewer, longer questions, where an answer with citations is the point. For reference, Hybrid Search returns its results in about 2 seconds and finishes the answer about 5 seconds later. Use both if you have both. They read the same catalog. All of them take `POST`, a JSON body, and your **secret** key. See [Authentication](/api/authentication). > The examples on this page use the public Wikinews catalog, so you can load it > and run them yourself. See [Example: Wikinews](/start/example-news-site). > **These endpoints need an engine.** Search and recommendation run on engines > that Miso creates for your app in Dojo. Until one exists, every call here > returns `404`: > > ```json > { "message": "`search` engine is not found. Please create it in Dojo first or retry in a few seconds." } > ``` > > The GenAI endpoints — answers, hybrid search, summaries — do **not** need > one. If search returns this error while answers work, the engine is what is > missing, not your key or your data. ## Which one do I want? | You want | Endpoint | | --- | --- | | Fast search over a product catalog | `POST /v1/search/search` | | A type-ahead box | `POST /v1/search/autocomplete` | | Several products by id, in one call | `POST /v1/search/mget` | | "More like this" on an article page | `POST /v1/recommendation/product_to_products` | | A personalized rail for one reader | `POST /v1/recommendation/user_to_products` | | What is popular now | `POST /v1/recommendation/user_to_trending` | | The categories a reader leans towards | `POST /v1/recommendation/user_to_categories` | | The attributes a reader leans towards | `POST /v1/recommendation/user_to_attributes` | | Several of the above in one round trip | `POST /v1/bulk` | Every parameter and response is in the [API Reference](/api/reference/tag/search-apis). ## Search ```bash Search your catalog curl -X POST "https://api.askmiso.com/v1/search/search" \ -H "X-Api-Key: YOUR_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "q": "interest rates", "rows": 10, "fl": ["title", "url", "cover_image"], "fq": "custom_attributes.premium:\"false\"", "anonymous_id": "visitor-8f3a1c" }' ``` | Field | What it does | | --- | --- | | `q` | The query. | | `rows`, `start` | Page size and offset. | | `fl` | Which product fields come back. Any field you uploaded, including a custom attribute. | | `fq` | A filter that restricts the candidates. It does not affect ranking. | | `user_id`, `anonymous_id` | Identify the reader, so Miso can personalize the order. | `fq` is the same filter syntax the answer APIs use, so a rule you write once works in both. See [Filter Syntax (fq)](/api/fq). ## Recommendation Every recommendation call needs **a reader** — `user_id` or `anonymous_id`. Without one you get `422 "Either user_id or anonymous_id need to be present"`. Most also take an anchor. ```bash More like this article curl -X POST \ "https://api.askmiso.com/v1/recommendation/product_to_products" \ -H "X-Api-Key: YOUR_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "product_id": "wikinews-2911067", "anonymous_id": "visitor-8f3a1c", "rows": 3, "fl": ["title", "url"] }' ``` The three product endpoints answer with the same shape: ```json Response { "message": "success", "data": { "took": 56, "miso_id": "0e4c3ccc-8c86-11f1-…", "products": [ { "product_id": "wikinews-2911067", "title": "Red Hat to move focus away from CentOS in favour of Stream…", "url": "https://example.com/…", "_boosted": false } ] } } ``` | Field | What it is | | --- | --- | | `products` | The recommendations, in order. `fl` decides which fields each one carries. | | `_boosted` | `true` when a boost rule lifted this item. | | `_order_by` | The sort values, when you set your own order. | | `miso_id` | The request id. Send it back on an interaction to attribute the click. | | `took` | Milliseconds. | ### The two that do not return products `user_to_categories` returns the categories a reader leans towards, and a few products for each. **The category is an array**, because it is a path through your hierarchy: ```json user_to_categories { "took": 1295, "miso_id": "1af2d2f6-8c86-11f1-…", "categories": [ { "category": ["Computing"], "total": 0, "recommended_products": [ { "product_id": "wikinews-2911293" } ] } ] } ``` `user_to_attributes` does the same for one field, which you must name: ```json user_to_attributes { "attributes": [ { "value": "Computing", "total": 66, "recommended_products": [ { "product_id": "wikinews-2911067" }, { "product_id": "wikinews-2911293" } ] } ] } ``` `field` is **required** here. Without it the call returns `422 "field required"`. A field that no record carries returns an empty `attributes` list, not an error. **Recommendations improve with interactions.** `user_to_products` and `user_to_trending` read what your readers did. If you send no interactions, the results fall back to popularity. See [Integrating Your Data](/data/integrating-your-data). ## Bulk API — one round trip for a whole page A homepage often needs several units at once. `POST /v1/bulk` runs them together, so the page makes one request: ```bash Bulk curl -X POST "https://api.askmiso.com/v1/bulk" \ -H "X-Api-Key: YOUR_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "requests": [ { "api_name": "recommendation/user_to_trending", "body": { "anonymous_id": "visitor-8f3a1c", "rows": 6 } }, { "api_name": "recommendation/product_to_products", "body": { "product_id": "wikinews-2911067", "anonymous_id": "visitor-8f3a1c", "rows": 6 } } ] }' ``` Each entry needs `api_name` and `body`. Send 1 to 100 of them. Each `body` is the same JSON you post to that endpoint on its own, identity included. **`api_name` is `{engine}/{endpoint}`, with exactly one slash.** A bare endpoint name is rejected before anything runs: ```json api_name: user_to_trending { "status_code": 400, "body": { "message": "API endpoint should be formatted in {engine_type}/{api_name}" } } ``` Bulk carries **engine** APIs, so `recommendation/…` and `search/…` both work, and you can mix them in one call. The GenAI endpoints are not engines. Ask a question with [the Answer API](/api/genai/answer) instead. | `api_name` | Runs | | --- | --- | | `recommendation/user_to_products` | Yes | | `recommendation/user_to_trending` | Yes | | `recommendation/product_to_products` | Yes | | `search/search`, `search/autocomplete` | Yes, once the search engine exists | | `ask/questions` | No. `400 Unknown engine type: ask` | The response wraps each result, in the order you sent them: ```json Response { "errors": false, "data": [ { "error": false, "status_code": 200, "body": { "message": "success", "data": { "took": 56, "miso_id": "…", "products": ["…"] } } } ] } ``` **One failing request does not stop the others**, but it does change the outer status. A batch whose second request is malformed returns **HTTP 422**, with the first result intact: ```json Partial failure { "errors": true, "data": [ { "error": false, "status_code": 200, "body": { "…": "the products" } }, { "error": true, "status_code": 422, "body": { "message": "Request schema error. See \"data.errors\" for details", "data": { "errors": [ { "loc": ["__root__"], "msg": "Either user_id or anonymous_id need to be present" } ] } } } ] } ``` So read `errors` and each `status_code`, not the HTTP status alone. An all-success run returns `200` with `errors: false`. Bulk endpoints carry a tighter rate limit than the rest. See [Errors & Rate Limits](/api/errors). ## Report what the reader did Results get better when Miso sees the outcome. Send an interaction when a reader views or clicks a unit: ```bash Report a click curl -X POST "https://api.askmiso.com/v1/interactions" \ -H "X-Api-Key: YOUR_PUBLISHABLE_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": [ { "type": "product_detail_page_view", "user_id": "u-10293", "product_ids": ["wikinews-2911067"], "timestamp": "2026-06-12T10:15:00Z" } ] }' ``` This is the one endpoint a **publishable** key can reach, so you can call it from the browser. The [Miso SDK](/sdk/overview) does it for you. # MCP — Internal Use Give an AI assistant access to your content. :::::scalar-callout{ type=info } **Which setup?** ::::scalar-grid{ cols=2 } :::scalar-card{ title="Internal Use (this page)" icon="phosphor/regular/plugs-connected" iconPosition="title" } Zero effort. No sign-in. ::: :::scalar-card{ title="For your Subscribers" icon="phosphor/regular/users-three" iconPosition="title" href="/mcp/subscribers" } Subscribers sign in with your existing login. ::: :::scalar-card{ title="MCP Proxy API" icon="phosphor/regular/arrows-left-right" iconPosition="title" href="/mcp/proxy" } Your gateway signs users in. ::: :::scalar-card{ title="Tools API" icon="phosphor/regular/wrench" iconPosition="title" href="/mcp/tools-api" } Your MCP server calls Miso tools. ::: :::: ::::: Miso runs a **Model Context Protocol (MCP)** server. Any assistant that speaks MCP can search your content and read the full text of what it finds. That includes chat assistants such as ChatGPT and Claude, enterprise assistants such as Microsoft 365 Copilot, coding agents such as GitHub Copilot and Cursor, and your own application. Below we connect one assistant, then lock down what it can reach. The **internal** setup uses one credential for your whole app, shared by your own team or one application you control. The assistant gets two tools: 1. A **search tool**, named for your brand. It returns short snippets from many articles at once. 2. A **detail tool**, `get_snippet_detail`. It returns the full text of one snippet. This two-step design keeps the assistant's context small. The assistant scans many short results first. Then it reads in full only what it needs. > **Availability.** Miso enables MCP per app and issues your token. To turn it > on, contact your Miso representative. --- ## How a call travels ```mermaid sequenceDiagram autonumber actor T as Your team participant A as AI Agent participant M as Miso MCP T->>A: Paste your MCP URL once Note over A: The URL carries your publishable key and MCP token T->>A: Ask about your content A->>M: MCP call, with the key and token from the URL Note over M: Miso speaks MCP: search, read, cite M-->>A: The MCP answer Note over M: Usage reported to you, per app ``` There is no sign-in step. Anyone with the URL has access, so give it only to your own team or to one application you control. --- ## Connect Your MCP server URL looks like this: ```text Server URL https://api.askmiso.com/v1/ask/mcp?api_key=YOUR_KEY&token=YOUR_MCP_TOKEN ``` Miso gives you both values. Use your **publishable** API key. The MCP token is the access gate. The transport is **Streamable HTTP** with JSON-RPC 2.0. Most clients call this "HTTP". Every client below reaches the same server and gets the same two tools. | Client | Where you add the server | | --- | --- | | ChatGPT | Settings, then Plugins | | Claude Desktop | Settings, then Connectors | | Claude Code, Codex, Gemini CLI | One terminal command | | GitHub Copilot in VS Code | A JSON file in your project | | Cursor and Windsurf | A JSON file in your project | | Microsoft Copilot | Copilot Studio, or your tenant administrator | | Your own application | Any MCP client library | ### ChatGPT Open **Settings ▸ Security and login** and turn on developer mode. Then open **Plugins**, select the plus button, and add the server URL. Three things to know: - Developer mode runs on the web, for Pro, Plus, Business, Enterprise and Education accounts. - ChatGPT reaches remote servers over streaming HTTP, which is what Miso serves. - ChatGPT accepts a server that carries no authentication of its own, so the key and token in the URL are all it needs. ### Claude Desktop Open **Settings ▸ Connectors ▸ Add custom connector**. Paste the full server URL. ### Claude Code ```bash Add the server claude mcp add --transport http miso \ "https://api.askmiso.com/v1/ask/mcp?api_key=YOUR_KEY&token=YOUR_MCP_TOKEN" ``` Add `--scope project` to write the server into a `.mcp.json` file that you can commit. Add `--scope user` to keep it private to your machine. ### GitHub Copilot in VS Code Put this in `.vscode/mcp.json`, then open Copilot Chat and switch it to agent mode: ```json .vscode/mcp.json { "servers": { "miso": { "type": "http", "url": "https://api.askmiso.com/v1/ask/mcp?api_key=KEY&token=TOKEN" } } } ``` The top-level key here is `servers`. Visual Studio and the Copilot CLI read the same shape from their own locations. ### Cursor and Windsurf Add this to your `mcp.json`: ```json mcp.json { "mcpServers": { "miso": { "type": "http", "url": "https://api.askmiso.com/v1/ask/mcp?api_key=KEY&token=TOKEN" } } } ``` This is the portable shape, and VS Code also reads it from `.mcp.json` at the root of a project. ### Microsoft Copilot Two routes, in two different products. **Copilot Studio** takes the server URL directly. On your agent's **Tools** page, select **Add a tool ▸ New tool ▸ Model Context Protocol**. Fill in a name, a description and the server URL. For authentication choose **API key**, and put the key in a header or a query parameter. Copilot Studio speaks the streamable transport, which is what Miso serves. **Microsoft 365 Copilot** reaches an MCP server through a federated connector. Those are published to Microsoft's Connectors Gallery and approved by Microsoft, then switched on by a tenant administrator. A URL alone does not open this route, so talk to Miso if you want your content in Copilot Chat or the Researcher agent. Access there runs under each signed-in user, and nothing is copied into Microsoft 365. ### Clients that support stdio only Some clients cannot speak HTTP directly. Bridge them with `mcp-remote`: ```bash stdio bridge npx mcp-remote https://api.askmiso.com/v1/ask/mcp \ --header "Authorization: Bearer YOUR_MCP_TOKEN-YOUR_KEY" ``` ### Authentication formats You can authenticate in either of two ways. | Method | How | | --- | --- | | Combined header | `Authorization: Bearer -` | | Separate values | `X-API-Key` and `X-MCP-Token` headers, or the `api_key` and `token` query parameters | The combined header is the simplest form, and most MCP clients expect it. Use the query-parameter form for clients that cannot set headers. Both values are always required. If the token does not match the one Miso issued for your app, the server returns `401`. --- ```mermaid %%{init: {'theme':'base','themeVariables':{ 'fontFamily':'IBM Plex Sans, ui-sans-serif, system-ui','fontSize':'14px', 'actorBkg':'#3148be','actorBorder':'#3148be','actorTextColor':'#ffffff', 'actorLineColor':'#9aa3c0','signalColor':'#9aa3c0','signalTextColor':'#6b7392', 'labelBoxBkgColor':'#f4effc','labelBoxBorderColor':'#cdbcf0', 'labelTextColor':'#40277a','noteBkgColor':'#e8ecfb','noteBorderColor':'#b9c2ea', 'noteTextColor':'#22307a','sequenceNumberColor':'#ffffff' }}}%% sequenceDiagram autonumber participant U as A person participant AI as The AI assistant participant M as Miso MCP U->>AI: asks about your content AI->>M: search tool (question) M-->>AI: short snippets from many articles Note over AI: it scans the previews first AI->>M: get_snippet_detail (product_id, offset from that result) M-->>AI: the full passage Note over M: only ids a search returned are accepted, for one hour AI-->>U: an answer that cites your articles ``` ## The search tool Miso names this tool for your brand, for example `ask_yourbrand`. Your Miso representative confirms the exact name. | Parameter | Type | Required | Notes | | --- | --- | --- | --- | | `question` | string | **yes** | The question to search for. | | `context` | string | no | What the user is working on. Miso adds it to the question. | | `skill_used` | string | no | The name of the skill or template that made the call. Used for analytics only. | | `author` | string | no | Restrict results to one author. Available only if Miso enables it for your app. | > The parameter is `question`, not `query`. A wrong name returns an error. The `author` filter is fuzzy. Partial names, any casing, and small trailing typos all match. But the first letters must be correct. The response reports which author names matched. There is **no** parameter for result count, paging, or filtering. Miso scopes the search to your catalog on the server side. ### What search returns ```json Search result { "query": "interest rate cuts", "results": [ { "product_id": "art-20260612-rates", "product_title": "Central bank signals 2026 cuts", "authors": "A. Reporter", "offset": 1, "snippet_preview": "The central bank said it expects two cuts...", "published_date": "2026-06-12", "url": "https://example.com/markets/rates", "relevance_score": 0.87 } ], "citation_format": "Use markdown links: [product_title](url) by authors" } ``` | Field | What it is | | --- | --- | | `product_id` | Pass this to `get_snippet_detail`. | | `offset` | Pass this to `get_snippet_detail`. A negative value means a whole-work match. | | `snippet_preview` | The first 300 characters, cut on a sentence boundary. | | `relevance_score` | A score from 0 to 1. | | `url` | The citation link. | | `published_date` | Present when the article has a date. | | `child_title` | The chapter or section, when there is one. | | `matched_authors` | Present when you use the `author` filter. | If nothing matches, `results` is empty and the response carries a `message`. --- ## The detail tool: `get_snippet_detail` This is the default name. Miso can rename it for your brand. | Parameter | Type | Required | Notes | | --- | --- | --- | --- | | `product_id` | string | **yes** | From a search result. | | `offset` | integer | **yes** | From the same search result. | | `skill_used` | string | no | Analytics only. | **Call the search tool first.** `get_snippet_detail` only accepts a `product_id` and `offset` that a search returned. Any other value is refused, and Miso records the attempt. A result stays readable for one hour after the search that found it. See [Protecting your content](#protecting-your-content). ### What `get_snippet_detail` returns ```json Detail result { "product_id": "art-20260612-rates", "product_title": "Central bank signals 2026 cuts", "authors": "A. Reporter", "offset": 1, "content": "The full text of the snippet...", "url": "https://example.com/rates", "citation_format": "[Central bank signals cuts](https://ex.com/r)", "citation_instruction": "ALWAYS cite using the markdown link." } ``` The `citation_format` field holds a ready-made markdown link. The assistant is told to cite with it, so the reader can click straight through to your article. --- ## Test the connection Send three JSON-RPC calls: `initialize`, `tools/list`, then `tools/call`. Replace the tool name with your own. ```bash cURL BASE=https://api.askmiso.com/v1/ask/mcp AUTH="Authorization: Bearer YOUR_MCP_TOKEN-YOUR_KEY" CT="Content-Type: application/json" # 1. initialize curl -X POST "$BASE" -H "$AUTH" -H "$CT" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {} }' # 2. list the tools curl -X POST "$BASE" -H "$AUTH" -H "$CT" \ -d '{ "jsonrpc": "2.0", "id": 2, "method": "tools/list" }' # 3. run a search curl -X POST "$BASE" -H "$AUTH" -H "$CT" \ -d '{ "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "ask_yourbrand", "arguments": { "question": "Rate outlook?" } } }' ``` ```javascript Node.js const BASE = "https://api.askmiso.com/v1/ask/mcp"; const HEADERS = { Authorization: `Bearer ${MCP_TOKEN}-${API_KEY}`, "Content-Type": "application/json", }; async function rpc(method, params = {}, id = 1) { const res = await fetch(BASE, { method: "POST", headers: HEADERS, body: JSON.stringify({ jsonrpc: "2.0", id, method, params }), }); return res.json(); } await rpc("initialize"); const tools = await rpc("tools/list", {}, 2); const hit = await rpc("tools/call", { name: "ask_yourbrand", arguments: { question: "What changed in the rate outlook?" }, }, 3); ``` ```python Python import requests BASE = "https://api.askmiso.com/v1/ask/mcp" HEADERS = { "Authorization": f"Bearer {MCP_TOKEN}-{API_KEY}", "Content-Type": "application/json", } def rpc(method, params=None, id=1): body = {"jsonrpc": "2.0", "id": id, "method": method, "params": params or {}} return requests.post(BASE, headers=HEADERS, json=body).json() rpc("initialize") tools = rpc("tools/list", id=2) hit = rpc("tools/call", { "name": "ask_yourbrand", "arguments": {"question": "What changed in the rate outlook?"}, }, id=3) ``` `tools/list` shows the two tools available to your app. If the search tool is missing, MCP is not yet enabled for your key. --- ## Protecting your content An MCP server gives an AI assistant access to your archive. Miso controls that access at four levels. ### Snippets are not addressable This is the main protection. `get_snippet_detail` does **not** accept any `product_id` you choose. It only returns a snippet that a search **already returned to you**, and only for one hour after that search. The result: - Nobody can enumerate your catalog by guessing or incrementing ids. - Nobody can walk through a whole article by stepping the `offset`. - Every full-text read must follow a real search that surfaced that exact passage. - Access to a passage expires one hour after the search that found it. Bulk extraction therefore needs thousands of genuine searches. Each one is slow, is charged, and is recorded. Miso records every refused read as well as every successful one. A client that probes for content it was never shown is visible in your usage data. See [Usage and analytics](#usage-and-analytics). ### Requests from data centers are blocked Miso blocks traffic from cloud and hosting providers, from known scraper networks, and from selected regions. This stops most scripted extraction, because that traffic rarely comes from a home or office connection. ### Rate limits and IP restrictions Miso can cap how many MCP calls your app accepts, and can restrict MCP access to your own IP ranges. Both are useful when only your staff or one internal application uses the server. Contact your Miso representative to set them up. ### Your credentials control access Both an API key and your app's MCP token are required, and the token is specific to your app. If a credential leaks, ask Miso to rotate the token. Every client that uses it loses access immediately. Treat the server URL as a secret. It carries both values. --- ## Usage and analytics Miso records every MCP call. Ask your Miso representative for a report, or for access to the usage data. ### What Miso records | Call | What is stored | | --- | --- | | Search | The question, the optional `context` and `author`, the `skill_used` tag, and how long the call took. | | Full-text read | The article id, the passage offset, whether the read was allowed, the size of the passage served, and a short excerpt of it. | Miso stores the **length and a short excerpt** of each passage it serves, not the whole passage. ### What you can measure - **Volume.** Searches and full-text reads per day, and the trend over time. - **What people ask.** The questions assistants send to your content. - **The read-through funnel.** Miso links each full-text read back to the search that surfaced it. You can therefore measure how many searches lead to a read, and how many results an assistant reads per search. - **Which content gets used.** The articles that assistants read most, and how much of each one they read. - **Refused reads.** Attempts to fetch a passage that no search returned. A rise here suggests someone is probing your archive. - **Speed.** How long searches take for your catalog. ### Tag your own traffic Pass `skill_used` on any call to label where it came from: a named workflow, a prompt template, or one internal application. Miso records the value, so you can split your usage report by it. ```json Tagged call { "name": "ask_yourbrand", "arguments": { "question": "What changed in the rate outlook?", "skill_used": "morning-briefing" } } ``` ### One limitation MCP reporting is **per app**. MCP clients do not send an end-user identity, so Miso cannot break usage down by seat or by reader. If you need per-user reporting, talk to your Miso representative about the options. --- ## Notes and limits - **Errors return HTTP 200.** JSON-RPC reports failures in the response body, not in the status code. Read the `error` field, and read `isError` on a tool result. - **Both tools are read-only.** They carry the read-only annotation, so clients can let a user approve them once. - **Search takes a few seconds.** Half of searches complete in about 6 seconds. Reading a snippet is almost instant. - **Results are scoped to your catalog.** The assistant cannot reach content outside it. - **One URL serves every brand.** Your API key decides which brand's tool appears, so keep your key and token together. An address on your own domain is a separate setup. See [Your MCP address](/mcp/subscribers#your-mcp-address). --- ## Next - [Your MCP address](/mcp/subscribers#your-mcp-address) — an address on your own domain, with an install page and a skill. - [Tools API](/mcp/tools-api) — the same tools as plain HTTP, for a server you run yourself. - [MCP — for your Subscribers](/mcp/subscribers) — per-subscriber sign-in. # MCP — for your Subscribers Let your subscribers connect their own AI agent, on your login. :::::scalar-callout{ type=info } **Which setup?** ::::scalar-grid{ cols=2 } :::scalar-card{ title="Internal Use" icon="phosphor/regular/plugs-connected" iconPosition="title" href="/mcp/internal" } Zero effort. No sign-in. ::: :::scalar-card{ title="For your Subscribers (this page)" icon="phosphor/regular/users-three" iconPosition="title" } Subscribers sign in with your existing login. ::: :::scalar-card{ title="MCP Proxy API" icon="phosphor/regular/arrows-left-right" iconPosition="title" href="/mcp/proxy" } Your gateway signs users in. ::: :::scalar-card{ title="Tools API" icon="phosphor/regular/wrench" iconPosition="title" href="/mcp/tools-api" } Your MCP server calls Miso tools. ::: :::: ::::: Let each of your subscribers connect **their own** AI agent to your content, tied to their existing login and their plan. Usage comes back to you per subscriber and per tier. Below we show the address your subscribers connect to and what it gives them, then run the sign-in once, from the agent to your site and back. Miso runs the OAuth exchange with the AI agent. Your site provides the login and, on the way back, a signed token that proves who the subscriber is. --- ## Try one Miso runs a public host you can connect to right now. It carries the Wikinews archive, and it is built the same way as yours: ```text The demo host https://wikinews.mcp.miso.ai ``` Open it in a browser to see the install page. In Claude Code, two commands give you the connection and the skill: ```bash Install the demo /plugin marketplace add https://wikinews.mcp.miso.ai/marketplace.json /plugin install wikinews-mcp-plugin@wikinews ``` Sign in with an email address on first use. Access lasts 30 days. Then ask your assistant something the archive covers, such as what happened at the 2012 Olympics opening ceremony, and watch it search, read the full article, and cite it. Every path in [What a Miso MCP server host serves](#what-a-miso-mcp-server-host-serves) answers on that host, so you can also open `/llms.txt` or `/marketplace.json` and read what a client reads. > A Miso product demo, with content from Wikinews under CC BY 2.5. It is not > affiliated with Wikinews or the Wikimedia Foundation. The archive runs > through 2013. --- ## Your MCP address Your subscribers do not paste a Miso URL or hold a key. They connect to a host that carries your name, and sign in there. The host can be a Miso subdomain, or a name on your own domain. | Shape | Example | What you do | | --- | --- | --- | | Miso subdomain | `your-site.mcp.miso.ai` | Nothing. Miso runs the DNS. | | Your own domain | `mcp.your-site.com` | Point a CNAME at Miso. | Your own domain is the one to pick when subscribers will see the address. It keeps your brand on the connection, in the assistant's settings screen, and in the sign-in prompt. Any shape of name works: a subdomain, a deep subdomain, or your apex domain. Miso maps the host to your content when the host is set up. A name that was never declared returns `404`, so no other address can serve your content. The endpoint your subscribers connect to is `/mcp` on that host: ```text The MCP endpoint https://mcp.your-site.com/mcp ``` --- ## What a Miso MCP server host serves Miso runs the host. These answer on it from the day it is set up. Each path below links to the live demo host, so you can open it and read what a client reads. | Path | What it is | | --- | --- | | [`/`](https://wikinews.mcp.miso.ai/) | The install page. A reader picks their assistant and copies one command. | | [`/mcp`](https://wikinews.mcp.miso.ai/mcp) | The MCP endpoint. Your subscribers sign in here. | | [`/marketplace.json`](https://wikinews.mcp.miso.ai/marketplace.json) | The plugin catalog, for a one-command install in Claude Code. | | [`/plugin.zip`](https://wikinews.mcp.miso.ai/plugin.zip) | The plugin itself: the connection and the skill together. | | [`/skills.zip`](https://wikinews.mcp.miso.ai/skills.zip) | The skill on its own, for every other assistant. | | [`/llms.txt`](https://wikinews.mcp.miso.ai/llms.txt) | A plain-text index of all of the above, for an agent that lands on the host. | | [`/.well-known/…`](https://wikinews.mcp.miso.ai/.well-known/oauth-protected-resource/mcp) | The sign-in metadata a client reads before it connects. | Two of those links download a file, and `/mcp` answers `405` in a browser. The endpoint speaks JSON-RPC over POST, and answering a browser GET that way is what the transport specification asks for. You build none of these. The content carries your brand name and your tool names. --- ## What your subscribers install ### The install page `https://mcp.your-site.com/` is a page you can send to a subscriber, or link from your account settings. It shows your name, what the connection gives them, and a tab for each assistant: Claude Code, Cursor, Codex, Gemini CLI, Claude Desktop and ChatGPT. Each tab holds the exact command for that client. The page has two halves. The first installs the plugin, which is the connection and the skill in one step. The second connects the endpoint on its own, for a reader who wants the tools and no more. ### The plugin, and what is in it In Claude Code, two commands install everything: ```bash Install the plugin /plugin marketplace add https://mcp.your-site.com/marketplace.json /plugin install your-site-mcp-plugin@your-site ``` That install carries two pieces: **The connection.** The MCP endpoint, already pointed at your host, so the reader types no URL and pastes no key. They sign in on first use. **A skill.** A short set of instructions that loads into the assistant alongside your tools. It teaches the assistant how to get good answers from your archive: search before answering, rephrase and try again when the first search misses, open the full article when detail matters, and cite the title and URL of everything it used. It also states what your archive does not cover, so the assistant says so rather than inventing an answer. The skill is the part that changes answer quality. A connection alone gives an assistant your tools. The skill tells it how you want them used. ### Every other assistant The one-command install is specific to Claude Code. Every other assistant loads the same skill from a folder, so the host serves it as a plain archive: ```bash Add the skill curl -sL https://mcp.your-site.com/skills.zip -o /tmp/skill.zip unzip -o /tmp/skill.zip -d ~/.cursor/skills/ ``` The archive holds the skill folders at its top level, so it unzips straight into the assistant's skills directory. Change the last path for the client in front of you: `~/.cursor/skills/` for Cursor, `~/.agents/skills/` for Codex, `~/.gemini/skills/` for Gemini CLI. In ChatGPT, download the file and upload it under Plugins. The endpoint is added separately in those clients, with one command: ```bash Connect the endpoint codex mcp add your-site --url https://mcp.your-site.com/mcp ``` The install page carries the version of this for each client, so a subscriber copies rather than adapts. ### The index for agents `https://mcp.your-site.com/llms.txt` describes the host in plain text: what the archive covers, where the install page is, the endpoint URL, the plugin commands, and the name and purpose of each tool. An agent that is handed your host and no instructions reads this file and knows what to do with it. --- ## The round-trip ```mermaid sequenceDiagram autonumber actor S as Subscriber participant A as AI Agent participant M as Miso participant Y as Your site S->>A: Click "Authenticate" A->>M: Reach the Miso OAuth endpoint M-->>S: Redirect to your sign-in Note over S,Y: These two steps happen on your site S->>Y: Sign in, and enable MCP for this plan Y-->>M: Redirect back with a signed JWT M->>M: Verify the assertion (HS256, your key) M-->>A: Issue an OAuth access token A->>M: MCP requests with that token Note over M,Y: Usage reported to you, by subscriber and tier ``` ## What your site needs You do not need to build an identity provider. If you have a login and can sign a token, you have the pieces. Three things: **1. A sign-in page Miso can redirect to.** Miso sends the subscriber to your login with two query parameters — a `state` and the `callback` URL to return to. The subscriber signs in with their existing account. You confirm that their plan includes MCP. **2. A redirect back with a signed assertion.** Send the subscriber to the `callback` carrying a short-lived JWT. Sign it with **your Miso secret key** (HS256). That shared secret is how Miso knows the assertion came from you. **3. The right claims in that assertion.** | Claim | What it is | | --- | --- | | `sub` | A stable subscriber id. Who the access is for. | | `access_exp` | How long MCP access stays valid. | | `state` | Echo the `state` Miso sent you. This blocks CSRF. | | `aud` | The audience: `https://api.askmiso.com`. | | `exp` | The lifetime of this assertion. Keep it under 5 minutes. | | `tier` | Optional. The plan tier, to segment your usage reports. | ## What your sign-in page receives ```text Redirect in GET https://your-site.com/login ?state=Yk3f...opaque &callback=https://api.askmiso.com/v1/ask/oauth/callback ``` ## Signing the assertion After the subscriber signs in, and after you confirm their entitlement, sign a short-lived assertion and redirect them back. ```python Python import time, jwt # pip install pyjwt from urllib.parse import urlencode def redirect_back(state, callback, subscriber_id, tier): now = int(time.time()) assertion = jwt.encode( { "sub": subscriber_id, # stable subscriber id "aud": "https://api.askmiso.com", "state": state, # echo Miso's state "exp": now + 120, # keep this short "access_exp": now + 30 * 24 * 3600, "tier": tier, # optional, for reports }, MISO_SECRET_API_KEY, # your Miso secret key algorithm="HS256", ) params = {"state": state, "assertion": assertion} return redirect(f"{callback}?{urlencode(params)}") ``` ```javascript Node.js import jwt from "jsonwebtoken"; // npm i jsonwebtoken function redirectBack(res, state, callback, subscriberId, tier) { const now = Math.floor(Date.now() / 1000); const assertion = jwt.sign( { sub: subscriberId, // stable subscriber id aud: "https://api.askmiso.com", state, // echo Miso's state exp: now + 120, // keep this short access_exp: now + 30 * 24 * 3600, tier, // optional, for reports }, MISO_SECRET_API_KEY, // your Miso secret key { algorithm: "HS256" } ); const params = new URLSearchParams({ state, assertion }); return res.redirect(`${callback}?${params}`); } ``` ```php PHP $subscriber_id, // stable subscriber id 'aud' => 'https://api.askmiso.com', 'state' => $state, // echo Miso's state 'exp' => $now + 120, // keep this short 'access_exp' => $now + 30 * 24 * 3600, 'tier' => $tier, // optional, for reports ], MISO_SECRET_API_KEY, // your Miso secret key 'HS256' ); $q = http_build_query([ 'state' => $state, 'assertion' => $assertion, ]); header("Location: {$callback}?{$q}"); exit; } ``` ```ruby Ruby require "jwt" # gem install jwt def redirect_back(state, callback, subscriber_id, tier) now = Time.now.to_i assertion = JWT.encode( { sub: subscriber_id, # stable subscriber id aud: "https://api.askmiso.com", state: state, # echo Miso's state exp: now + 120, # keep this short access_exp: now + 30 * 24 * 3600, tier: tier # optional, for reports }, MISO_SECRET_API_KEY, # your Miso secret key "HS256" ) query = URI.encode_www_form(state: state, assertion: assertion) redirect_to "#{callback}?#{query}" end ``` That is the whole integration on your side. Miso handles discovery, PKCE, and the token exchange with the agent. ## Who does what | Step | Your site | Miso | | --- | --- | --- | | Start | — | Receives the agent and begins OAuth. | | Sign-in | Login, and enable MCP for the plan. | Redirects the subscriber to you. | | Hand-back | Redirect back with a signed JWT. | Verifies the JWT. | | Token | — | Issues the access token to the agent. | | Reporting | Receives usage reports. | Attributes usage from your claims. | --- ## The tools your subscribers get Once connected, a subscriber's agent sees two tools. They are the same two the internal setup gets, and they work the same way here. ### The search tool Named for your brand, for example `ask_yourbrand`. | Parameter | Type | Required | Notes | | --- | --- | --- | --- | | `question` | string | **yes** | The question to search for. | | `context` | string | no | What the subscriber is working on. Miso adds it to the question. | | `skill_used` | string | no | The skill or template that made the call. Analytics only. | | `author` | string | no | Restrict results to one author. Available when Miso enables it for your app. | The agent sends a question in the subscriber's own words. Back come ranked passages from your archive: ```json Search result { "query": "interest rate cuts", "results": [ { "product_id": "art-20260612-rates", "product_title": "Central bank signals 2026 cuts", "authors": "A. Reporter", "offset": 1, "snippet_preview": "The central bank said it expects two cuts...", "published_date": "2026-06-12", "url": "https://example.com/markets/rates", "relevance_score": 0.87 } ], "citation_format": "Use markdown links: [product_title](url) by authors" } ``` Each result carries what an answer needs to cite you: the headline, the date, and the URL that sends the reader back to your page. There is no parameter for result count, paging or filtering. Miso scopes every search to your catalog on the server side. ### The detail tool: `get_snippet_detail` This is the default name. Miso renames it for your brand on request. | Parameter | Type | Required | Notes | | --- | --- | --- | --- | | `product_id` | string | **yes** | From a search result. | | `offset` | integer | **yes** | From the same search result. | | `skill_used` | string | no | Analytics only. | It returns the full text of one passage, plus a ready-made markdown link in `citation_format` that the agent is told to cite with. The two tools are a pair, and the order is enforced. `get_snippet_detail` accepts only a `product_id` and `offset` that a search returned, and a result stays readable for one hour after the search that found it. An agent therefore reads your archive one passage at a time, in response to a real question. See [MCP — Internal Use](/mcp/internal) for the full field list and the content protections that apply to both tools. --- ## Getting set up Miso sets up the host and the sign-in with you, in one short working session with your engineers. Together you agree: 1. **The name.** A Miso subdomain needs nothing from you. Your own domain needs a CNAME record, which Miso gives you. 2. **The wording.** Your brand name, what the archive covers, the tool names, and anything you want the assistant told about your content. 3. **The sign-in.** Your login URL, the signing key, and how you map a signed-in user to a subscriber id and tier. Most publishers pilot it on a single tier first. Contact your Miso representative. --- ## Next - [MCP — Internal Use](/mcp/internal) — one credential for your own team. - [Tools API](/mcp/tools-api) — run the same tools inside a server you own. # MCP Proxy API Your gateway handles sign-in. Miso handles MCP. :::::scalar-callout{ type=info } **Which setup?** ::::scalar-grid{ cols=2 } :::scalar-card{ title="Internal Use" icon="phosphor/regular/plugs-connected" iconPosition="title" href="/mcp/internal" } Zero effort. No sign-in. ::: :::scalar-card{ title="For your Subscribers" icon="phosphor/regular/users-three" iconPosition="title" href="/mcp/subscribers" } Subscribers sign in with your existing login. ::: :::scalar-card{ title="MCP Proxy API (this page)" icon="phosphor/regular/arrows-left-right" iconPosition="title" } Your gateway signs users in. ::: :::scalar-card{ title="Tools API" icon="phosphor/regular/wrench" iconPosition="title" href="/mcp/tools-api" } Your MCP server calls Miso tools. ::: :::: ::::: Your users connect their assistant to an address you run. Your gateway signs them in, then passes each MCP call to Miso with your Secret API Key. Miso speaks the MCP protocol: it reads the call, runs the search, and answers in MCP. Your gateway hands that answer straight back. Below we build the gateway. The split is what sets this setup apart from the [Tools API](/mcp/tools-api). There, your own MCP server speaks the protocol and calls Miso for search. Here, your gateway decides who gets in, and Miso does everything after that. > **Your Secret API Key stays on your server.** This page is for a gateway you > run. Never put the secret key into an agent, an MCP URL, or a browser. To give > people a URL they can paste into an assistant, use > [MCP — Internal Use](/mcp/internal) or > [MCP — for your Subscribers](/mcp/subscribers) instead. --- ## How a call travels ```mermaid sequenceDiagram autonumber actor U as Your user participant A as AI Agent participant G as Your gateway participant M as Miso MCP Proxy U->>A: Ask about your content A->>G: MCP call, with your user's own credential Note over G: Your sign-in decides who gets through G->>M: The same MCP call, plus Secret API Key, user id and filter Note over M: Miso speaks MCP: search, read, cite M-->>G: The MCP answer for that user and filter G-->>A: Passed straight back Note over M: Usage reported to you, per user your gateway names ``` The proxy suits a pass-through. Every MCP call is one JSON-RPC POST that answers with JSON. There is no session to carry and nothing streams on the POST, so your gateway forwards the body as it is and adds three things. --- ## What your gateway adds | What | Where | Notes | | --- | --- | --- | | Your Secret API Key | `Authorization: Bearer `, or the `X-API-Key` header | No MCP token. The secret key opens the proxy alone. | | The user | `X-MCP-User-Id` header, or `?user_id=` | Optional. Accepted only with the secret key. The header wins when both are sent. | | A filter | `?fq=` on the URL | Optional. Narrows what this call can search. | The proxy's address is the same endpoint every MCP client uses: ```text Endpoint POST https://api.askmiso.com/v1/ask/mcp ``` All three ride outside the JSON-RPC body. The body belongs to the protocol, and the tool arguments inside it belong to the assistant, which fills them in. A `user_id` or `fq` at the top level of the body is refused with a message naming where it goes. --- ## Tell Miso who the user is Send your own id for the user on every call: ```text User header X-MCP-User-Id: user-123 ``` Miso records it beside every search and every full-text read, so your usage report splits by user. Use an opaque id rather than an email address. It can be up to 256 characters, with no control characters. The user id is your assertion. Miso trusts it because it arrives with your secret key, which only your server holds. With a publishable key the call is refused with `401`. --- ## Narrow what a call can search Add a filter in Lucene syntax as `?fq=`: ```text Filter POST https://api.askmiso.com/v1/ask/mcp?fq=tags:public ``` The filter can only narrow. Miso adds it as one clause and keeps its own filter for your app on top, so a call never reaches content your app's setup excludes. Your gateway chooses the filter per call, so it can give each user the slice their plan allows. Brackets must open and close within the filter, and phrases and regular expressions must close. A filter that breaks either rule, ends with a backslash, or runs past 2,000 characters is refused with `400` before any search runs. `?type=` still works beside it, and the two combine. --- ## Full text follows the same rules An AI agent reads your content in two steps: 1. It calls the search tool, for example `ask_yourbrand`, and gets back short passages. 2. It calls the detail tool, `get_snippet_detail` by default, for the full text of one of those passages. Miso returns the full text only when both calls match. They must carry the same user id, the same `?fq=` and the same `?type=`, and the search must be less than one hour old. | `get_snippet_detail` call | Result | | --- | --- | | Same user, same filter, within the hour | The full text. | | A different user | Refused. | | A different filter or type | Refused. | | More than one hour after the search | Refused. Search again. | This keeps your filter in force for full text. A user cannot read a passage that only another user's search found. Your gateway needs no extra work for this. It already sends the same user id and filter on every call from one user. --- ## The gateway In the following gateway, we sign the user in, pick their filter, and forward the call: ```python gateway.py lineNumbers import os import httpx from fastapi import FastAPI, HTTPException, Request from fastapi.responses import JSONResponse MISO_MCP = "https://api.askmiso.com/v1/ask/mcp" MISO_SECRET_API_KEY = os.environ["MISO_SECRET_API_KEY"] app = FastAPI() client = httpx.AsyncClient(timeout=60) def sign_in(request: Request) -> dict: """Your own check. Return the user, or raise.""" user = your_auth.user_from(request) # whatever your site already uses if not user: raise HTTPException(401, "Sign in first") return user @app.post("/mcp") async def mcp(request: Request) -> JSONResponse: user = sign_in(request) reply = await client.post( MISO_MCP, params={"fq": "tags:public"} if user["plan"] == "free" else {}, headers={ "Authorization": f"Bearer {MISO_SECRET_API_KEY}", "X-MCP-User-Id": user["id"], }, json=await request.json(), ) return JSONResponse(reply.json(), status_code=reply.status_code) ``` `your_auth.user_from` stands for whatever your site already does to recognise a signed-in user: a session cookie, a token, or your auth library. --- ## When something is refused | Status | Message | Cause | | --- | --- | --- | | `401` | `MCP token required` | A publishable key with no MCP token. Use the secret key. | | `401` | `Invalid MCP token` | A token was sent and it is not this app's. With the secret key, send no token. | | `401` | `MCP is not enabled for this app` | MCP is not set up for this app. Contact Miso. | | `401` | `A user id is only accepted with the secret API key` | A user id arrived with a publishable key. | | `400` | Names the problem with the filter | A bracket, phrase or regular expression does not close. Or the filter ends with a backslash, or is too long. | | `200`, JSON-RPC error | Names the header or parameter | `user_id` or `fq` was sent in the body. | --- ## Next - [Tools API](/mcp/tools-api) — when your own MCP server speaks the protocol and calls Miso for search. - [MCP — Internal Use](/mcp/internal) — the search tool and `get_snippet_detail` in full. # Tools API You host the MCP server. Miso does the searching. :::::scalar-callout{ type=info } **Which setup?** ::::scalar-grid{ cols=2 } :::scalar-card{ title="Internal Use" icon="phosphor/regular/plugs-connected" iconPosition="title" href="/mcp/internal" } Zero effort. No sign-in. ::: :::scalar-card{ title="For your Subscribers" icon="phosphor/regular/users-three" iconPosition="title" href="/mcp/subscribers" } Subscribers sign in with your existing login. ::: :::scalar-card{ title="MCP Proxy API" icon="phosphor/regular/arrows-left-right" iconPosition="title" href="/mcp/proxy" } Your gateway signs users in. ::: :::scalar-card{ title="Tools API (this page)" icon="phosphor/regular/wrench" iconPosition="title" } Your MCP server calls Miso tools. ::: :::: ::::: Use the Tools API when you run your own MCP server and want Miso search as one of its tools. Your server keeps the transport, the tool names and the sign-in. Miso answers two HTTP calls: - `GET /v1/ask/mcp/tools` lists the tools. - `POST /v1/ask/mcp/tools/{name}` runs one tool. The search tool takes a question in the words of a reader. It returns ranked passages from your archive, and each passage has a title, a date and a URL to cite. Below we make both calls, then put them inside a working MCP server. --- ## How a call travels ```mermaid sequenceDiagram autonumber actor U as Your user participant A as AI Agent participant S as Your MCP server participant M as Miso Tools API U->>A: Ask about your content A->>S: MCP call, with your user's own credential Note over S: Your server signs the user in and speaks MCP S->>M: GET /v1/ask/mcp/tools, then POST /v1/ask/mcp/tools/{name} Note over M: Secret API Key. Miso runs the search M-->>S: JSON: ranked passages with title, date and URL S-->>A: Your server wraps the result as an MCP answer ``` Your server owns both sign-in and the MCP protocol. Miso sees plain HTTP calls and returns JSON. --- ## The two calls | Call | What it gives you | | --- | --- | | `GET /v1/ask/mcp/tools` | Every tool your app exposes, with a JSON Schema for its arguments. | | `POST /v1/ask/mcp/tools/{name}` | The result of running one tool. | Both live on `https://api.askmiso.com`. Both take your **Secret API Key**, in either header: ```text Authentication X-API-Key: YOUR_SECRET_API_KEY Authorization: Bearer YOUR_SECRET_API_KEY ``` Without a key the reply is `401`. The key is a server credential, so these calls belong on your back end. --- ## List the tools ```bash List curl -s https://api.askmiso.com/v1/ask/mcp/tools \ -H "X-API-Key: YOUR_SECRET_API_KEY" ``` ```json Response { "tools": [ { "name": "ask_your_site", "description": "Search the Your Site archive — news, analysis and reference.", "input_schema": { "type": "object", "properties": { "question": { "type": "string" } }, "required": ["question"] } }, { "name": "get_your_site_article", "description": "Get the full text of a specific snippet returned by ask_your_site.", "input_schema": { "type": "object", "properties": { "product_id": { "type": "string" }, "offset": { "type": "integer" } }, "required": ["product_id", "offset"] } } ], "version": "1.0.0" } ``` Two tools come back. A **search tool**, named for your brand, and a **detail tool** that returns the full text of one result. The names and descriptions are the ones Miso set up with you, so `ask_your_site` above stands for your own tool name. `input_schema` is JSON Schema. Hand it to your MCP server as the tool's schema rather than retyping it, and a change Miso makes reaches your agent on your next start. --- ## Run a tool Arguments go in an `arguments` object: ```bash Search curl -s https://api.askmiso.com/v1/ask/mcp/tools/ask_your_site \ -H "X-API-Key: YOUR_SECRET_API_KEY" \ -H "Content-Type: application/json" \ -d '{"arguments": {"question": "What happened at the 2012 Olympics opening ceremony?"}}' ``` ```json Response { "success": true, "result": "{\"query\": \"...\", \"results\": [ ... ], \"citation_format\": \"...\"}" } ``` **`result` is a string.** It holds JSON, so parse it once more before you read it. Returning it as a string is what an MCP client expects to receive, so a server that passes it straight through needs no parsing at all. Inside, a search result carries the fields your agent cites from: | Field | What it is | | --- | --- | | `product_id` | The article. Pass it back to `get_snippet_detail`. | | `offset` | Which passage of that article matched. `get_snippet_detail` needs it too. | | `product_title` | The headline, for the citation. | | `url` | Where the citation points. | | `published_date` | The date, for recency questions. | | `snippet_preview` | The passage that matched, to show or to judge relevance. | | `relevance_score` | How well it matched, between 0 and 1. | `get_snippet_detail` takes `product_id` and `offset` from a result and returns the same fields plus `content`, the full text. --- ## Wrap them in your server The whole integration is one function that forwards a call, plus one tool declaration for each Miso tool. In the following server, we expose both tools under our own names: ```python server.py lineNumbers import os, requests from mcp.server.mcpserver import MCPServer MISO_BASE = "https://api.askmiso.com/v1/ask/mcp/tools" HEADERS = {"X-API-Key": os.environ["MISO_SECRET_API_KEY"]} mcp = MCPServer("your-site") def call_miso(name, arguments): response = requests.post( f"{MISO_BASE}/{name}", headers=HEADERS, json={"arguments": arguments}, timeout=60 ) response.raise_for_status() body = response.json() if not body["success"]: raise RuntimeError(body["error"]) return body["result"] @mcp.tool() def search(question: str) -> str: """Search our archive. Returns snippets with titles, dates and URLs.""" return call_miso("ask_your_site", {"question": question}) @mcp.tool() def get_article(product_id: str, offset: int) -> str: """Return the full text of one result from search.""" return call_miso("get_your_site_article", {"product_id": product_id, "offset": offset}) if __name__ == "__main__": mcp.run() ``` Your agent now sees `search` and `get_article` on your server. The tools keep Miso's behaviour, and the name, the description and the transport are yours. Your key stays on your server, and your subscribers never hold a Miso credential. Access is yours to control: put your own API key or your own sign-in in front of this server, and it decides who gets in. --- ## Narrow a connection to content types Add `type=` to either call, and the tools answer only from those content types. The value is a comma-separated list, matched exactly as your content is indexed: ```bash Courses and services only curl -s "https://api.askmiso.com/v1/ask/mcp/tools?type=COURSE,SERVICE" \ -H "X-API-Key: YOUR_SECRET_API_KEY" ``` Send the same parameter on the call that runs a tool. A listing narrowed this way also says so in the tool description, so the agent knows what it is searching. This is how one app serves two servers: a wide one for your own team, and a narrow one for a customer-facing agent. --- ## Narrow a call with a filter Add a filter in Lucene syntax as `?fq=` on the call that runs a tool: ```bash Public content only curl -s "https://api.askmiso.com/v1/ask/mcp/tools/ask_your_site?fq=tags:public" \ -H "X-API-Key: YOUR_SECRET_API_KEY" \ -H "Content-Type: application/json" \ -d '{"arguments": {"question": "What changed in the 2024 rules?"}}' ``` The filter can only narrow. Miso adds it as one clause and keeps its own filter for your app on top, so a call never reaches content that your app excludes. Your server chooses the filter for each call. For example, it can give each user only the content that their plan allows. Brackets must open and close within the filter, and phrases and regular expressions must close. If a filter breaks one of these rules, ends with a backslash, or is longer than 2,000 characters, the call is refused with `400`. No search runs. `?type=` still works beside `?fq=`, and the two combine. The listing call reads `?type=` only. `?fq=` changes the results, and the tool descriptions stay the same. --- ## Tell Miso who the user is Send your own id for the user on the call that runs a tool: ```text User header X-MCP-User-Id: user-123 ``` You can also send it as `?user_id=`. If you send both, the header wins. Miso records the id with each search and each full-text read, so your usage report splits by user. Use an opaque id, such as a database key, and do not use an email address. The id can be up to 256 characters, with no control characters. The user id is your assertion. Miso accepts it only with your Secret API Key. With a publishable key, the call is refused with `401`. Put `?fq=` on the URL and the user id in the header. If you put `fq` or `user_id` next to `arguments` in the body, the call is refused with `400`. The error message tells you where the value goes. --- ## Full text follows the same rules `get_snippet_detail` returns the full text of a result only when the two calls match. The call to `get_snippet_detail` must have the same user id, the same `?fq=` and the same `?type=` as the search that returned the result. The search must also be less than one hour old. If one of these is different, the call still answers `"success": true`, but `result` holds `"error": "Snippet not accessible"`. Search again with the same parameters. In the server above, add the parameters in `call_miso`, so that both tools send them. --- ## When something fails | What you get | What happened | | --- | --- | | `400` | `?fq=` is not valid, or `fq` or `user_id` is in the body. `detail` says which. | | `401` | No key, a key that is not this app's secret key, or a user id with a publishable key. | | `404` with `Tool not found` | The tool name is not one from the listing. | | `200` with `"success": false` | The tool ran and failed. `error` says why. | The third one is the one to handle deliberately. A missing required argument arrives here, with `success: false` and a message naming the argument. Raise it as a tool error in your server so the agent can correct itself and try again. --- ## Next - [MCP — for your Subscribers](/mcp/subscribers#your-mcp-address) — a Miso-run server on your own domain. - [MCP — Internal Use](/mcp/internal) — connect a client with no server of your own. - [MCP — for your Subscribers](/mcp/subscribers) — per-subscriber sign-in. # Answer Metrics (Dojo) See how many questions your readers ask, how Miso answers them, and what readers do next. **Answers ▸ Metrics** in [Dojo](https://dojo.askmiso.com/) shows this data as charts. The charts count every question that your readers ask on your site. They do not count Hybrid Search answers or the test requests of Miso. ![The top of the Metrics page, with four pie charts. The button that opens the filter pane is at the top left.](/images/dojo-metrics-overview.png) ## Change the time range By default, the charts show the last month. The time range applies to all charts except the retention table. ![The Filters pane, with the Time Range field.](/images/Dojo-metrics-2.png) 1. Select the filter button at the top left of the charts. The **Filters** pane opens. 2. Select the **Time Range** field. The **Edit time range** window opens. 3. Select a **Range type**, then set the period. 4. Select **Apply**. 5. Select **Apply filters** at the bottom of the pane. To go back to the last month, select **Clear all** in the pane. | Range type | What you set | Example | | --- | --- | --- | | **Last** | **Last day**, **Last week**, **Last month**, **Last quarter**, or **Last year**. The period ends today. | **Last week** is the 7 days before today. | | **Previous** | A calendar period before the current one. | The previous calendar month. | | **Custom** | A start and an end. Each one is a date, or a date relative to today. | From **7 Days Before** to today. | | **Advanced** | A start and an end, as text. | From `7 days ago` to `today`. | | **No filter** | Nothing. | All the data that Miso has. | Under **Actual time range**, the window shows the dates of the period. The period includes the start date. It does not include the end date. ![The Range type list in the Edit time range window, with Custom selected.](/images/Dojo-metrics-3.png) ![A custom range from 7 days before to a fixed end date.](/images/Dojo-metrics-4.png) ## Find a chart The charts are in five groups on this page. | Group | Your question | Section | | --- | --- | --- | | Volume | How many questions do readers ask? | [Question volume](#question-volume) | | | Which of my sites get the most questions? | [Questions by site](#questions-by-site) | | | Who are the readers? | [Readers by type](#readers-by-type) | | | How many questions does each reader ask? | [Questions per reader](#questions-per-reader) | | Answer quality | Does Miso answer the questions? | [Answer outcome](#answer-outcome) | | | How long do readers wait for an answer? | [Time to answer](#time-to-answer) | | | What do readers ask about most? | [Top questions](#top-questions) | | Entry points | Do readers type questions, or select Explore questions? | [Typed and Explore questions](#typed-and-explore-questions) | | | Do readers select the Explore questions? | [Explore questions](#explore-questions) | | | Do my pages always have Explore questions? | [Explore question availability](#explore-question-availability) | | | Do readers use the question box? | [Question box](#question-box) | | | Which articles start the most questions? | [Most effective pages](#most-effective-pages) | | Reader engagement | Do readers ask a second question? | [First and follow-up questions](#first-and-follow-up-questions) | | | Do answers send readers to my articles? | [Clicks on source articles](#clicks-on-source-articles) | | | How long do readers stay on an answer? | [Engagement time](#engagement-time) | | | Do readers come back? | [Retention](#retention) | | Data check | Does my site send user IDs? | [Signed-in and anonymous questions](#signed-in-and-anonymous-questions) | Each section has the same table. The rows are: | Row | What it tells you | | --- | --- | | What it shows | The data in the chart. | | How Miso counts it | What is in the count, and what is not. | | How to read it | What a high value, a low value, or a change means. | | Example | One example with numbers. | | Use it to | The decisions that the chart supports. | | See also | The chart to look at next. | ## Words on this page | Term | What it means | | --- | --- | | Question | One request for an answer. A reader who asks three questions makes three. | | Reader | One person. Miso knows a reader by the user ID that your site sends. If your site sends no ID, Miso uses an anonymous ID for each browser. | | Unique | Counted once. 50 unique readers can ask 80 questions. | | Impression | A page load with the element on it. The reader did not always see the element. | | Viewable impression | A page load where the element was on the reader's screen. | | CTR | Click-through rate: clicks divided by impressions. 20 clicks on 1,000 impressions is 2%. | | vCTR | Viewable click-through rate: clicks divided by viewable impressions. | | Placement | Where on your site an element shows. **Home** is your home page. **Article** is any other page. A custom placement has the name that your site gives it. | | Median | The middle value. Half of the values are lower, and half are higher. | | Percentile | At the 90th percentile, 90 values in 100 are lower and 10 are higher. | ## Volume ### Question volume ![The Weekly Answer Request Count and Daily Answer Request Count charts.](/images/dojo-metrics-volume.png) | Charts | Weekly Answer Request Count
Daily Answer Request Count | | --- | --- | | What it shows | The number of questions for each week, and for each day. | | How Miso counts it | Every question counts, also a question that Miso did not answer. A reader who asks twice counts twice.

A week starts on Monday. The last point is the current week, so it stays low until the week ends. | | How to read it | A flat line is steady use. A regular dip is often the weekend. A sudden peak or drop is an event. | | Example | 360 questions a day is about 2,500 a week. A peak on one day often matches a large news story. A drop to half often matches a change on your site. | | Use it to | Measure the growth of Answers. See the effect of a launch, a newsletter, or a new placement. Find the date of a problem, then look at that date in the other charts. | | See also | [Questions by site](#questions-by-site) shows which site causes a change. [Readers by type](#readers-by-type) shows if more people ask, or the same people ask more. | ### Questions by site The Site Breakdown pie chart. ![The Daily Answer Count by Site chart.](/images/dojo-metrics-site-daily.png) | Charts | Site Breakdown
Daily Answer Count by Site | | --- | --- | | What it shows | **Site Breakdown** shows the share of questions from each site in the time range.

**Daily Answer Count by Site** shows the questions for each day, with one band for each site. | | How Miso counts it | Miso gets the site from your page. If you have one site, the only slice is **Main**. **Other** is a page that Miso cannot match to a site, for example a test page.

The bands stack. The top edge is the total for all sites. | | How to read it | Compare the share of each site with its share of your traffic. In the daily chart, look for one band that changes while the others stay the same. | | Example | Your news site has 40% of the questions and 40% of your traffic. Then Answers does as well there as on your other sites. If only one band decreases, the cause is on that site. | | Use it to | Compare your sites. Find a site that needs a better placement. Find the site that causes a change in the total. | | See also | [Explore questions](#explore-questions) and [Question box](#question-box) have one line for each site and placement. | ### Readers by type The User Type Breakdown pie chart. ![The Daily Unique User Count chart.](/images/dojo-metrics-readers-daily.png) | Charts | User Type Breakdown
Daily Unique User Count | | --- | --- | | What it shows | **User Type Breakdown** shows the readers in the time range, by type. The number at the top is the total.

**Daily Unique User Count** shows the readers who asked at least one question each day, by type. | | How Miso counts it | Each reader counts once. In the daily chart, a reader who asks five questions on one day counts once for that day. | | How to read it | Compare the readers with the questions. If the questions increase but the readers do not, the same readers ask more. | | Example | 7,880 readers with 12% subscribers is about 950 subscribers. 250 readers on a day with 360 questions is about 1.4 questions for each reader. | | Use it to | See if Answers reaches the readers who matter most to your business. See the effect of a paywall or a sign-in change. | | See also | [Signed-in and anonymous questions](#signed-in-and-anonymous-questions) shows if your site sends the data that this chart needs. | Miso gets the user type from the data that your site sends. Miso can show subscribers and registered readers only if your site sends this data. See [Integrating Your Data](/data/integrating-your-data). | User type | Who it is | How Miso knows | | --- | --- | --- | | **subscriber** | A paying reader. | Your site sends the type. | | **registered** | A reader who signed in. | Your site sends the type, or a user ID with no type. | | **anonymous** | A reader who did not sign in. | Your site sends no user ID. | ### Questions per reader ![The Daily Average Question per User chart.](/images/dojo-metrics-questions-per-reader.png) | Chart | Daily Average Question per User | | --- | --- | | What it shows | The average number of questions for each reader, each day. There is one line for each user type. | | How Miso counts it | The questions of one user type on one day, divided by the readers of that type on that day. | | How to read it | 1.0 means that each reader asked one question. A higher value means that readers ask more questions. | | Example | Subscribers at 1.9 and anonymous readers at 1.5 means that subscribers ask more follow-up questions. | | Use it to | Compare how much each type of reader uses Answers. | | See also | [First and follow-up questions](#first-and-follow-up-questions). | ## Answer quality ### Answer outcome The Answer Type Breakdown pie chart. ![The Answer Type Breakdown chart for each day.](/images/dojo-metrics-outcome-daily.png) | Charts | Answer Type Breakdown (pie)
Answer Type Breakdown (daily) | | --- | --- | | What it shows | The outcome of the questions. The pie shows the time range, with the total in the center. The daily chart shows each day. | | How Miso counts it | Each question has one outcome, from the table after this one. In the daily chart, the bands stack. The top edge is the total for the day. | | How to read it | Most of the pie is usually **success**. In the daily chart, look for a band that becomes wider. | | Example | 10,800 **success** in a total of 11,400 is a success rate of about 95%. If **Insufficient Content** increases for three days, readers ask about a topic that your articles do not cover. | | Use it to | Do a regular health check. Find gaps in your content. See when metering starts to block readers. | | See also | The answer log in [Answer Analytics](/operate/answer-analytics) shows the questions for each outcome. | | Outcome | What happened | What to do | | --- | --- | --- | | **success** | Miso answered, with your articles as sources. | Nothing. | | **Insufficient Content** | Your articles did not have enough information to answer. | Read these questions in the answer log. They show topics that your archive does not cover. | | **No Citation By LLM** | Miso answered, but the answer cites no article. | A small share is normal. If it increases, tell your Miso representative. | | **Canned Message** | Miso showed a set reply, for example for a support question. | Make sure that the set replies are still correct. | | **Metering Blocked** | The reader reached the question limit of their plan. | Compare with your metering rules. See [Metering & Entitlements](/operate/metering). | | **Safety Guardrail** | The safety check declined the question. | Nothing. A small number is normal. | | **Internal Error** | An error occurred in Miso. | If this occurs every day, tell your Miso representative. | ### Time to answer ![The Time to Answer (seconds) chart.](/images/dojo-metrics-time-to-answer-1.png) ![The Explore Question Time to Answer (seconds) chart.](/images/dojo-metrics-time-to-answer-2.png) | Charts | Time to Answer (seconds)
Explore Question Time to Answer (seconds) | | --- | --- | | What it shows | The wait for an answer, for each day. The first chart has all questions. The second chart has Explore questions only. | | How Miso counts it | The seconds from the question until the first words of the answer show. | | How to read it | Lower is better. The median line shows the usual wait. The 95% line shows the slow answers. | | Example | A median of 7 seconds and a 95% line of 15 seconds: most readers wait about 7 seconds, and 1 reader in 20 waits 15 seconds or more. | | Use it to | Monitor the wait of your readers. Compare the two charts to see if Explore questions take longer. | | See also | If the lines increase for more than a day, tell your Miso representative. | | Line | What it means | | --- | --- | | **Median Latency** | The usual wait. Half of the questions were faster. | | **90% Latency** | 1 question in 10 waited longer than this. | | **95% Latency** | 1 question in 20 waited longer than this. | ### Top questions ![The Answers - Top questions table.](/images/dojo-metrics-top-questions.png) | Chart | Answers - Top questions | | --- | --- | | What it shows | The questions that the most readers asked. | | How Miso counts it | **Unique User** is the number of different readers. A reader who asks the same question ten times counts once. Questions with different words are different rows. | | How to read it | The top rows are the topics that most readers want to know about. Select a column heading to sort the table. | | Example | A question about the new city budget at the top shows the topic that your readers follow most. | | Use it to | Find ideas for articles and explainers. Make sure that your archive covers the top topics. | | See also | [Answer outcome](#answer-outcome) shows if Miso answered these questions. | ## Entry points ### Typed and Explore questions The Total Answer Request pie chart. ![The Organic v.s. Explore Question Breakdown chart.](/images/dojo-metrics-question-source-daily.png) | Charts | Total Answer Request
Organic v.s. Explore Question Breakdown | | --- | --- | | What it shows | **Total Answer Request** shows all questions in the time range, in two slices. The number at the top is the total.

**Organic v.s. Explore Question Breakdown** shows the share of each slice, for each day. | | How Miso counts it | **Organic** is a question that a reader typed. **Explore (Generated)** is an Explore question that a reader selected.

The daily chart always fills to 100%. For the number of questions, see [Question volume](#question-volume). | | How to read it | A large **Explore (Generated)** share means that most questions start from your Explore questions. A large **Organic** share means that readers come with their own questions. | | Example | A total of 11.5k with 85% **Explore (Generated)** is about 9,800 questions from Explore questions. | | Use it to | Find the entry point that gets the most questions. See the effect of a placement change, for example a question box higher on the page. | | See also | [Explore questions](#explore-questions) and [Question box](#question-box) show each entry point. | ### Explore questions ![The five charts of the Explore Question Performance section.](/images/dojo-metrics-explore.png) | Charts | Daily Explore Question Click
Daily Explore Question Impression
Daily Explore Question Viewable
Daily Explore Question CTR
Daily Explore Question vCTR | | --- | --- | | What it shows | How often Explore questions load, show on screen, and get clicks. Each chart has one line for each site and placement, for example `news - Article`. The table after this one gives each chart. | | How Miso counts it | In the click chart, a reader who selects two questions on one page load counts once. The two rates count every click. | | How to read it | Read the counts first. They show the reach of each placement. Then read the rates. vCTR shows best how interesting the questions are, because it leaves out the readers who did not see them. | | Example | 10,000 loads and 3,000 viewable: 7 readers in 10 did not scroll to the questions. 20 clicks on 10,000 loads is a CTR of 0.2%. 20 clicks on 400 viewable is a vCTR of 5%. | | Use it to | Compare placements. Decide if a placement must move higher on the page. Use vCTR to compare a change to the questions. | | See also | [Explore question availability](#explore-question-availability) shows if each page had questions to show. | | Chart | What it counts | | --- | --- | | Daily Explore Question Click | Page loads where a reader selected an Explore question. | | Daily Explore Question Impression | Times that the questions loaded on a page. | | Daily Explore Question Viewable | Times that the questions were on the reader's screen. Each page load counts once. | | Daily Explore Question CTR | Clicks divided by impressions. | | Daily Explore Question vCTR | Clicks divided by viewable impressions. | ### Explore question availability ![The Explore Question Available Rate chart.](/images/dojo-metrics-explore-available.png) | Chart | Explore Question Available Rate | | --- | --- | | What it shows | The share of page loads that had at least one Explore question, for each day. | | How Miso counts it | The page loads that got one or more questions, divided by all the page loads that asked Miso for questions. | | How to read it | A rate near 100% is good. A decrease means that some pages show no questions. | | Example | 800 of 1,000 page loads is 80%. The other 200 page loads had no question for the reader to select. | | Use it to | Find content problems. New article types, or articles with little text, can cause a decrease. | | See also | If the rate stays low, tell your Miso representative. | ### Question box ![The five charts of the Search Box Performance section.](/images/dojo-metrics-search-box.png) | Charts | Daily Explore Query Submit
Daily Explore Container Impression
Daily Explore Container Viewable
Daily Explore Searchbox CTR
Daily Explore Searchbox vCTR | | --- | --- | | What it shows | How often the question box loads, shows on screen, and gets typed questions. Each chart has one line for each site and placement. The table after this one gives each chart. | | How Miso counts it | Every typed question counts. | | How to read it | Read the charts as you read [Explore questions](#explore-questions). The rates are usually lower, because a reader must type a question. | | Example | 50 questions on 5,000 loads is a CTR of 1%. If 2,000 of those loads had the box on screen, the vCTR is 2.5%. | | Use it to | Compare placements of the box. Use vCTR to compare a change to the text or the design of the box. | | See also | [Typed and Explore questions](#typed-and-explore-questions) shows the share of typed questions. | | Chart | What it counts | | --- | --- | | Daily Explore Query Submit | Questions that readers typed in the box and sent. | | Daily Explore Container Impression | Times that the box loaded on a page. | | Daily Explore Container Viewable | Times that the box was on the reader's screen. Each page load counts once. | | Daily Explore Searchbox CTR | Typed questions divided by impressions. | | Daily Explore Searchbox vCTR | Typed questions divided by viewable impressions. | ### Most effective pages ![The Explore - Most effective pages table.](/images/dojo-metrics-effective-pages.png) | Chart | Explore - Most effective pages | | --- | --- | | What it shows | The pages where readers selected the most Explore questions. | | How Miso counts it | **question_source** is the page. **COUNT(\*)** is the number of questions. `_trending` is the trending questions placement, for example on your home page. Typed questions are not in this table. | | How to read it | The top rows are the pages that make readers want to know more. | | Example | An article with 750 questions in a month starts many conversations. | | Use it to | Find the articles and topics that get the most questions. Put Explore questions on similar pages. | | See also | [Top questions](#top-questions) shows what readers ask. | ## Reader engagement ### First and follow-up questions ![The First Question v.s. Follow Up Question chart.](/images/dojo-metrics-follow-up.png) | Chart | First Question v.s. Follow Up Question | | --- | --- | | What it shows | The share of first questions and follow-up questions, for each day. | | How Miso counts it | **First Question** starts a new conversation. **Follow Up Question** comes after an answer, in the same conversation. | | How to read it | A larger **Follow Up Question** share means that more readers ask a second question after the first answer. | | Example | 10% follow-up questions means that 1 question in 10 continues a conversation. | | Use it to | See if answers start conversations. See the effect of a change to the follow-up questions under the answer. | | See also | [Questions per reader](#questions-per-reader) shows the questions for each type of reader. | ### Clicks on source articles ![The Daily Source Article Click Through Rate and Daily Source Article Viewable Click Through Rate charts.](/images/dojo-metrics-source-clicks.png) | Charts | Daily Source Article Click Through Rate
Daily Source Article Viewable Click Through Rate | | --- | --- | | What it shows | The click rate on the source articles under the answers, for each day and site. | | How Miso counts it | The first chart divides the clicks by the answers that showed sources. The second chart divides the clicks by the answers where the sources were on the screen. One answer can get more than one click. | | How to read it | The first rate shows the traffic that answers send to your articles. The second rate shows how often readers click a source that they see. The second rate is always the higher one. | | Example | 30 clicks on 200 answers is 15%. If 100 of those answers had the sources on screen, the viewable rate is 30%. | | Use it to | Measure the traffic that Answers sends to your articles. A low first rate with a high second rate means that readers do not scroll to the sources. | | See also | [Engagement time](#engagement-time) shows how long readers stay on an answer. | ### Engagement time ![The two Answers User Engagement Time charts.](/images/dojo-metrics-engagement.png) | Charts | Answers User Engagement Time (sum, in hours)
Answers User Engagement Time (percentile, in minutes) | | --- | --- | | What it shows | The first chart shows the total hours that readers were active on answers each day, with one line for each site. The second chart shows the minutes on one answer. | | How Miso counts it | Only active time on the answer counts. Each answer counts for 60 minutes or less.

**50%** is the usual reader. At **90%**, 1 reader in 10 stayed this long or longer. At **95%**, 1 reader in 20 did. | | How to read it | The total increases with more readers, and with more time for each reader. The percentiles show the time for each reader. | | Example | 3 hours a day on one site can be 90 readers for 2 minutes each. **50%** at 1.5 minutes means that the usual reader stays 90 seconds on an answer. | | Use it to | See the total time that readers give to Answers. See if readers read the answers. | | See also | [Clicks on source articles](#clicks-on-source-articles) shows where readers go after the answer. | ### Retention ![The User Retention Table 7d/30d.](/images/dojo-metrics-retention.png) | Chart | User Retention Table 7d/30d | | --- | --- | | What it shows | For each group of new readers, the share who came back. | | How Miso counts it | Miso puts readers in groups by the week of their first question. **n** is the number of readers in the group. The table always shows the last six months. The time range does not change it. | | How to read it | Compare the groups from top to bottom. The recent weeks are not complete, because their readers had less time to come back. | | Example | A 7d value of 6% in a group of 1,000 readers means that 60 readers asked again a week or more later. | | Use it to | See if readers make Answers a habit. Compare the groups before and after a change, for example a new placement. | | See also | Retention needs user IDs. See [Signed-in and anonymous questions](#signed-in-and-anonymous-questions). | | Column | What it means | | --- | --- | | **week** | The week of the first question, for example `2026-05-04 (n=250)`. | | **7d** | The share of the group who asked again 7 or more days after their first question. | | **30d** | The share of the group who asked again 30 or more days after their first question. | ## Data check ### Signed-in and anonymous questions ![The Sign-in v.s. Anonymous Breakdown chart.](/images/dojo-metrics-sign-in.png) | Chart | Sign-in v.s. Anonymous Breakdown | | --- | --- | | What it shows | The share of questions from signed-in readers and from anonymous readers, for each day. | | How Miso counts it | **Signed-In (with User ID)** means that your site sent a user ID. **Anonymous (withOUT User ID)** means that it did not. | | How to read it | The signed-in share is usually steady. A sudden change usually comes from a change in your integration. | | Example | If the signed-in share decreases to zero on one day, your site possibly stopped sending the user ID. | | Use it to | Make sure that your site sends user IDs. [Readers by type](#readers-by-type) and [Retention](#retention) need them. | | See also | [Integrating Your Data](/data/integrating-your-data). | ## Related For the helpful votes and the log of each question and answer, see [Answer Analytics](/operate/answer-analytics). # Answer Analytics (Dojo) Read each question, its answer, and what the reader thought of it. **Answers ▸ Analytics** in [Dojo](https://dojo.askmiso.com/) has two parts. The tiles at the top count answers and clicks. The **Answer Logs** list under them shows each question with its answer and sources. ## Helpful and Not Helpful Under each answer, a reader can select **Helpful** or **Not helpful**. Dojo counts these votes in two tiles, **Helpful** and **Not Helpful**. Select **#** on a tile to see the count, or **%** to see the rate. The rate divides the votes by all answers in the time range, with or without a vote. As a result, the rate is lower than the share of votes. A reader who selects the same button again clears the vote. Dojo then stops counting it. For what the widget sends, see [Ask interactions](/sdk/ask/interactions). ## Find a question Type in **Search questions or user ID** and press Enter. Select **Filters** to show only questions with a tag, for example **Helpful** or **Not helpful**. **Dedup** shows a question once when a reader asked it more than once. ## Download the log Select the download button to the right of **Dedup**. The file has the questions that the list shows, with your search and filters applied. It is a CSV file. To choose the columns, select the arrow next to the download button. Clear the columns that you do not need, then download. | Column | What it holds | | --- | --- | | **Question ID** | The id of the answer. It links a row to the interactions for that answer. | | **Question** | What the reader asked. | | **User ID**, **Anonymous ID** | Who asked, from the data your site sends. | | **User Type** | **subscriber**, **registered**, or **anonymous**. | | **Question Source** | Where the question came from. | | **fq**, **Keywords** | The filter that your site sent with the question, and the keywords that Miso found in it. | | **Answer**, **Sources** | The answer, and the articles that it cites. | | **Followup Question** | Whether the reader selected a suggested follow-up question. | | **Ads Click**, **Article Click** | Whether the reader clicked an ad or a source article. | | **Organic Question**, **Generated Question** | Whether the reader typed the question, or selected one that Miso suggested. | | **Helpful**, **Unhelpful** | `True` when the reader's vote on this answer is that button. | | **Tags**, **Created At**, **Request Metadata** | The tags on the row, the time of the question, and the extra data your site sent with it. | | **Feedback Comment** | The text the reader typed in the feedback box under the answer. If the reader commented more than once, this is the latest comment. It is empty when there is no comment. | The comment is only in the file. The list in Dojo does not show it. Before a comment goes into the file, Miso replaces personal data that has a known pattern: | In the comment | In the file | | --- | --- | | An email address | `[email]` | | A US Social Security number, written 123-45-6789 | `[ssn]` | | A phone number | `[phone]` | | A run of more than 15 digits, for example a card number | `[number]` | Names and street addresses have no fixed pattern. They stay in the comment. ## What the log does not show The log shows feedback that readers give in the answer widget. Feedback that readers send through a form on your own site does not come to Miso. For answer volume by week and by user type, see [Answer Metrics](/operate/answer-metrics). # Metering & Entitlements Cap how many answers each kind of reader gets. Metering controls **how many answers each kind of reader gets**, and **what the reader sees** when they reach the limit. Use it to put Answers behind your existing access model: a registration wall, a free taster, or a subscriber allowance. Below we set the allowances, then write what the reader reads at each limit. > **Miso configures metering for you.** Send us your rules and your messages, > and we set them up on your app. There is no self-serve screen for this yet. > Contact your Miso representative to start. --- ## What you send us Two things: 1. **The rules** — how many questions each kind of reader gets. 2. **The messages** — exactly what the reader sees, in your own words. Everything below is what those two lists can express. --- ## What you send on every question Metering needs to know **who is asking**. Send these on `POST /v1/ask/questions`: | Field | Why it is needed | | --- | --- | | `user_type` | Which tier the reader belongs to. | | `user_id` | Identifies a signed-in reader across sessions and devices. | | `anonymous_id` | Identifies a signed-out visitor. | > **CAUTION:** If you do not send `user_type`, metering never runs and every > reader is unlimited. This fails silently, with no error. Make it part of > your first integration test. ### Two ways to send them **In a JWT.** Your server signs a short-lived token with `user_id` and `user_type`, and the page sends it as the `Authorization: Bearer` header. The tier comes from your server, so a reader cannot change it. This needs backend work: an endpoint that mints the token after your own session check. See [JWT (user authentication)](/api/authentication#jwt-user-authentication). ```json title="Token claims" { "user_id": "alice", "user_type": "subscriber", "exp": 1789500000 } ``` **In the request body.** Send `user_id` and `user_type` as plain fields on `POST /v1/ask/questions`. No backend work, and metering runs the same way. ```json title="Request body" { "question": "…", "user_id": "alice", "user_type": "subscriber" } ``` Use the JWT when you can. If you send `user_type` both ways, the two must match, or the request is `401 Token does not match the user_type`. --- ## Reader tiers Miso groups readers into three tiers. Your `user_type` value decides the tier. | You send | Tier | Typically | | --- | --- | --- | | `anonymous` | **anon** | Signed-out visitor. | | `registered` or `free` | **reg** | Signed in, no paid plan. | | `subscriber`, `paid`, or `internal` | **sub** | Paying reader or staff. | `user_type` is a fixed list. A value outside it is rejected. --- ## Question kinds Miso counts two kinds of question separately: | Kind | What it is | | --- | --- | | **organic** | The reader typed the question. | | **related** | The reader clicked a suggested or related question. | Most publishers meter the two differently. A common choice is to let readers click suggestions freely, and meter only the questions they type. --- ```mermaid %%{init: {'theme':'base','themeVariables':{ 'fontFamily':'IBM Plex Sans, ui-sans-serif, system-ui','fontSize':'14px', 'lineColor':'#9aa3c0','clusterBkg':'transparent','clusterBorder':'#d3d8e8', 'titleColor':'#8b93ad' },'flowchart':{'curve':'basis','nodeSpacing':18,'rankSpacing':58,'padding':12}}}%% flowchart LR Q["`**A question arrives**`"] UT{"`user_type sent?`"} FREE["`No metering every reader unlimited`"] TIER["`Map to a tier anon · reg · sub`"] KIND["`Which kind? organic or related`"] CNT{"`Under the limit?`"} ANS["`**Answer** plus your below message`"] BLOCK["`**Your message** blocked_reason metering`"] Q --> UT UT -- no --> FREE UT -- yes --> TIER --> KIND --> CNT CNT -- yes --> ANS CNT -- "no, at or past it" --> BLOCK classDef q fill:#f6f7fa,stroke:#c9cfe0,color:#454c69 classDef work fill:#e8ecfb,stroke:#b9c2ea,color:#22307a classDef out fill:#f4effc,stroke:#cdbcf0,color:#40277a classDef warn fill:#fdf2f2,stroke:#e4b9b9,color:#7a2222 class Q q class UT,TIER,KIND,CNT work class ANS out class FREE warn class BLOCK out ``` ## The rules You give one limit per **tier × kind**. For example: | Rule | Meaning | | --- | --- | | anon, organic → `0` | A signed-out visitor cannot type a question at all. | | anon, related → unlimited | But they can click suggested questions freely. | | reg, organic → `5` | A registered reader gets 5 typed questions. | | sub, organic → unlimited | A subscriber has no limit. | Any tier you do not mention is unlimited. ### When the count resets | You choose | Behavior | | --- | --- | | **Monthly** | The count resets on the 1st of each month, UTC. | | **Never** (default) | The allowance is once per reader, for good. | Asking the **same question again does not count twice**. A reader can re-read an answer without spending another credit. --- ## The messages You write the exact text. Miso shows it to the reader. For each tier and kind, you can supply a message for three moments: | Moment | When the reader sees it | | --- | --- | | **below** | They are still under the limit. | | **reached** | This question is the one that hits the limit. | | **above** | They are past the limit and get no answer. | You do not have to write all three. If **above** is missing, Miso uses **reached**. If **reached** is missing, it uses **below**. You can also write a message for one specific question, for example a nudge only on the reader's 3rd question. ### Counters in your text Three placeholders are filled in for you: | Placeholder | Becomes | | --- | --- | | `{curr}` | How many questions the reader has used. | | `{max}` | Their limit. | | `{remain}` | How many they have left. | > You have used {curr} of your {max} free answers. {remain} left this month. Messages support Markdown, so you can link straight to your sign-in, registration, or subscribe page. --- ## What the reader gets **Under the limit.** Miso returns the normal answer. If you supplied a *below* message, it appears with the answer. Use it for a gentle nudge or a counter. **At or past the limit.** Miso returns your message instead of an answer, and sets `blocked_reason` to `metering` so your front end can render a paywall state. ```json Blocked response { "message": "success", "data": { "finished": true, "blocked_reason": "metering", "answer": "> You have used all 5 of your free answers this month." } } ``` --- ## Common setups ### 1. Registration wall The most common pattern. Signed-out visitors can read but not ask. Suggested questions stay open so the feature is still visible. | Tier | organic | related | | --- | --- | --- | | anon | `0` | unlimited | | reg | `5` | unlimited | | sub | unlimited | unlimited | Messages to write: - **anon, organic** — "To ask your own question, [sign in](…) or [register](…)." - **anon, related** — "This answer is a starting point. To ask your own questions, [register](…)." - **reg, organic, reached** — "You have used all {max} of your answers. [Subscribe](…) to keep asking." ### 2. Free taster, then a wall Let visitors feel the product before asking them to register. | Tier | organic | related | | --- | --- | --- | | anon | `2` | unlimited | | reg | `10` | unlimited | | sub | unlimited | unlimited | - **anon, organic, below** — "{remain} free answers left. [Register](…) for more." - **anon, organic, reached** — "That was your last free answer. [Register](…) to continue." ### 3. Monthly subscriber allowance Meter paying readers too, and reset every month. | Tier | organic | | --- | --- | | anon | `0` | | reg | `2` | | sub | `20`, reset monthly | - **sub, organic, below** — "You have used {curr} of {max} answers this month." - **sub, organic, above** — "You have used all {max} answers this month. Your allowance resets on the 1st." ### 4. Staff and internal users bypass the limit Send `user_type: "internal"` for your own team. They map to the **sub** tier, so give that tier no limit and your staff are never metered. ### 5. Suggested questions always free Set every **related** limit to unlimited and meter only **organic**. Readers can explore your suggested questions all day, and the allowance only applies to questions they type. --- ## Reset a reader's count while you test Testing the wall spends a reader's allowance fast. In the following call, we put the test reader back to zero from your server: ```http title="Reset one reader" POST /v1/ask/metering/reset?api_key=YOUR_SECRET_API_KEY Content-Type: application/json { "user_id": "alice" } ``` ```json title="Response" { "message": "success", "data": { "user_id": { "id": "alice", "previous_count": 5 } } } ``` - It takes your **Secret API Key**. A publishable key gets `403`. - Send `user_id`, `anonymous_id`, or both. The count is the sum over both ids, so if your front end sends both on a question, reset both. - A question the reader already asked in the last 30 days still does not count after the reset. Ask a new question to see the counter move. --- ## Before you launch 1. Send Miso your rules and messages. 2. Confirm your front end sends `user_type` on **every** question, and the right value for each reader. 3. Test each tier: sign out, sign in as a free reader, and sign in as a subscriber. 4. Check the state at the boundary: the question that hits the limit, and the one after it. [Reset the count](#reset-a-readers-count-while-you-test) to run it again. 5. Confirm your front end renders `blocked_reason: "metering"` as a paywall and not as an error. # FAQ Common questions about Miso, and where to go next. > Have a question? We probably have you covered. **I want a recipe that does \[X]. Can Miso help?** Most likely. We want to hear your ideas. Contact us at any time at . **Can Miso recommend UX patterns for implementing a recipe?** Yes. We have much experience in the UX patterns that are most effective for personalized search and recommendations. Ask your Miso solutions engineer about Bento, our coming-soon UI Kit of best practices and style guides. **Do I send interaction data in bulk or in real time?** You can bulk upload historical interactions. However, **you must stream live interactions in real time at low latency.** Miso then personalizes the experience for each user immediately. It reacts as they click, scroll, and search. This matters most for a new user, because Miso tailors the recommendations at cold start. See [Integrating Your Data](/data/integrating-your-data) for sample code. **What do Miso's results look like for first-time users?** Miso provides results from all the activity on your site. Miso then learns immediately from the user's first few interactions. For this reason, stream interactions to Miso in real time. You can also use the `user_cohort` parameter. This parameter tells Miso to personalize the cold start behavior as if the user belonged to a certain cohort on your site. See the [API Reference](/api/reference) for more details. **Can Miso incorporate negative signals?** Yes. Negative signals include removing an item from the cart, requesting a refund, removing an item from a collection, or pressing a 'dislike' button. A product detail view with a very short duration can also indicate that the item was not relevant. For more information on the different types of interactions that Miso supports, please see [Integrating Your Data](/data/integrating-your-data#interactions-what-readers-do). **Can Miso use social engagement (likes, comments) in its model?** Yes. Miso can use social feedback such as liking, commenting, sharing, and rating. These are strong signals of user preference. Send them to Miso if you have them. For more information on the different types of interactions that Miso supports, please see [Integrating Your Data](/data/integrating-your-data#interactions-what-readers-do). **Can Miso's engines be trained using limited structured data?** Provide as many details as you can about the products or content in your catalog. More details give more meaningful search and recommendation results. These details include attributes such as the title, description, brand, and any domain-specific tags. For more information on our product schema, see [Product Schema](/data/product-schema). When necessary, Miso can also use unstructured data, such as images and videos, to strengthen the personalization models. **Can your APIs support asynchronous writes?** Yes. To use asynchronous mode, append `?async=1` to the Product or User Upload APIs. **Do I need to send customers' purchase history to Miso?** During the onboarding phase, we typically ask for at least 3 months of clickstream data. This data covers product detail page views and add to cart events. The purchase history of customers is not required. If it is available, Miso can incorporate it into the initial training. After you configure the real-time clickstream data feed, Miso automatically tracks purchase history. Miso then retrains the models on a given cadence. **What is your strategy to minimize latency for customers globally?** Miso runs satellite servers in US East, Asia, and Europe. They serve latency-sensitive requests, such as Search and Recommendation API calls. To keep latency low, some customers send those requests from their front-end JavaScript. Their users' browsers then talk to the Miso API directly. Contact your Miso solutions engineer for more details about this option. **Can Miso be used headless?** Yes. You use Miso mostly through REST APIs in your front-end and back-end clients. You can also use our [Node.js](https://misoai.github.io/miso-server-js-sdk/sdk/) and [Python SDK](https://misoai.github.io/miso-python-sdk/), primarily for data upload (content and interactions). You manage the initial engine training and certain merchandising tools, such as synonyms, through Dojo. Dojo is our no-code UI for your Miso instance. For Answer deployments, we also recommend our [front-end JS SDK](https://github.com/MisoAI/miso-client-js-sdk). It provides ready-to-use UI components, built-in analytics, and customizable HTML templates. These save significant development time. **Can you decouple the Search and Recommendation engines?** Yes. In fact, the Search and Recommendation engines are entirely separate and can be fine-tuned individually. **Can I manually swap out a recommendation or search result?** Yes. You can boost, bury, or exclude products, brands, or categories from your recommendations or search results. These actions use pre-defined conditions. You set the conditions programmatically with `boost_fq`, or in Dojo, our no-code UI. See [Filter Syntax (fq)](/api/fq) for the syntax `boost_fq` takes. # Answers FAQ Common questions about deploying Answers. > Deployment FAQs **What counts toward metering?** Metering is when a user's usage of Answers counts toward a predefined limit or quota. There are currently two kinds of actions for engaging with Answers: * clicking on a pre-generated question (for example, Explore Questions and follow-up questions) * submitting an organic query (for example, the user types a question) Clicks on pre-generated questions do not count toward metering. All user types generally have unlimited usage of these. Submitting an organic query counts toward metering. Miso handles it with the metering rules that you define for each user type (for example, anonymous, registered, or subscribed users). **An answer came back empty. Is that an error?** No. When Miso finds nothing relevant in your catalog, it returns `200` with `finish_reason: "success"`, an empty `sources` array, and text that says it found nothing. Check the catalog before you check your code. The usual causes are an upload that has not finished indexing, or a question outside your content. See [Answer API](/api/genai/answer). **Every user history endpoint returns 403. What is wrong?** User history is enabled per app. Until Miso turns it on, every endpoint on that page returns: ```json { "message": "user history is not enabled for this app" } ``` This is a setting, not your key: the same key reaches the rest of the API. Ask your Miso representative to enable it. See [User History](/api/genai/user-history). **How do I tell an update Miso wrote from a reader's question?** A generated update is appended to the thread as an ordinary turn, so it looks like any other question. Miso marks it in the answer metadata: ```json { "metadata": { "miso_generated_by": "answer_update_monitor" } } ``` Test that field rather than the question text. See [Answer Updates](/api/genai/answer-updates). # Pricing A monthly fee, with no per-answer charge. Miso charges a **monthly fee**. The fee covers unlimited API requests and unlimited responses. There are no token charges and no per-answer charges. Usage and adoption can rise without a cost that rises with them, so you can put Answers in front of every reader instead of rationing it. ## What is included | | | | --- | --- | | **API requests and responses** | Unlimited. | | **Indexing your content** | Free. Upload the whole catalog, and re-upload as it changes. | | **Products** | Priced by the products you switch on. See [Welcome to Miso](/) for the list. | To limit how many answers a **reader** gets, use metering. That is your business rule, not a Miso charge. See [Metering & Entitlements](/operate/metering). ## Get a quote Pricing depends on the products you enable and the size of your audience. [Contact Miso](https://miso.ai/get-answers) for a quote, or ask your Miso representative.