-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathconversation_executor.ts
More file actions
171 lines (148 loc) · 5.45 KB
/
conversation_executor.ts
File metadata and controls
171 lines (148 loc) · 5.45 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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/**
* Multi-turn conversation executor
* Handles the loop: LLM → Tool calls → Execute tools → Add to messages → Repeat
*/
// eslint-disable-next-line import/extensions
import type { ChatCompletionMessageParam, ChatCompletionTool } from 'openai/resources/chat/completions';
import { mcpToolsToOpenAiTools } from '../shared/openai_tools.js';
import { AGENT_SYSTEM_PROMPT, MAX_CONVERSATION_TURNS, MODELS } from './config.js';
import type { LlmClient } from './llm_client.js';
import type { McpClient } from './mcp_client.js';
import type { ConversationHistory, ConversationTurn } from './types.js';
export type ConversationExecutorOptions = {
/** User's initial prompt */
userPrompt: string;
/** MCP client for tool execution and dynamic tool fetching */
mcpClient: McpClient;
/** LLM client for chat completions */
llmClient: LlmClient;
/** Maximum number of turns (optional, uses config default) */
maxTurns?: number;
/** Model to use (optional, uses config default) */
model?: string;
/** Additional instructions from MCP server (optional) */
serverInstructions?: string | null;
}
/**
* Execute a multi-turn conversation with tool calling
* Tools are fetched dynamically from MCP after each turn
*/
export async function executeConversation(
options: ConversationExecutorOptions,
): Promise<ConversationHistory> {
const {
userPrompt,
mcpClient,
llmClient,
maxTurns = MAX_CONVERSATION_TURNS,
model = MODELS.agent,
serverInstructions,
} = options;
const turns: ConversationTurn[] = [];
// Build system prompt with optional server instructions
let systemPrompt = AGENT_SYSTEM_PROMPT;
if (serverInstructions) {
systemPrompt += `\n\n## MCP Server Instructions\n\n${serverInstructions}`;
}
const messages: ChatCompletionMessageParam[] = [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userPrompt },
];
let turnNumber = 0;
let completed = false;
// Fetch tools initially
let tools: ChatCompletionTool[] = mcpToolsToOpenAiTools(mcpClient.getTools());
while (turnNumber < maxTurns) {
turnNumber++;
// Call LLM with current conversation state and current tools
const llmResponse = await llmClient.callLlm(messages, model, tools);
// Check if LLM wants to call tools
if (!llmResponse.toolCalls || llmResponse.toolCalls.length === 0) {
// No tool calls - this is the final response
turns.push({
turnNumber,
toolCalls: [],
toolResults: [],
finalResponse: llmResponse.content || '',
});
completed = true;
break;
}
// LLM wants to call tools
const turn: ConversationTurn = {
turnNumber,
toolCalls: llmResponse.toolCalls.map((tc) => ({
name: tc.name,
arguments: JSON.parse(tc.arguments),
})),
toolResults: [],
};
// Add assistant message with tool calls to conversation
messages.push({
role: 'assistant',
content: llmResponse.content,
tool_calls: llmResponse.toolCalls.map((tc) => ({
id: tc.id,
type: 'function' as const,
function: {
name: tc.name,
arguments: tc.arguments,
},
})),
});
// Execute each tool call
for (const toolCall of llmResponse.toolCalls) {
let args: Record<string, unknown>;
try {
args = JSON.parse(toolCall.arguments);
} catch (error) {
// Invalid JSON arguments
const errorResult = {
toolName: toolCall.name,
success: false,
error: `Failed to parse arguments: ${error}`,
};
turn.toolResults.push(errorResult);
// Add error to conversation
messages.push({
role: 'tool',
tool_call_id: toolCall.id,
content: JSON.stringify({ error: errorResult.error }),
});
continue;
}
// Execute tool via MCP
const result = await mcpClient.callTool({
name: toolCall.name,
arguments: args,
});
turn.toolResults.push(result);
// Add tool result to conversation
if (result.success) {
messages.push({
role: 'tool',
tool_call_id: toolCall.id,
content: JSON.stringify(result.result),
});
} else {
messages.push({
role: 'tool',
tool_call_id: toolCall.id,
content: JSON.stringify({ error: result.error }),
});
}
}
turns.push(turn);
// Refresh tools after executing tool calls
// Tools can change dynamically (e.g., add-actor adds new tools)
// Fetch fresh tools from MCP server for next turn
tools = mcpToolsToOpenAiTools(mcpClient.getTools());
}
return {
userPrompt,
turns,
completed,
hitMaxTurns: turnNumber >= maxTurns && !completed,
totalTurns: turnNumber,
};
}