import json
from writerai import Writer
# Initialize the Writer client. If you don't pass the `apiKey` parameter,
# the client looks for the `WRITER_API_KEY` environment variable.
client = Writer()
def generate_product_description(product_name):
response = client.applications.generate_content(
application_id="your-application-id",
inputs=[
{
"id": "Product name",
"value": [product_name]
}
]
)
return response.suggestion
tools = [
{
"type": "function",
"function": {
"name": "generate_product_description",
"description": "A function that will invoke an agent for text-generation, specialized in generating product descriptions. Any user request asking for product descriptions should use this tool.",
"parameters": {
"type": "object",
"properties": {
"product_name": {
"type": "string",
"description": "The name of the product"
}
},
"required": ["product_name"]
}
}
}
]
messages = [{"role": "user", "content": "Generate a description for the Terra running shoe"}]
# Send the request
response = client.chat.chat(
model="palmyra-x5",
messages=messages,
tools=tools,
tool_choice="auto",
stream=False
)
# Process the response
response_message = response.choices[0].message
# Check if the response contains tool calls,
#and if so, call the custom function
tool_calls = response_message.tool_calls
if tool_calls:
tool_call = tool_calls[0]
tool_call_id = tool_call.id
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
if function_name == "generate_product_description":
function_response = generate_product_description(function_args["product_name"])
messages.append({
"role": "tool",
"tool_call_id": tool_call_id,
"name": function_name,
"content": function_response
})
final_response = client.chat.chat(
model="palmyra-x5",
messages=messages,
stream=False
)
print(final_response.choices[0].message.content)
# Here's a product description for the Terra running shoe: ...