|
| 1 | +# LangChain FRAI Doc Concierge – Implementation Plan |
| 2 | + |
| 3 | +## 1. Problem & Opportunity |
| 4 | +- **Challenge:** Teams want the FRAI scan + documentation workflows but do not always remember CLI flags or wish to embed them inside chat surfaces (Slack, VS Code, internal portals). |
| 5 | +- **Pain Point Today:** Manual CLI runs, context switching, repeated explanations for how to produce `checklist.md`, `model_card.md`, and `risk_file.md`. |
| 6 | +- **Opportunity:** Wrap FRAI’s existing capabilities in a conversational agent so stakeholders can say “scan the repo and draft the docs,” then receive structured outputs instantly. |
| 7 | + |
| 8 | +## 2. Success Criteria |
| 9 | +- Single command (or exported module) that accepts natural-language prompts and triggers FRAI workflows via LangChain. |
| 10 | +- Agent returns actionable artifacts: scan summary + generated documentation locations. |
| 11 | +- Implementation fits existing repo patterns: TypeScript tooling, pnpm workspace, FRAI core APIs, documented in `docs/`. |
| 12 | +- Tests or manual verification instructions demonstrate end-to-end execution. |
| 13 | + |
| 14 | +## 3. High-Level Architecture |
| 15 | +| Component | Purpose | Notes | |
| 16 | +|-----------|---------|-------| |
| 17 | +| LangChain Agent Executor | Orchestrates tool selection and execution. | Use OpenAI tool-calling agent for simplicity and reliability. | |
| 18 | +| FRAI Tool Wrappers | Expose `scanRepo` and `generateDocs` as LangChain tools. | Thin adapters around `frai-core` APIs. | |
| 19 | +| Memory / Context | Optional short-term conversation memory. | Keep initial version stateless to stay simple. | |
| 20 | +| CLI Entrypoint | Provides easy invocation (`pnpm run agent:frai`). | Streams agent responses for good UX. | |
| 21 | +| Config Layer | Reads FRAI + model keys (`.env`, CLI config). | Reuse existing config helpers where possible. | |
| 22 | + |
| 23 | +## 4. Tech Choices |
| 24 | +- **Language:** TypeScript (align with repo, type safety, shared configs). |
| 25 | +- **Runtime:** Node.js ≥ 18 (already required). |
| 26 | +- **Package Management:** pnpm workspace (existing). |
| 27 | +- **LLM Provider:** OpenAI via `ChatOpenAI` (consistent with FRAI usage); provider is swappable. |
| 28 | +- **Prompting:** LangChain’s `createOpenAIToolsAgent` with a concise system prompt describing responsibilities and guardrails. |
| 29 | + |
| 30 | +## 5. Target Folder Structure |
| 31 | +``` |
| 32 | +packages/ |
| 33 | + frai-agent/ |
| 34 | + package.json |
| 35 | + tsconfig.json (extends repo root) |
| 36 | + src/ |
| 37 | + index.ts # CLI entrypoint |
| 38 | + agent/ |
| 39 | + prompt.ts # System prompt + message templates |
| 40 | + executor.ts # Agent creation + streaming helpers |
| 41 | + tools/ |
| 42 | + scan-tool.ts # Wrapper around Scanners.scanCodebase |
| 43 | + docs-tool.ts # Wrapper around Documents.generateDocuments |
| 44 | + config/ |
| 45 | + env.ts # Key loading (reuse frai-core if possible) |
| 46 | + cli/ |
| 47 | + run.ts # Thin wrapper to execute agent from CLI command |
| 48 | + README.md # Package usage doc (generated later) |
| 49 | +``` |
| 50 | + |
| 51 | +## 6. Implementation Steps |
| 52 | +1. **Scaffold Package** |
| 53 | + - Add `packages/frai-agent` workspace with TypeScript config (extends root settings). |
| 54 | + - Declare dependencies: `frai-core`, `langchain`, `@langchain/openai`, `zod`, `tsx` (for dev run), and shared lint configs. |
| 55 | +2. **Environment Handling** |
| 56 | + - Reuse FRAI config utilities if available; otherwise load `.env` + FRAI config to fetch OpenAI API key. |
| 57 | + - Validate presence of `OPENAI_API_KEY`; guide user on setup. |
| 58 | +3. **Tool Adapters** |
| 59 | + - `scan-tool.ts`: Accept optional `path`, call `Scanners.scanCodebase({ cwd: path ?? process.cwd() })`, return structured summary (counts, flags, high-risk indicators, raw JSON path). |
| 60 | + - `docs-tool.ts`: Accept optional `path` and `overwrite` flag; call `Documents.generateDocuments`; return paths to outputs (`checklist.md`, `model_card.md`, `risk_file.md`). |
| 61 | + - Define input/output schemas with `zod`, register as LangChain tools via `tool()` helper. |
| 62 | +4. **Agent Construction** |
| 63 | + - `prompt.ts`: system message (mission, guardrails, fallback behavior). |
| 64 | + - `executor.ts`: instantiate `ChatOpenAI` (model default `gpt-4.1-mini` or `gpt-4o-mini`), pass tools to `createOpenAIToolsAgent`, wrap in `AgentExecutor`. |
| 65 | + - Provide helper `runAgent(input: string)` returning final text + intermediate tool outputs. |
| 66 | +5. **CLI Interface** |
| 67 | + - `cli/run.ts`: parse command-line input (`pnpm agent:frai "scan the repo"`), call `runAgent`, stream tokens or print steps. |
| 68 | + - Handle empty input by prompting user for interactive question. |
| 69 | +6. **DX Enhancements** |
| 70 | + - Add npm script in root (`"agent:frai": "pnpm --filter frai-agent exec pnpm start"`). |
| 71 | + - Document usage in new package README (created in `packages/frai-agent/README.md`). |
| 72 | +7. **Testing & Verification** |
| 73 | + - Manual smoke test instructions in this README. |
| 74 | + - Optionally add automated test with mocked FRAI APIs (stretch goal). |
| 75 | +8. **Documentation** |
| 76 | + - Update `docs/langchain-agent/README.md` (this file) with validation steps once implemented. |
| 77 | + - Summarize in root `README.md` under “Integrations” (follow-up PR). |
| 78 | + |
| 79 | +## 7. User Flow |
| 80 | +1. User installs dependencies (`pnpm install` already covers new package). |
| 81 | +2. Ensure `OPENAI_API_KEY` configured (via `frai setup --global` or `.env`). |
| 82 | +3. Run `pnpm agent:frai "<request>"`. |
| 83 | +4. Agent may call `scanRepo` (returns summary) and/or `generateDocs` (writes docs). |
| 84 | +5. CLI prints actionable output with file paths and next steps. |
| 85 | + |
| 86 | +## 8. UX Guidelines |
| 87 | +- Print clear status messages before/after tool calls. |
| 88 | +- Surface document paths relative to repo root. |
| 89 | +- On errors (missing key, scan failure), show friendly guidance. |
| 90 | +- Keep responses concise; highlight high-risk findings and doc paths. |
| 91 | + |
| 92 | +## 9. Validation Checklist |
| 93 | +- [ ] `pnpm agent:frai "scan the repo"` returns scan summary without error. |
| 94 | +- [ ] `pnpm agent:frai "generate the docs"` creates/updates documentation files. |
| 95 | +- [ ] Combined instruction triggers sequential tool usage. |
| 96 | +- [ ] CLI handles invalid prompts gracefully (responds with guidance). |
| 97 | +- [ ] Works from any repo subdirectory when `--cwd` option provided (stretch goal). |
| 98 | + |
| 99 | +### Manual Validation Hints |
| 100 | +- Configure `OPENAI_API_KEY` via `frai setup` or by exporting an environment variable before running the agent. |
| 101 | +- Run `pnpm agent:frai "scan the repository for AI indicators"` to exercise the scan tool. |
| 102 | +- For documentation, provide structured answers: |
| 103 | + ```bash |
| 104 | + pnpm agent:frai "Generate documentation with this context: {\"answersJson\": \"{...}\"}" |
| 105 | + ``` |
| 106 | + In interactive mode, the agent will prompt for missing sections if the JSON is incomplete. |
| 107 | +- Use `pnpm agent:frai --interactive` for a multi-turn session and `--verbose` to inspect tool input/output pairs. |
| 108 | + |
| 109 | +## 10. Future Enhancements |
| 110 | +- Add memory (LangChain `BufferMemory`) for multi-turn chats. |
| 111 | +- Support additional tools (`rag` indexing, `eval` reports). |
| 112 | +- Publish as reusable library or Slack bot (wrap CLI script). |
| 113 | +- Introduce tests with mock LangChain tools for CI determinism. |
| 114 | + |
| 115 | +## 11. Open Questions |
| 116 | +- Do we reuse FRAI CLI logging utilities for consistent style? |
| 117 | +- Should generated docs automatically open diff viewer or just print paths? |
| 118 | +- How do we handle long-running scans (progress updates, spinners)? |
| 119 | + |
| 120 | +This plan keeps the implementation lightweight, leverages existing FRAI-core capabilities, and delivers a high-impact productivity win through a conversational interface. |
| 121 | + |
| 122 | + |
| 123 | + |
| 124 | +• Shipped a new frai-agent workspace that wraps FRAI scans and docs generation behind a LangChain-powered CLI and tools. |
| 125 | + |
| 126 | + - packages/frai-agent/src/cli/run.ts:1 – added single-turn and interactive REPL entrypoint with --model, --verbose, and tool |
| 127 | + logging. |
| 128 | + - packages/frai-agent/src/tools/scan-tool.ts:10 – exposed scan_repository LangChain tool returning concise AI indicator summaries. |
| 129 | + - packages/frai-agent/src/tools/docs-tool.ts:28 – added generate_responsible_ai_docs tool that parses questionnaire JSON, writes |
| 130 | + FRAI markdown, and respects overwrite flags. |
| 131 | + - packages/frai-agent/src/agent/executor.ts:22 & src/agent/prompt.ts:1 – wired ChatGPT-based tool-calling agent with guardrails |
| 132 | + plus helper exports for reuse. |
| 133 | + - packages/frai-agent/src/config/env.ts:10 – reused FRAI key-store logic to resolve OPENAI_API_KEY automatically. |
| 134 | + - packages/frai-agent/package.json:1, tsconfig.json:1, README.md:1 – scaffolded package metadata, TypeScript config, and usage |
| 135 | + docs; root package.json:10 now exposes pnpm agent:frai. |
| 136 | + - docs/langchain-agent/README.md:51 – refreshed implementation plan with actual DX steps and validation hints. |
| 137 | + |
| 138 | + Tests not run: new dependencies (langchain, @langchain/openai, tsx) aren’t installed in this sandbox. |
| 139 | + |
| 140 | + Next steps: |
| 141 | + |
| 142 | + 1. pnpm install (or pnpm install --filter frai-agent...) to pull new dependencies and update the lockfile. |
| 143 | + 2. Validate: pnpm agent:frai "scan the repository for AI indicators" and try --interactive --verbose to inspect tool calls. |
| 144 | + 3. Provide full questionnaire JSON in a prompt to confirm docs generation writes checklist.md, model_card.md, and risk_file.md. |
0 commit comments