or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

app-management.mdcode-migration.mdindex.mdintegration-development.mdtemplate-development.mdutilities.md

code-migration.mddocs/

0

# Code Migration

1

2

Migrate LangChain code to newer versions using Grit pattern matching with interactive and diff modes for safe code transformation. This functionality helps developers update their codebases to work with newer LangChain versions.

3

4

## Capabilities

5

6

### Migrate Code

7

8

Run automated code migration using Grit pattern matching to update imports, function calls, and API usage patterns.

9

10

```bash { .api }

11

langchain migrate [grit-args] [options]

12

13

Options:

14

--diff Show changes without applying them (dry-run mode)

15

--interactive Prompt for confirmation before making each change

16

17

Additional Arguments:

18

Any additional arguments are passed directly to the Grit CLI

19

```

20

21

**Usage Examples:**

22

23

```bash

24

# Run migration with preview (recommended first step)

25

langchain migrate --diff

26

27

# Run migration interactively

28

langchain migrate --interactive

29

30

# Run migration with both diff and interactive modes

31

langchain migrate --diff --interactive

32

33

# Run migration and apply changes

34

langchain migrate

35

36

# Pass additional Grit arguments

37

langchain migrate --disable some_pattern --interactive

38

```

39

40

**Migration Process:**

41

42

The migration system uses Grit pattern matching to:

43

44

1. **Identify Patterns**: Scan code for outdated LangChain usage patterns

45

2. **Transform Code**: Apply systematic transformations to update imports and API calls

46

3. **Validate Changes**: Ensure transformations maintain code functionality

47

4. **Report Results**: Provide detailed feedback on applied changes

48

49

### Migration Strategy

50

51

**Two-Pass Migration Required:**

52

53

The migration process requires running twice for complete migration:

54

55

1. **First Pass**: Moves imports from `langchain` to community packages

56

2. **Second Pass**: Migrates from community packages to partner packages when available

57

58

Example migration flow:

59

```

60

langchain.llms.openai → langchain_community.llms.openai → langchain_openai.llms

61

```

62

63

**Targeted Migration Areas:**

64

65

- **Import Statements**: Update module import paths

66

- **Class References**: Update class names and initialization

67

- **Function Calls**: Update deprecated function signatures

68

- **Configuration**: Update configuration patterns and parameter names

69

70

## Programmatic API

71

72

### Migration Functions

73

74

```python { .api }

75

def migrate(

76

ctx: typer.Context,

77

diff: bool = False,

78

interactive: bool = False,

79

) -> None:

80

"""Migrate langchain to the most recent version."""

81

82

def get_gritdir_path() -> Path:

83

"""Get the path to the grit directory."""

84

```

85

86

### Migration Generation Functions

87

88

Advanced utilities for generating migration patterns and analyzing code imports.

89

90

```python { .api }

91

def generate_raw_migrations(

92

from_package: str,

93

to_package: str,

94

filter_by_all: bool = False

95

) -> list[tuple[str, str]]:

96

"""

97

Generate raw migration patterns between packages.

98

99

Args:

100

from_package: Source package name

101

to_package: Target package name

102

filter_by_all: Whether to filter by __all__ exports only

103

104

Returns:

105

List of (from_import, to_import) tuples

106

"""

107

108

def generate_simplified_migrations(

109

from_package: str,

110

to_package: str,

111

filter_by_all: bool = True

112

) -> list[tuple[str, str]]:

113

"""

114

Generate simplified migration patterns with duplicate removal.

115

116

Args:

117

from_package: Source package name

118

to_package: Target package name

119

filter_by_all: Whether to filter by __all__ exports only

120

121

Returns:

122

List of unique (from_import, to_import) tuples

123

"""

124

125

def generate_top_level_imports(pkg: str) -> list[tuple[str, str]]:

126

"""

127

Generate migration patterns for top-level package imports.

128

129

Args:

130

pkg: Package name to analyze

131

132

Returns:

133

List of (old_import, new_import) tuples for top-level imports

134

"""

135

136

class ImportExtractor(ast.NodeVisitor):

137

"""

138

AST visitor for extracting import statements from Python code.

139

140

Attributes:

141

imports: List of discovered import statements

142

from_imports: List of discovered from-import statements

143

"""

144

145

def __init__(self) -> None:

146

"""Initialize the import extractor."""

147

148

def visit_Import(self, node: ast.Import) -> None:

149

"""Visit import statements."""

150

151

def visit_ImportFrom(self, node: ast.ImportFrom) -> None:

152

"""Visit from-import statements."""

153

```

154

155

**Usage Examples:**

156

157

```python

158

from langchain_cli.namespaces.migrate.generate.utils import generate_raw_migrations, generate_simplified_migrations, ImportExtractor

159

160

# Generate migration patterns

161

raw_migrations = generate_raw_migrations("langchain.llms", "langchain_community.llms")

162

print(f"Raw migrations: {raw_migrations}")

163

164

simplified_migrations = generate_simplified_migrations("langchain.embeddings", "langchain_openai")

165

print(f"Simplified migrations: {simplified_migrations}")

166

167

# Extract imports from code

168

import ast

169

code = """

170

from langchain.llms import OpenAI

171

from langchain.embeddings import OpenAIEmbeddings

172

import langchain.vectorstores

173

"""

174

175

tree = ast.parse(code)

176

extractor = ImportExtractor()

177

extractor.visit(tree)

178

print(f"Found imports: {extractor.from_imports}")

179

```

180

181

### Migration Implementation

182

183

The migration system:

184

185

1. **Pattern Loading**: Loads Grit patterns from embedded `.grit` directory

186

2. **Code Analysis**: Scans target codebase for applicable patterns using ImportExtractor

187

3. **Pattern Generation**: Uses migration generation functions to create transformation rules

188

4. **Transformation**: Applies pattern-based code transformations

189

5. **Validation**: Verifies transformation correctness

190

6. **Reporting**: Provides detailed migration results

191

192

## Migration Patterns

193

194

### Import Migrations

195

196

Common import pattern transformations:

197

198

```python

199

# Before (LangChain 0.1)

200

from langchain.llms import OpenAI

201

from langchain.embeddings import OpenAIEmbeddings

202

from langchain.vectorstores import Chroma

203

204

# After First Migration (Community)

205

from langchain_community.llms import OpenAI

206

from langchain_community.embeddings import OpenAIEmbeddings

207

from langchain_community.vectorstores import Chroma

208

209

# After Second Migration (Partner packages)

210

from langchain_openai import OpenAI, OpenAIEmbeddings

211

from langchain_chroma import Chroma

212

```

213

214

### Class Usage Updates

215

216

```python

217

# Before

218

llm = OpenAI(temperature=0.7)

219

embeddings = OpenAIEmbeddings()

220

221

# After

222

llm = OpenAI(temperature=0.7) # Same usage, different import

223

embeddings = OpenAIEmbeddings() # Same usage, different import

224

```

225

226

### Configuration Changes

227

228

```python

229

# Before (deprecated patterns)

230

from langchain.chains import ConversationChain

231

chain = ConversationChain(llm=llm, memory=memory)

232

233

# After (updated patterns)

234

from langchain.chains import ConversationChain

235

chain = ConversationChain(llm=llm, memory=memory) # Updated internally

236

```

237

238

## Best Practices

239

240

### Pre-Migration Preparation

241

242

1. **Backup Code**: Always backup your codebase before migration

243

2. **Version Control**: Commit changes before running migration

244

3. **Test Suite**: Ensure comprehensive test coverage

245

4. **Dependencies**: Review current LangChain dependency versions

246

247

### Migration Workflow

248

249

1. **Preview Changes**: Run with `--diff` to see planned changes

250

```bash

251

langchain migrate --diff

252

```

253

254

2. **Interactive Review**: Use interactive mode for careful review

255

```bash

256

langchain migrate --interactive

257

```

258

259

3. **Apply Changes**: Run migration to apply transformations

260

```bash

261

langchain migrate

262

```

263

264

4. **Validate Results**: Test migrated code thoroughly

265

```bash

266

python -m pytest tests/

267

```

268

269

5. **Update Dependencies**: Update `requirements.txt` or `pyproject.toml`

270

```bash

271

pip install langchain-openai langchain-anthropic

272

```

273

274

### Post-Migration Tasks

275

276

1. **Dependency Updates**: Add new partner packages to requirements

277

2. **Import Cleanup**: Remove unused imports and consolidate where possible

278

3. **Testing**: Run comprehensive test suite

279

4. **Documentation**: Update any documentation referring to old patterns

280

281

### Error Handling

282

283

Common migration issues and solutions:

284

285

- **Parse Errors**: Code syntax issues prevent pattern matching

286

- **Ambiguous Patterns**: Multiple transformation options for same code

287

- **Dependency Conflicts**: New packages have version conflicts

288

- **Import Errors**: Missing new dependency packages

289

- **Test Failures**: Functional changes requiring code updates

290

291

### Migration Validation

292

293

After migration, validate:

294

295

- **Import Resolution**: All imports resolve correctly

296

- **Functionality**: Core application features work as expected

297

- **Performance**: No performance regressions

298

- **Dependencies**: All required packages are installed

299

- **Tests**: Test suite passes completely

300

301

## Troubleshooting

302

303

### Common Issues

304

305

1. **Incomplete Migration**: Run migration twice for full transformation

306

2. **Missing Dependencies**: Install new partner packages manually

307

3. **Import Conflicts**: Resolve duplicate or conflicting imports

308

4. **Pattern Mismatches**: Some code may require manual updates

309

310

### Manual Updates

311

312

Some patterns may require manual intervention:

313

314

- Custom extensions to LangChain classes

315

- Complex inheritance hierarchies

316

- Dynamic import patterns

317

- Configuration-dependent code paths

318

319

### Recovery

320

321

If migration causes issues:

322

323

1. **Revert Changes**: Use version control to restore previous state

324

2. **Selective Migration**: Use Grit disable flags for problematic patterns

325

3. **Manual Migration**: Apply changes manually for complex cases

326

4. **Incremental Approach**: Migrate smaller code sections individually