Last active
February 7, 2024 16:25
-
-
Save petrbrzek/4c539b12cc691254e3c7f8a5dc3ae3fe to your computer and use it in GitHub Desktop.
Langtail simple chat completition fetch in TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function getChatCompletion({ | |
promptName, | |
variables, | |
}: { | |
promptName: string | |
variables: Record<string, string> | |
}) { | |
const workspace = '<YOUR_WORKSPACE>' // Replace <YOUR_WORKSPACE> with your actual workspace ID | |
const project = '<YOUR_PROJECT>' // Replace <YOUR_PROJECT> with your actual project ID | |
const env = 'production' | |
const apiKey = '<YOUR_API_KEY>' // Replace <YOUR_API_KEY> with your actual API key | |
try { | |
const response = await fetch( | |
`https://api.langtail.com/${workspace}/${project}/${promptName}/${env}?v=1`, | |
{ | |
method: 'POST', | |
headers: { | |
'X-API-Key': apiKey, | |
'Content-Type': 'application/json', | |
}, | |
body: JSON.stringify({ | |
stream: false, | |
variables: variables, | |
}), | |
} | |
) | |
if (!response.ok) { | |
throw new Error('Network response was not ok') | |
} | |
const data = await response.json() | |
return data.choices[0].message.content | |
} catch (err) { | |
console.error('Fetch error:', err) | |
} | |
} | |
async function main() { | |
const headline = await getChatCompletion({ | |
promptName: 'get-headline', | |
variables: { | |
category: 'AI', | |
}, | |
}) | |
// headline result: "AI Takes Over the World: 10 Mind-Blowing Ways Artificial Intelligence is Revolutionizing Our Lives!" | |
const tweet = await getChatCompletion({ | |
promptName: 'get-tweet', | |
variables: { | |
title: headline, | |
}, | |
}) | |
console.log(tweet) | |
// tweet result: "From self-driving cars to personalized medicine, AI is transforming our lives in unimaginable ways. Check out these mind-blowing ways artificial intelligence is revolutionizing our world! #AI #technology #innovation" | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment