chatgpt-api/examples/ts-sdks/openai/bin/weather.ts

57 wiersze
1.4 KiB
TypeScript
Czysty Zwykły widok Historia

2024-06-02 22:30:39 +00:00
import 'dotenv/config'
import { AgenticToolClient } from '@agentic/platform-tool-client'
2024-06-02 22:30:39 +00:00
import OpenAI from 'openai'
async function main() {
const searchTool = await AgenticToolClient.fromIdentifier('@agentic/search')
2024-06-02 22:30:39 +00:00
const openai = new OpenAI()
const messages: OpenAI.ChatCompletionMessageParam[] = [
{
role: 'system',
content: 'You are a helpful assistant. Be as concise as possible.'
},
{ role: 'user', content: 'What is the weather in San Francisco?' }
]
2024-06-02 23:13:24 +00:00
{
// First call to OpenAI to invoke the tool
2024-06-02 23:13:24 +00:00
const res = await openai.chat.completions.create({
messages,
2024-08-04 10:55:47 +00:00
model: 'gpt-4o-mini',
2024-06-02 23:13:24 +00:00
temperature: 0,
tools: searchTool.functions.toolSpecs,
2024-06-02 23:13:24 +00:00
tool_choice: 'required'
})
const message = res.choices[0]!.message!
const toolCall = message.tool_calls![0]!.function!
const toolResult = await searchTool.callTool(
toolCall.name,
toolCall.arguments
)
2024-06-02 23:13:24 +00:00
messages.push(message)
messages.push({
role: 'tool',
tool_call_id: message.tool_calls![0]!.id,
2024-06-02 23:13:24 +00:00
content: JSON.stringify(toolResult)
})
}
{
// Second call to OpenAI to generate a text response
const res = await openai.chat.completions.create({
messages,
2024-08-04 10:55:47 +00:00
model: 'gpt-4o-mini',
2024-06-02 23:13:24 +00:00
temperature: 0,
tools: searchTool.functions.toolSpecs
2024-06-02 23:13:24 +00:00
})
const message = res.choices?.[0]?.message
console.log(message?.content)
2024-06-02 23:13:24 +00:00
}
2024-06-02 22:30:39 +00:00
}
await main()