File size: 6,687 Bytes
4eb0a6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4370c9
4eb0a6b
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
---
license: mit
tags:
  - tutorial
  - crazyrouter
  - langchain
  - llamaindex
  - autogen
  - ai-agents
  - llm
language:
  - en
  - zh
---

# πŸ”— Crazyrouter + LangChain / LlamaIndex / AutoGen

> Use 624+ AI models in your favorite framework β€” zero config changes.

Since Crazyrouter is 100% OpenAI-compatible, it works out of the box with every major AI framework.

---

## LangChain

### Installation

```bash
pip install langchain langchain-openai
```

### Basic Chat

```python
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    base_url="https://crazyrouter.com/v1",
    api_key="sk-your-crazyrouter-key",
    model="gpt-4o"
)

response = llm.invoke("Explain microservices in one paragraph")
print(response.content)
```

### Switch Models on the Fly

```python
# Use Claude for analysis
analyst = ChatOpenAI(
    base_url="https://crazyrouter.com/v1",
    api_key="sk-your-crazyrouter-key",
    model="claude-sonnet-4-20250514"
)

# Use DeepSeek for coding (cheaper)
coder = ChatOpenAI(
    base_url="https://crazyrouter.com/v1",
    api_key="sk-your-crazyrouter-key",
    model="deepseek-chat"
)

# Use GPT-4o-mini for simple tasks (cheapest)
helper = ChatOpenAI(
    base_url="https://crazyrouter.com/v1",
    api_key="sk-your-crazyrouter-key",
    model="gpt-4o-mini"
)
```

### LangChain Chains

```python
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful coding assistant."),
    ("user", "{question}")
])

chain = prompt | llm | StrOutputParser()

result = chain.invoke({"question": "How do I read a CSV file in Python?"})
print(result)
```

### RAG with Crazyrouter

```python
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_community.vectorstores import FAISS
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough

# Embeddings (use a cheap model)
embeddings = OpenAIEmbeddings(
    base_url="https://crazyrouter.com/v1",
    api_key="sk-your-crazyrouter-key",
    model="text-embedding-3-small"
)

# Chat model
llm = ChatOpenAI(
    base_url="https://crazyrouter.com/v1",
    api_key="sk-your-crazyrouter-key",
    model="gpt-4o-mini"
)

# Split your documents
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
docs = splitter.create_documents(["Your document text here..."])

# Create vector store
vectorstore = FAISS.from_documents(docs, embeddings)
retriever = vectorstore.as_retriever()

# RAG chain
template = """Answer based on context:
{context}

Question: {question}"""

prompt = ChatPromptTemplate.from_template(template)

chain = (
    {"context": retriever, "question": RunnablePassthrough()}
    | prompt
    | llm
)

result = chain.invoke("What does the document say?")
print(result.content)
```

---

## LlamaIndex

### Installation

```bash
pip install llama-index llama-index-llms-openai-like
```

### Basic Usage

```python
from llama_index.llms.openai_like import OpenAILike

llm = OpenAILike(
    api_base="https://crazyrouter.com/v1",
    api_key="sk-your-crazyrouter-key",
    model="gpt-4o",
    is_chat_model=True
)

response = llm.complete("What is retrieval augmented generation?")
print(response)
```

### With OpenAI Class Directly

```python
from llama_index.llms.openai import OpenAI
import os

os.environ["OPENAI_API_KEY"] = "sk-your-crazyrouter-key"
os.environ["OPENAI_API_BASE"] = "https://crazyrouter.com/v1"

llm = OpenAI(model="gpt-4o-mini")
response = llm.complete("Hello!")
print(response)
```

---

## AutoGen

### Installation

```bash
pip install autogen-agentchat
```

### Multi-Agent Setup

```python
import autogen

config_list = [
    {
        "model": "gpt-4o",
        "base_url": "https://crazyrouter.com/v1",
        "api_key": "sk-your-crazyrouter-key",
    }
]

llm_config = {"config_list": config_list}

# Create agents
assistant = autogen.AssistantAgent(
    name="assistant",
    llm_config=llm_config,
)

user_proxy = autogen.UserProxyAgent(
    name="user_proxy",
    human_input_mode="NEVER",
    max_consecutive_auto_reply=3,
    code_execution_config={"work_dir": "coding"},
)

# Start conversation
user_proxy.initiate_chat(
    assistant,
    message="Write a Python script that fetches the top 10 Hacker News stories."
)
```

### Multi-Model Agents (Cost Optimization)

```python
# Expensive model for complex reasoning
senior_config = [{"model": "gpt-4o", "base_url": "https://crazyrouter.com/v1", "api_key": "sk-your-key"}]

# Cheap model for simple tasks
junior_config = [{"model": "gpt-4o-mini", "base_url": "https://crazyrouter.com/v1", "api_key": "sk-your-key"}]

senior = autogen.AssistantAgent("senior", llm_config={"config_list": senior_config})
junior = autogen.AssistantAgent("junior", llm_config={"config_list": junior_config})
```

---

## CrewAI

```python
from crewai import Agent, Task, Crew
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    base_url="https://crazyrouter.com/v1",
    api_key="sk-your-crazyrouter-key",
    model="gpt-4o"
)

researcher = Agent(
    role="Researcher",
    goal="Find accurate information",
    backstory="You are an expert researcher.",
    llm=llm
)

task = Task(
    description="Research the latest trends in AI API gateways",
    agent=researcher,
    expected_output="A summary of trends"
)

crew = Crew(agents=[researcher], tasks=[task])
result = crew.kickoff()
print(result)
```

---

## Environment Variables (Works Everywhere)

Set these once and most frameworks auto-detect:

```bash
export OPENAI_API_KEY="sk-your-crazyrouter-key"
export OPENAI_API_BASE="https://crazyrouter.com/v1"
export OPENAI_BASE_URL="https://crazyrouter.com/v1"
```

---

## Pro Tips

1. **Use cheap models for agents that do simple tasks** β€” `gpt-4o-mini` or `deepseek-chat` for routing, summarizing, formatting
2. **Use powerful models for reasoning** β€” `gpt-4o`, `claude-sonnet-4-20250514`, or `deepseek-reasoner` for complex analysis
3. **Mix providers freely** β€” one agent uses Claude, another uses GPT, another uses Gemini. All through one API key
4. **Monitor costs** β€” Crazyrouter dashboard shows per-model usage

---

## Links

- 🌐 [Crazyrouter](https://crazyrouter.com/?utm_source=huggingface&utm_medium=tutorial&utm_campaign=dev_community)
- πŸ“– [Getting Started Guide](https://huggingface.co/xujfcn/Crazyrouter-Getting-Started)
- πŸ€– [Live Demo](https://huggingface.co/spaces/xujfcn/Crazyrouter-Demo)
- πŸ’¬ [Telegram](https://t.me/crazyrouter)
- 🐦 [Twitter @metaviiii](https://twitter.com/metaviiii)