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

utilities.mddocs/

0

# Utility Functions

1

2

Core utility functions for package management, git operations, project configuration, and event tracking used throughout the CLI. These utilities provide the foundational functionality that powers the CLI commands.

3

4

## Capabilities

5

6

### Package Management

7

8

Utilities for discovering and managing LangChain packages and their configurations.

9

10

```python { .api }

11

def get_package_root(cwd: Optional[Path] = None) -> Path:

12

"""

13

Get package root directory by traversing upward for pyproject.toml.

14

15

Args:

16

cwd: Starting directory (defaults to current directory)

17

18

Returns:

19

Path to directory containing pyproject.toml

20

21

Raises:

22

FileNotFoundError: If no pyproject.toml found in directory tree

23

"""

24

25

def get_langserve_export(filepath: Path) -> LangServeExport:

26

"""

27

Get LangServe export information from a pyproject.toml file.

28

29

Args:

30

filepath: Path to pyproject.toml file

31

32

Returns:

33

LangServeExport with module, attr, and package_name

34

35

Raises:

36

KeyError: If invalid LangServe PyProject.toml format

37

"""

38

```

39

40

**Usage Examples:**

41

42

```python

43

from langchain_cli.utils.packages import get_package_root, get_langserve_export

44

45

# Find project root

46

project_root = get_package_root()

47

print(f"Project root: {project_root}")

48

49

# Get LangServe export info

50

pyproject_path = project_root / "pyproject.toml"

51

export_info = get_langserve_export(pyproject_path)

52

print(f"Module: {export_info['module']}")

53

print(f"Attribute: {export_info['attr']}")

54

print(f"Package: {export_info['package_name']}")

55

```

56

57

### Git Operations

58

59

Utilities for managing git repositories, dependency parsing, and template distribution.

60

61

```python { .api }

62

def parse_dependency_string(

63

dep: Optional[str],

64

repo: Optional[str],

65

branch: Optional[str],

66

api_path: Optional[str],

67

) -> DependencySource:

68

"""

69

Parse a dependency string into a DependencySource.

70

71

Args:

72

dep: Dependency specification (template name or git URL)

73

repo: GitHub repository override

74

branch: Git branch/ref override

75

api_path: Custom API path for template

76

77

Returns:

78

DependencySource with git, ref, subdirectory, and metadata

79

80

Raises:

81

ValueError: If dependency format is invalid

82

"""

83

84

def parse_dependencies(

85

dependencies: Optional[list[str]],

86

repo: list[str],

87

branch: list[str],

88

api_path: list[str],

89

) -> list[DependencySource]:

90

"""

91

Parse multiple dependencies with parameter expansion.

92

93

Args:

94

dependencies: List of dependency strings

95

repo: Repository specifications (expandable)

96

branch: Branch specifications (expandable)

97

api_path: API path specifications (expandable)

98

99

Returns:

100

List of DependencySource objects

101

102

Raises:

103

ValueError: If parameter lengths don't match

104

"""

105

106

def update_repo(gitstring: str, ref: Optional[str], repo_dir: Path) -> Path:

107

"""

108

Update a git repository to the specified ref.

109

110

Args:

111

gitstring: Git repository URL

112

ref: Git reference (branch, tag, commit)

113

repo_dir: Directory for repository cache

114

115

Returns:

116

Path to updated repository

117

"""

118

119

def copy_repo(source: Path, destination: Path) -> None:

120

"""

121

Copy a repository, ignoring git folders.

122

123

Args:

124

source: Source repository path

125

destination: Destination path

126

127

Raises:

128

FileNotFoundError: If source doesn't exist

129

"""

130

```

131

132

**Usage Examples:**

133

134

```python

135

from langchain_cli.utils.git import parse_dependencies, update_repo, copy_repo

136

137

# Parse template dependencies

138

deps = parse_dependencies(

139

dependencies=["template1", "git+https://github.com/user/template.git"],

140

repo=[],

141

branch=["v0.2"],

142

api_path=[],

143

)

144

145

# Update repository

146

repo_path = update_repo(

147

"https://github.com/langchain-ai/langchain.git",

148

"master",

149

Path("/tmp/repos")

150

)

151

152

# Copy template

153

copy_repo(repo_path / "templates/template1", Path("./packages/template1"))

154

```

155

156

### Project Configuration

157

158

Utilities for managing pyproject.toml files and dependency configuration.

159

160

```python { .api }

161

def add_dependencies_to_pyproject_toml(

162

pyproject_toml: Path,

163

local_editable_dependencies: Iterable[tuple[str, Path]],

164

) -> None:

165

"""

166

Add editable dependencies to pyproject.toml.

167

168

Args:

169

pyproject_toml: Path to pyproject.toml file

170

local_editable_dependencies: Iterable of (name, path) tuples

171

"""

172

173

def remove_dependencies_from_pyproject_toml(

174

pyproject_toml: Path,

175

local_editable_dependencies: Iterable[str],

176

) -> None:

177

"""

178

Remove dependencies from pyproject.toml.

179

180

Args:

181

pyproject_toml: Path to pyproject.toml file

182

local_editable_dependencies: Iterable of dependency names

183

"""

184

```

185

186

**Usage Examples:**

187

188

```python

189

from langchain_cli.utils.pyproject import add_dependencies_to_pyproject_toml, remove_dependencies_from_pyproject_toml

190

191

# Add local dependencies

192

add_dependencies_to_pyproject_toml(

193

Path("pyproject.toml"),

194

[("template1", Path("packages/template1")), ("template2", Path("packages/template2"))]

195

)

196

197

# Remove dependencies

198

remove_dependencies_from_pyproject_toml(

199

Path("pyproject.toml"),

200

["template1", "template2"]

201

)

202

```

203

204

### Event Tracking

205

206

Utilities for analytics and usage tracking.

207

208

```python { .api }

209

def create_events(events: list[EventDict]) -> Optional[dict[str, Any]]:

210

"""

211

Create analytics events.

212

213

Args:

214

events: List of event dictionaries

215

216

Returns:

217

Response data from analytics service or None on error

218

"""

219

```

220

221

**Usage Examples:**

222

223

```python

224

from langchain_cli.utils.events import create_events

225

226

# Track CLI usage

227

events = [

228

{

229

"event": "template_added",

230

"properties": {

231

"template_name": "rag-template",

232

"source": "github"

233

}

234

}

235

]

236

237

response = create_events(events)

238

```

239

240

### Development Server Creation

241

242

Utilities for creating demo servers with different playground configurations for template development and testing.

243

244

```python { .api }

245

def create_demo_server(

246

*,

247

config_keys: Sequence[str] = (),

248

playground_type: Literal["default", "chat"] = "default"

249

) -> FastAPI:

250

"""

251

Create a demo server for templates with configurable playground.

252

253

Args:

254

config_keys: Configuration keys to expose for dynamic configuration

255

playground_type: Type of playground interface ("default" or "chat")

256

257

Returns:

258

FastAPI application instance configured for template serving

259

"""

260

261

def create_demo_server_configurable() -> FastAPI:

262

"""

263

Create a demo server with configurable route for dynamic template parameters.

264

265

Returns:

266

FastAPI application with configurable endpoint

267

"""

268

269

def create_demo_server_chat() -> FastAPI:

270

"""

271

Create a demo server with chat playground interface.

272

273

Returns:

274

FastAPI application with chat interface

275

"""

276

```

277

278

**Usage Examples:**

279

280

```python

281

from langchain_cli.dev_scripts import create_demo_server, create_demo_server_configurable, create_demo_server_chat

282

283

# Create basic demo server

284

app = create_demo_server()

285

286

# Create server with configurable parameters

287

app_config = create_demo_server_configurable()

288

289

# Create server with chat interface

290

app_chat = create_demo_server_chat()

291

292

# Create server with specific configuration keys

293

app_custom = create_demo_server(

294

config_keys=["temperature", "model_name"],

295

playground_type="chat"

296

)

297

```

298

299

### GitHub Integration

300

301

Utilities for discovering and listing LangChain templates from GitHub repositories.

302

303

```python { .api }

304

def list_packages(*, contains: Optional[str] = None) -> list[str]:

305

"""

306

List available LangChain template packages from GitHub.

307

308

Args:

309

contains: Filter templates containing this substring

310

311

Returns:

312

List of template package names

313

314

Raises:

315

HTTPException: If GitHub API request fails

316

"""

317

```

318

319

**Usage Examples:**

320

321

```python

322

from langchain_cli.utils.github import list_packages

323

324

# List all available templates

325

all_templates = list_packages()

326

print(f"Found {len(all_templates)} templates")

327

328

# Search for specific templates

329

rag_templates = list_packages(contains="rag")

330

print(f"RAG templates: {rag_templates}")

331

332

# Search for OpenAI templates

333

openai_templates = list_packages(contains="openai")

334

print(f"OpenAI templates: {openai_templates}")

335

```

336

337

### Find and Replace

338

339

Utilities for template processing and string replacement operations across files and directories.

340

341

```python { .api }

342

def find_and_replace(source: str, replacements: dict[str, str]) -> str:

343

"""

344

Perform string replacements in source text.

345

346

Args:

347

source: Source text to process

348

replacements: Dictionary of find->replace mappings

349

350

Returns:

351

Processed text with replacements applied

352

"""

353

354

def replace_file(source: Path, replacements: dict[str, str]) -> None:

355

"""

356

Apply string replacements to a file in-place.

357

358

Args:

359

source: Path to file to modify

360

replacements: Dictionary of find->replace mappings

361

362

Raises:

363

FileNotFoundError: If source file doesn't exist

364

PermissionError: If file cannot be written

365

"""

366

367

def replace_glob(parent: Path, glob: str, replacements: dict[str, str]) -> None:

368

"""

369

Apply string replacements to all files matching glob pattern.

370

371

Args:

372

parent: Parent directory to search

373

glob: Glob pattern for file matching

374

replacements: Dictionary of find->replace mappings

375

376

Raises:

377

FileNotFoundError: If parent directory doesn't exist

378

"""

379

```

380

381

**Usage Examples:**

382

383

```python

384

from langchain_cli.utils.find_replace import find_and_replace, replace_file, replace_glob

385

from pathlib import Path

386

387

# Replace text in string

388

replacements = {

389

"__package_name__": "my-integration",

390

"__ModuleName__": "MyIntegration"

391

}

392

393

processed_text = find_and_replace("Template: __package_name__", replacements)

394

print(processed_text) # "Template: my-integration"

395

396

# Replace in single file

397

replace_file(Path("template.py"), replacements)

398

399

# Replace in all Python files

400

replace_glob(Path("src/"), "**/*.py", replacements)

401

```

402

403

### Additional Utilities

404

405

The CLI includes several other utility modules:

406

407

- **langchain_cli.constants**: Configuration constants and defaults

408

409

## Type Definitions

410

411

```python { .api }

412

class LangServeExport(TypedDict):

413

"""Fields from pyproject.toml relevant to LangServe."""

414

module: str # Import module path

415

attr: str # Attribute to import

416

package_name: str # Package name

417

418

class DependencySource(TypedDict):

419

"""Dependency source information."""

420

git: str # Git repository URL

421

ref: Optional[str] # Git reference (branch/tag/commit)

422

subdirectory: Optional[str] # Subdirectory within repository

423

api_path: Optional[str] # Custom API path

424

event_metadata: dict[str, Any] # Analytics metadata

425

426

class EventDict(TypedDict):

427

"""Event data structure for analytics tracking."""

428

event: str # Event name

429

properties: Optional[dict[str, Any]] # Event properties

430

```

431

432

## Configuration Constants

433

434

```python { .api }

435

# Default repository settings

436

DEFAULT_GIT_REPO = "https://github.com/langchain-ai/langchain.git"

437

DEFAULT_GIT_SUBDIRECTORY = "templates"

438

DEFAULT_GIT_REF = "master"

439

440

# Analytics configuration

441

WRITE_KEY = "310apTK0HUFl4AOv" # Analytics write key

442

```

443

444

## Error Handling

445

446

### Common Error Patterns

447

448

- **FileNotFoundError**: Missing pyproject.toml or template files

449

- **KeyError**: Invalid LangServe configuration format

450

- **ValueError**: Invalid dependency string formats or parameter mismatches

451

- **HTTPException**: Network errors during git operations or analytics

452

- **OSError**: File system permission or access issues

453

454

### Error Recovery

455

456

Utilities include comprehensive error handling:

457

458

- **Graceful Degradation**: Non-critical operations continue on errors

459

- **User Feedback**: Clear error messages with actionable guidance

460

- **Retry Logic**: Network operations include retry mechanisms

461

- **Validation**: Input validation prevents common error conditions

462

463

### Debugging Support

464

465

Enable detailed logging for troubleshooting:

466

467

```python

468

import logging

469

logging.basicConfig(level=logging.DEBUG)

470

471

# Utilities will provide detailed debug information

472

```