A documentation assistant gets “Does it keep the order?” as its second question. Search that sentence on its own and the retriever has no object to look up. If the previous question concerned Python dictionaries, the useful search is “Do Python dictionaries preserve insertion order?”
Send just enough conversation history
Pass the previous question and latest question as named JSON fields. Ask Granite to resolve references using only that context. A special CLARIFY response gives the application a way to pause retrieval when two objects fit.
Run the example locally
Start Ollama on your computer and run ollama pull granite3.3:2b in a terminal. Save the script as example.py and run python example.py with Python 3. It uses the standard library. The first request may take longer while Ollama loads the model.
import json
from urllib.request import Request, urlopen
turns = {'previous': 'How do Python dictionaries work?',
'latest': 'Does it keep the order?'}
question = json.dumps(turns)
payload = {
'model': 'granite3.3:2b',
'messages': [
{'role': 'system', 'content': "Write a standalone search question from the two supplied chat turns. Resolve references only when the previous turn identifies one clear subject. If ambiguous return CLARIFY. Return only the question or CLARIFY. Do not answer it."},
{'role': 'user', 'content': question},
],
'stream': False,
'options': {'temperature': 0, 'num_predict': 64},
}
request = Request('http://localhost:11434/api/chat',
data=json.dumps(payload).encode(),
headers={'Content-Type': 'application/json'})
with urlopen(request, timeout=120) as response:
result = json.load(response)['message']['content'].strip()
if result == 'CLARIFY' or not result:
print('Which object do you mean?')
else:
print(result)Check the result
Change the previous turn to “Compare Python dictionaries and sets.” Now “it” has two plausible meanings. Expect CLARIFY. To evaluate a real retrieval system, record whether the intended document appears in the top three with the original question and with the rewrite. Track clarification requests separately so an overly cautious model cannot appear accurate by skipping every difficult case.
Further reading: official model card and license · Ollama chat API · more Python tutorials.
No comments:
Post a Comment