1 | |
2 | type Telnyx = { |
3 | apiKey: string |
4 | } |
5 | |
6 | * Create a chat completion |
7 | * Chat with a language model. This endpoint is consistent with the [OpenAI Chat Completions API](https://platform.openai.com/docs/api-reference/chat) and may be used with the OpenAI JS or Python SDK. |
8 | */ |
9 | export async function main( |
10 | auth: Telnyx, |
11 | body: { |
12 | messages: { |
13 | content: string | { type: 'text' | 'image_url'; text?: string; image_url?: string }[] |
14 | role: 'system' | 'user' | 'assistant' | 'tool' |
15 | }[] |
16 | model?: string |
17 | stream?: false | true |
18 | temperature?: number |
19 | max_tokens?: number |
20 | tools?: |
21 | | { |
22 | type: 'function' |
23 | function: { name: string; description?: string; parameters?: {} } |
24 | } |
25 | | { |
26 | type: 'retrieval' |
27 | retrieval: { bucket_ids: string[]; max_num_results?: number } |
28 | }[] |
29 | tool_choice?: 'none' | 'auto' | 'required' |
30 | response_format?: { type: 'text' | 'json_object' } |
31 | guided_json?: {} |
32 | guided_regex?: string |
33 | guided_choice?: string[] |
34 | min_p?: number |
35 | n?: number |
36 | use_beam_search?: false | true |
37 | best_of?: number |
38 | length_penalty?: number |
39 | early_stopping?: false | true |
40 | logprobs?: false | true |
41 | top_logprobs?: number |
42 | frequency_penalty?: number |
43 | presence_penalty?: number |
44 | top_p?: number |
45 | openai_api_key?: string |
46 | } |
47 | ) { |
48 | const url = new URL(`https://api.telnyx.com/v2/ai/chat/completions`) |
49 |
|
50 | const response = await fetch(url, { |
51 | method: 'POST', |
52 | headers: { |
53 | 'Content-Type': 'application/json', |
54 | Authorization: 'Bearer ' + auth.apiKey |
55 | }, |
56 | body: JSON.stringify(body) |
57 | }) |
58 | if (!response.ok) { |
59 | const text = await response.text() |
60 | throw new Error(`${response.status} ${text}`) |
61 | } |
62 | return await response.json() |
63 | } |
64 |
|