Skip to content

Commit 96f9bf4

Browse files
committed
feature(agent-mode): integrated this new agent in langchain
1 parent ba7dce7 commit 96f9bf4

File tree

14 files changed

+2018
-19
lines changed

14 files changed

+2018
-19
lines changed

docs/langchain_agent.md

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
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.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
"scripts": {
1010
"dev": "pnpm --filter frai run start",
1111
"cli": "pnpm --filter frai run build && pnpm --filter frai exec node dist/index.js",
12+
"agent:frai": "pnpm --filter frai-agent exec pnpm start",
1213
"lint": "turbo lint",
1314
"test": "turbo test",
1415
"build": "turbo build"

packages/frai-agent/README.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# FRAI Agent
2+
3+
LangChain-powered concierge that wraps FRAI scanning and documentation workflows behind a conversational interface.
4+
5+
## Features
6+
- `scan_repository` tool wraps `Scanners.scanCodebase` to surface AI indicators in the current repo.
7+
- `generate_responsible_ai_docs` tool wraps `Documents.generateDocuments` to write `checklist.md`, `model_card.md`, and `risk_file.md`.
8+
- CLI entry point with single-turn and interactive modes (`pnpm agent:frai --interactive`).
9+
- Re-uses FRAI configuration to discover `OPENAI_API_KEY` from `.env` or global config.
10+
11+
## Getting Started
12+
1. Install dependencies (requires network access the first time):
13+
```bash
14+
pnpm install
15+
```
16+
2. Configure an OpenAI key via FRAI tooling or environment variables:
17+
```bash
18+
frai setup --global # or export OPENAI_API_KEY=...
19+
```
20+
3. Run the agent:
21+
```bash
22+
pnpm agent:frai "Scan the repo and summarise AI risks."
23+
```
24+
25+
## Interactive Mode
26+
Launch a chat-style session and inspect tool calls:
27+
```bash
28+
pnpm agent:frai --interactive --verbose
29+
```
30+
Use `exit`, `quit`, or `:q` to leave the REPL.
31+
32+
## Providing Questionnaire Answers
33+
Document generation requires the FRAI questionnaire structure:
34+
```bash
35+
pnpm agent:frai "Generate the docs with these answers: {
36+
\"core\": { \"name\": \"ReviewCopilot\", \"purpose\": \"assistant\", \"dataType\": \"personal\" },
37+
\"impact\": { \"stakeholders\": [\"developers\"], \"impactLevel\": \"medium\" },
38+
\"data\": { \"sources\": [\"internal docs\"], \"retention\": \"30 days\" },
39+
\"performance\": { \"metrics\": [\"accuracy\"], \"evaluation\": \"manual\" },
40+
\"monitoring\": { \"strategy\": \"daily review\", \"owners\": [\"ai-team\"] },
41+
\"bias\": { \"mitigations\": [\"red teaming\"], \"openConcerns\": \"none\" }
42+
}"
43+
```
44+
The agent will parse the JSON snippet, call the documentation tool, and report which files were written.
45+
46+
## API Usage
47+
```ts
48+
import { createFraIAgentExecutor } from "frai-agent";
49+
50+
const executor = await createFraIAgentExecutor();
51+
const result = await executor.invoke({ input: "scan the repository" });
52+
console.log(result.output);
53+
```
54+
55+
## Next Steps
56+
- Add additional FRAI tools (RAG indexing, evaluation reports).
57+
- Persist conversation memory across turns.
58+
- Write automated smoke tests with mocked LangChain tools.

packages/frai-agent/package.json

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
{
2+
"name": "frai-agent",
3+
"version": "0.0.1",
4+
"description": "LangChain-powered concierge for FRAI scanning and documentation",
5+
"type": "module",
6+
"main": "dist/index.js",
7+
"exports": {
8+
".": "./dist/index.js"
9+
},
10+
"files": [
11+
"dist/",
12+
"src/"
13+
],
14+
"scripts": {
15+
"build": "tsc --project tsconfig.json",
16+
"dev": "tsx --watch src/cli/run.ts",
17+
"lint": "eslint .",
18+
"start": "tsx src/cli/run.ts"
19+
},
20+
"dependencies": {
21+
"frai-core": "^0.0.1",
22+
"langchain": "^0.1.34",
23+
"@langchain/openai": "^0.0.12",
24+
"zod": "^3.22.4"
25+
},
26+
"devDependencies": {
27+
"tsx": "^4.7.1",
28+
"eslint": "^9.1.1",
29+
"vitest": "^1.4.0"
30+
},
31+
"keywords": [
32+
"frai",
33+
"langchain",
34+
"responsible-ai"
35+
],
36+
"author": "Sebastian Buzdugan",
37+
"license": "MIT",
38+
"repository": {
39+
"type": "git",
40+
"url": "git+https://github.com/sebastianbuzdugan/frai.git"
41+
},
42+
"homepage": "https://github.com/sebastianbuzdugan/frai#readme",
43+
"engines": {
44+
"node": ">=18.0.0"
45+
}
46+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import { ChatPromptTemplate, MessagesPlaceholder } from "langchain/prompts";
2+
import { AgentExecutor, createOpenAIToolsAgent } from "langchain/agents";
3+
import { ChatOpenAI } from "@langchain/openai";
4+
import type { BaseMessage } from "langchain/schema";
5+
6+
import { requireOpenAiApiKey } from "../config/env.js";
7+
import { generateDocumentsTool, scanRepositoryTool } from "../tools/index.js";
8+
import { SYSTEM_PROMPT } from "./prompt.js";
9+
10+
export interface AgentConfig {
11+
model?: string;
12+
temperature?: number;
13+
verbose?: boolean;
14+
}
15+
16+
export interface AgentRunOptions {
17+
input: string;
18+
history?: BaseMessage[];
19+
verbose?: boolean;
20+
}
21+
22+
export const createFraIAgentExecutor = async (config: AgentConfig = {}) => {
23+
requireOpenAiApiKey();
24+
25+
const llm = new ChatOpenAI({
26+
modelName: config.model ?? "gpt-4o-mini",
27+
temperature: config.temperature ?? 0
28+
});
29+
30+
const tools = [scanRepositoryTool, generateDocumentsTool];
31+
32+
const prompt = ChatPromptTemplate.fromMessages([
33+
["system", SYSTEM_PROMPT],
34+
new MessagesPlaceholder("chat_history"),
35+
["human", "{input}"],
36+
new MessagesPlaceholder("agent_scratchpad")
37+
]);
38+
39+
const agent = await createOpenAIToolsAgent({
40+
llm,
41+
tools,
42+
prompt
43+
});
44+
45+
return new AgentExecutor({
46+
agent,
47+
tools,
48+
verbose: config.verbose ?? false
49+
});
50+
};
51+
52+
export const runFraIAgent = async (options: AgentRunOptions) => {
53+
const executor = await createFraIAgentExecutor();
54+
return executor.invoke({
55+
input: options.input,
56+
chat_history: options.history ?? []
57+
});
58+
};
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
export const SYSTEM_PROMPT = `You are the FRAI doc concierge. Help responsible AI teams run repository scans and generate governance documents.
2+
3+
Responsibilities:
4+
- Decide whether to run a repository scan or generate documentation using the available tools.
5+
- Ask the user for any missing information before calling a tool. For document generation you need questionnaire answers covering: core, impact, data, performance, monitoring, and bias.
6+
- Summarize tool results clearly, highlight risks, and point to output file paths.
7+
- Never fabricate tool outputs. If a tool fails, explain why and suggest next steps.
8+
`;

0 commit comments

Comments
 (0)