Skip to content

Chapter 02 · Model routing and provider strings ​

Chapters that use a model need a tool-calling model service and API key (any OpenAI-compatible endpoint); running incurs cost.

Mechanics and design choices ​

The model argument accepts a chat model instance or a "provider:model" string routed through init_chat_model. The Deep Agents docs favor strings; in real projects an explicit model object gives more control over timeouts, retries, and tags.

Example ​

python
import os
from langchain_openai import ChatOpenAI

model = ChatOpenAI(
    model=os.environ["MODEL_ID"],
    api_key=os.environ["DEEPAGENT_API_KEY"],
    base_url=os.environ.get("DEEPAGENT_BASE_URL", "https://api.openai.com/v1"),
)

from deepagents import create_deep_agent

agent = create_deep_agent(
    model=model,
    system_prompt="Answer in one short paragraph.",
)
result = agent.invoke({"messages": [{"role": "user", "content": "Say exactly: ready"}]})
print(result["messages"][-1].content)

Run and verify ​

Run after configuring the three variables. Acceptance: a short confirmation and no side effects. String routing needs the provider package installed; the object form only needs its client.

Pitfalls ​

Do not hard-code model names in production: switching and rollbacks belong in configuration. String-routing errors surface at call time, so check environment variables and provider client versions together.

🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. What does model accept?

2. When does string routing resolve?

3. Which is preferred in production?

4. What are tags for?

Hands-on exercises ​

  1. Try the string form and compare when errors surface.
  2. Add tags to filter this model in streams.
  3. Write config that selects endpoints per environment.

Official references ​

Verified on 2026-09-17 with Deep Agents 0.7.15.