Qwen3.5 本地对话演示¶
这个 notebook 演示怎样调用本地 Ollama 中的 qwen3.5:0.8b 模型,让它完成一个最简单的中文对话任务。
第 1 步:准备依赖¶
In [ ]:
import json
import os
import urllib.request
import urllib.error
第 2 步:写一个 prompt¶
In [ ]:
prompt = '请用三句话解释什么是预训练,以及它为什么改变了 NLP。'
prompt
第 3 步:构造请求体¶
In [ ]:
payload = {
'model': 'qwen3.5:0.8b',
'stream': False,
'messages': [
{
'role': 'user',
'content': prompt,
}
],
}
payload
第 4 步:请求本地 Ollama¶
In [ ]:
request = urllib.request.Request(
'http://localhost:11434/api/chat',
data=json.dumps(payload).encode('utf-8'),
headers={'Content-Type': 'application/json'},
method='POST',
)
for key in [
'http_proxy',
'https_proxy',
'HTTP_PROXY',
'HTTPS_PROXY',
'all_proxy',
'ALL_PROXY',
]:
os.environ.pop(key, None)
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
with opener.open(request) as response:
result = json.loads(response.read().decode('utf-8'))
result
第 5 步:查看模型回答¶
In [ ]:
result['message']['content']
第 6 步:换一个更贴近课堂的问题¶
In [ ]:
payload['messages'][0]['content'] = '请比较 GPT、BERT、T5 三条路线的主要差别。'
request = urllib.request.Request(
'http://localhost:11434/api/chat',
data=json.dumps(payload).encode('utf-8'),
headers={'Content-Type': 'application/json'},
method='POST',
)
for key in [
'http_proxy',
'https_proxy',
'HTTP_PROXY',
'HTTPS_PROXY',
'all_proxy',
'ALL_PROXY',
]:
os.environ.pop(key, None)
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
with opener.open(request) as response:
result = json.loads(response.read().decode('utf-8'))
result['message']['content']