forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresearch.ts
More file actions
146 lines (133 loc) · 4.39 KB
/
Copy pathresearch.ts
File metadata and controls
146 lines (133 loc) · 4.39 KB
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
import { TavilySearchAPIRetriever } from "@langchain/community/retrievers/tavily_search_api";
import { HumanMessage, SystemMessage } from "@langchain/core/messages";
import { RunnableLambda } from "@langchain/core/runnables";
import { Annotation, END, MemorySaver, StateGraph } from "@langchain/langgraph";
import { ChatOpenAI } from "@langchain/openai";
interface AgentState {
topic: string;
searchResults?: string;
article?: string;
critique?: string;
}
const StateAnnotation = Annotation.Root({
agentState: Annotation<AgentState>({
value: (x: AgentState, y: AgentState) => y,
default: () => ({
topic: "",
}),
}),
});
function model() {
return new ChatOpenAI({
temperature: 0,
modelName: "gpt-3.5-turbo-0125",
});
}
async function search(state: typeof StateAnnotation.State) {
const retriever = new TavilySearchAPIRetriever({ k: 10 });
let topic = state.agentState.topic;
if (topic.length < 5) topic = "topic: " + topic;
const docs = await retriever.invoke(topic);
return {
agentState: { ...state.agentState, searchResults: JSON.stringify(docs) },
};
}
async function curate(state: typeof StateAnnotation.State) {
const response = await model().invoke(
[
new SystemMessage(
'Return 5 most relevant article URLs as JSON: {urls: ["url1",...]}',
),
new HumanMessage(
`Topic: ${state.agentState.topic}\nArticles: ${state.agentState.searchResults}`,
),
],
{ response_format: { type: "json_object" } },
);
const urls = JSON.parse(response.content as string).urls;
const searchResults = JSON.parse(state.agentState.searchResults!);
const filtered = searchResults.filter((r: any) =>
urls.includes(r.metadata.source),
);
return {
agentState: {
...state.agentState,
searchResults: JSON.stringify(filtered),
},
};
}
async function write(state: typeof StateAnnotation.State) {
const response = await model().invoke([
new SystemMessage("Write a 5-paragraph article in markdown."),
new HumanMessage(
`Topic: ${state.agentState.topic}\nSources: ${state.agentState.searchResults}`,
),
]);
return {
agentState: { ...state.agentState, article: response.content as string },
};
}
async function critique(state: typeof StateAnnotation.State) {
const feedback = state.agentState.critique
? `Previous critique: ${state.agentState.critique}`
: "";
const response = await model().invoke([
new SystemMessage(
"Review article. Return [DONE] if good, or provide brief feedback.",
),
new HumanMessage(`${feedback}\nArticle: ${state.agentState.article}`),
]);
const content = response.content as string;
return {
agentState: {
...state.agentState,
critique: content.includes("[DONE]") ? undefined : content,
},
};
}
async function revise(state: typeof StateAnnotation.State) {
const response = await model().invoke([
new SystemMessage("Edit article based on critique."),
new HumanMessage(
`Article: ${state.agentState.article}\nCritique: ${state.agentState.critique}`,
),
]);
return {
agentState: { ...state.agentState, article: response.content as string },
};
}
function shouldContinue(state: typeof StateAnnotation.State) {
return state.agentState.critique === undefined ? "end" : "continue";
}
export async function createNewspaperWorkflow() {
const workflow = new StateGraph(StateAnnotation)
.addNode("search", new RunnableLambda({ func: search }))
.addNode("curate", new RunnableLambda({ func: curate }))
.addNode("write", new RunnableLambda({ func: write }))
.addNode("critique", new RunnableLambda({ func: critique }))
.addNode("revise", new RunnableLambda({ func: revise }))
.addEdge("search", "curate")
.addEdge("curate", "write")
.addEdge("write", "critique")
.addConditionalEdges("critique", shouldContinue, {
continue: "revise",
end: END,
})
.addEdge("revise", "critique")
.addEdge("__start__", "search");
const checkpointer = new MemorySaver();
return workflow.compile({ checkpointer });
}
export async function researchWithLangGraph(topic: string) {
const app = await createNewspaperWorkflow();
const result = await app.invoke(
{ agentState: { topic } },
{
configurable: { thread_id: "research-" + Date.now(), checkpoint_id: "1" },
},
);
return result?.agentState?.article?.replace(
/<FEEDBACK>[\s\S]*?<\/FEEDBACK>/g,
"",
);
}