Skip to content

Instantly share code, notes, and snippets.

@petrbrzek
Last active February 7, 2024 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petrbrzek/4c539b12cc691254e3c7f8a5dc3ae3fe to your computer and use it in GitHub Desktop.
Save petrbrzek/4c539b12cc691254e3c7f8a5dc3ae3fe to your computer and use it in GitHub Desktop.
Langtail simple chat completition fetch in TypeScript
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