Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Ollama Multi-Model Collaboration and Agent Workflow

Ollama Multi-Model Collaboration and Agent Workflow

A single model does not have to do it all: let small models do routing, specialized models do tasks, and online models look up information, with structured output as the scheduling protocol, and you can combine fast and economical intelligent applications.

This chapter implements a multi-model routing system and upgrades it into an Agent workflow with online capabilities.


Architecture Design: Small-Model Routing + Expert Execution

The core idea is division of labor: judging "what the user wants to do" is very simple and only needs the smallest model; the real work is handed over to the appropriate specialized model.

multi-model routing architecture: router classification, three expert models executing

This design has three advantages: small-model routing takes only tens of milliseconds, so large models no longer handle low-value requests; each expert model's parameters can be adjusted independently as needed; a new task type only needs one more branch and does not affect existing pipelines.


Implementation One: Structured Output for Intent Routing

The key to routing is making the classification result "machine-readable"; structured output serves as the scheduling protocol here.

Example

File path: router.py

from

ollama

import

chat

from

pydantic

import

BaseModel

,

Field

Structured definition of the routing result

class

Route

(

BaseModel

)

:

    category:

str

=

Field

(

description

=

"Question category: chat / coding / search"

)

    reason:

str

=

Field

(

description

=

"One-sentence classification basis"

)

def

classify

(

question:

str

)

Route:

    response

=

chat

(

        model

=

'qwen3.5:4b'

,

         

Use a small model for routing

        messages

=

[

{

'role'

:

'user'

,

'content'

: question

}

]

,

        format

=

Route.

model_json_schema

(

)

,

        options

=

{

'temperature'

:

0

}

,

 

Classification should be stable

   

)

   

return

Route.

model_validate_json

(

response.

message

.

content

)

Quick self-test

for

q

in

[

'How to deduplicate a Python list?'

,

'What AI news is there today?'

,

'Tell a joke'

]

:

    r

=

classify

(

q

)

   

print

(

r.

category

,

'|'

,

r.

reason

)



$ python router.py

coding | 询问 Python 列表去重的编程方法

search | 询问当天的最新新闻,需要联网

chat   | 闲聊类请求,直接回答即可


Implementation Two: Three Expert Handlers

One handler function per route, with a unified signature for easy scheduling.

Example

Append to router.py

from

ollama

import

chat

,

web_search

,

web_fetch

def

handle_chat

(

question

)

:

   

"""Daily Q&A: the small model answers directly"""

    r

=

chat

(

model

=

'qwen3.5:4b'

,

             messages

=

[

{

'role'

:

'user'

,

'content'

: question

}

]

)

   

return

r.

message

.

content

def

handle_coding

(

question

)

:

   

"""Programming tasks: handed to a dedicated code model"""

    r

=

chat

(

model

=

'runoob-coder'

,

             messages

=

[

{

'role'

:

'user'

,

'content'

: question

}

]

,

             options

=

{

'temperature'

:

0.2

,

'num_ctx'

:

65536

}

)

   

return

r.

message

.

content

def

handle_search

(

question

)

:

   

"""Online tasks: small model + search tool Agent loop"""

    tools

=

{

'web_search'

: web_search

,

'web_fetch'

: web_fetch

}

    messages

=

[

{

'role'

:

'user'

,

'content'

: question

}

]

   

while

True

:

        r

=

chat

(

model

=

'qwen3.5:4b'

,

messages

=

messages

,

                 tools

=

[

web_search

,

web_fetch

]

)

        messages.

append

(

r.

message

)

       

if

not

r.

message

.

tool_calls

:

           

return

r.

message

.

content

       

for

call

in

r.

message

.

tool_calls

:

            func

=

tools.

get

(

call.

function

.

name

)

           

Truncate tool results to protect the context window

            result

=

str

(

func

(

**call.

function

.

arguments

)

)

[

:

2000

]

            messages.

append

(

{

'role'

:

'tool'

,

                             

'tool_name'

: call.

function

.

name

,

                             

'content'

: result

}

)

HANDLERS

=

{

'chat'

: handle_chat

,

           

'coding'

: handle_coding

,

           

'search'

: handle_search

}

def

ask

(

question

)

:

    route

=

classify

(

question

)

   

print

(

f

'[route -> {route.category}] {route.reason}'

)

   

return

HANDLERS

[

route.

category

]

(

question

)

The router itself does not produce answers, so its hallucination risk is limited to the single matter of "misclassification"; the cost of a wrong classification is just one extra correction step and does not pollute the final answer.


Implementation Three: Hybrid Local and Cloud Orchestration

Each route can add a "cloud upgrade tier": for tasks the local model cannot handle, just change the model name in the same code structure.

Example

Append to router.py

def

ask_with_fallback

(

question

,

force_cloud

=

False

)

:

   

"""Scheduling with cloud fallback: local first, complex tasks escalated to cloud"""

    route

=

classify

(

question

)

.

category

   

if

force_cloud

or

route

==

'coding'

:

       

Heavy tasks such as coding go directly to the cloud flagship specification

        model

=

'qwen3.5:cloud'

   

else

:

        model

=

'qwen3.5:4b'

   

print

(

f

'[route -> {route}] using model {model}'

)

    r

=

chat

(

model

=

model

,

             messages

=

[

{

'role'

:

'user'

,

'content'

: question

}

]

)

   

return

r.

message

.

content

Note a capability difference: Cloud models do not yet support structured output, so the router must be handled by a local model, which also fits the "small model does routing" design.


Comprehensive Evaluation of Cost and Latency

The economics of a multi-model strategy must be calculated across three dimensions together:

Dimension Local small model Local large model Cloud model
Time to first token Lowest (millisecond-level loading) Medium Includes network round trip
Marginal cost Approximately equal to electricity cost Electricity cost + VRAM usage Billed by usage
Answer quality Sufficient for simple tasks Near flagship level Flagship level
Concurrency capability Limited by the local machine Limited by VRAM Best elasticity

This yields a practical baseline strategy: use the local small model as the foundation for the router and light tasks; hand quality-sensitive tasks to the local large model; switch heavy-load or over-spec tasks to the cloud; put all three model types' names in a configuration file and adjust them at any time as retirement announcements or hardware changes occur.