-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.ts
More file actions
118 lines (103 loc) · 3.39 KB
/
app.ts
File metadata and controls
118 lines (103 loc) · 3.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
import express from 'express';
import bodyParser from 'body-parser';
import fetch from 'node-fetch'; // Import the fetch function
import Anthropic from '@anthropic-ai/sdk';
import * as dotenv from 'dotenv';
dotenv.config();
const app = express();
const port = 3000;
// Parse incoming JSON data
app.use(bodyParser.json());
// Set up using Tool
const tools: Anthropic.Beta.Tools.Tool[] = [
{
name: 'get_weather',
description: 'Get the weather for a specific location',
input_schema: {
type: 'object',
properties: { location: { type: 'string' } },
},
}
];
// Function that calls the OpenWeather API endpoint
async function get_weather() {
try {
//lat, long set for San Francisco, CA
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=37.8&lon=-122.41&appid=${process.env.OPENWEATHER_API_KEY}&units=imperial`
);
if (!response.ok) {
throw new Error(`Failed to fetch weather data. Status: ${response.status}`);
}
const responseData = await response.json(); // Parse JSON response
console.log(responseData);
return responseData;
} catch (error) {
console.error('Error fetching weather data:', error);
throw error; // Rethrow the error
}
}
// Switch function (necessary when you have many different types of tools you want to use)
const runFunction = async (name: string, args: any) => {
switch (name) {
case 'get_weather':
return await get_weather();
default:
return null;
}
}
// Initialize Anthropic client
const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
app.post('/chat', async (req, res) => {
try {
const userMessage: Anthropic.Beta.Tools.ToolsBetaMessageParam = {
role: 'user',
content: req.body.message,
};
const message = await client.beta.tools.messages.create({
model: 'claude-3-opus-20240229',
max_tokens: 1024,
messages: [userMessage],
tools,
});
if (message.stop_reason === 'tool_use') {
const tool = message.content.find((content): content is Anthropic.Beta.Tools.ToolUseBlock => content.type === 'tool_use');
if (tool) {
try {
const toolResult = await runFunction(tool.name, null);
// Extract temperature from toolResult
const toolResultText = toolResult?.main?.temp.toString() || 'Unknown';
const result = await client.beta.tools.messages.create({
model: 'claude-3-opus-20240229',
max_tokens: 1024,
messages: [
userMessage,
{ role: message.role, content: message.content },
{
role: 'user',
content: [
{
type: 'tool_result',
tool_use_id: tool.id,
content: [{ type: 'text', text: toolResultText }],
},
],
},
],
tools,
});
res.json({ response: result });
} catch (error) {
console.error('Error occurred while running tool function:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
}
}
} catch (error) {
console.error('Error occurred:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});