I'm trying to keep a conversation going using the completion() method with OpenAI PHP SDK.
Prompt #1: "How Are You?"
Prompt #2: "What I asked you before?"
but the AI seems to forget what i asked before. and it reply with random answers to the second prompt.
The code i'm using for the 2 calls are these:
$call1 = $open_ai->completion([
'model' => 'text-davinci-003',
'prompt' => 'How Are You?',
]);
$call2 = $open_ai->completion([
'model' => 'text-davinci-003',
'prompt' => 'What i asked you before?',
]);
What am I missing? How can i keep the session alive between these two calls in order to make the AI remember what I asked before?
Second answer, as the first one did not answer OP's question.
Based on this OpenAI Playground Example, a 'conversation' can only be 'asked' by sending both the command to the API.
Don't think there is a way of keep the conversation going after retreiving a response.
Consider this example, were we send the following text:
The following is a conversation with an AI assistant.
Human: Hello
Human: What is 3 * 3?
AI:
Human: What did I just asked?
AI:
The response I get is:
You asked me what 3 * 3 is. The answer is 9.
Code used for this:
<?php
require __DIR__ . '/vendor/autoload.php';
use Orhanerday\OpenAi\OpenAi;
$open_ai_key = getenv('OPENAI_API_KEY');
$open_ai = new OpenAi($open_ai_key);
function ask($ai, $question, $model = 'text-davinci-003') {
$res = $ai->completion([
'model' => $model,
'prompt' => $question,
'temperature' => 0.9,
'max_tokens' => 150,
'frequency_penalty' => 0,
'presence_penalty' => 0.6,
'stop' => ["\nHuman:", "\nAI:"]
]);
try {
$json = #json_decode($res);
foreach ($json->choices as $choice) {
echo $choice->text . PHP_EOL;
}
} catch (Exception $e) {
var_dump($e);
return NULL;
}
}
$text = <<<EOL
The following is a conversation with an AI assistant.
Human: Hello
Human: What is 3 * 3?
AI:
Human: What did I just asked?
AI:
EOL;
$res = ask($open_ai, $text);
Note the stop array that, quoted from the documentation:
Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence.
This seems to let the AI know where to 'read' and where to 'write'
If you remove that param from the request, it returns without the answer:
You asked what 3 times 3 is.
The same problem is here :( Kind of a dream to develop a relationship with AI to keep a conversation but apparently, every request triggers a new session, according to my experience you have to send a full text to AI (davinci for me now)to get what you want.
openai.api_key = key
response = openai.Completion.create(
model="text-davinci-003",
prompt="Human: Hello AI, how can we save our session to talk future? \nAI:",
temperature=0.9,
max_tokens=150,
top_p=1,
frequency_penalty=0.0,
presence_penalty=0.6,
stop=[" Human:", " AI:"]
)
Rep:
"text": " You can save the session by saving the conversation logs to a file or capturing screenshots of the conversation. Additionally, you can create an account with a chatbot service provider in order to save and continue conversations at any time."}
Related
I am trying to create a report so I can import products in bulk. The issue i am facing right now is that whatever I have done always got Invalid input error. It seems very very ambiguous error message I have checked issue here and similar once but unfortunately no solution worked.
So if you check below received error from sp-api
{
"notifications": [],
"text": "{\"message\":\"[400] [{\\\"code\\\":\\\"InvalidInput\\\",\\\"message\\\":\\\"Could not match input arguments\\\"}]\",\"success\":false}"
}
you will notice that it seems there is a mistake with my code regarding datatype(as I understood from error) But I have made sure many times of datatype, even I have wrote data as string[] but honestly it took too much time. Please find my code
$config = new Configuration([
"lwaClientId" => $account_data['lwa_client_id'],
"lwaClientSecret" => $account_data['lwa_client_secret'],
"lwaRefreshToken" => $account_data['lwa_refresh_token'],
"awsAccessKeyId" => $account_data['aws_access_key'],
"awsSecretAccessKey" => $account_data['aws_secret_key'],
"endpoint" => SellingPartnerApi\Endpoint::NA ,
]);
$apiInstance = new SellingPartnerApi\Api\ReportsApi($config);
$body = new SellingPartnerApi\Model\Reports\CreateReportSpecification([
'marketplace_ids' => [$merchant_data['marketplace_ids']],
'report_type' => ReportType::GET_MERCHANT_LISTINGS_ALL_DATA['name'],
]);
try{
$report_id = $apiInstance->createReport($body);
}catch(Exception $e){
return array("message"=>$e->getMessage(),'success'=>false);
}
Btw, I am using this lib https://github.com/jlevers/selling-partner-api
Please note that 3 of CreateReportSpecification parameter are optional (report_options, data_start_time, data_end_time) I didn't passed it at constructor.
Could you please advise what's went wrong with my code? Why I am receiving Invalid Input ??
Thanks in advance
Check that AWS_ENV=PRODUCTION (not SANDBOX)
I have setup a Google Actions conversational project, with dialogflow and webhook intents served by my server in PHP.
Upon new dialogflow conversation startup, e.g. just before replying to the welcome intent, the php code is pushing some session entities to the dialogflow engine.
The dialogflow engine recognized correctly the session entity words until two weeks ago, when it suddendly stopped working (I have changed nothing in the code), and right now it's still not working.
The session entities are created with no errors (I added code to query dialogflow api and list session entitites after creation, and google is replying with all the words I send).
However the Intent does not recognize and does not fill in the entity parameters.
Here is the code I'm using to push the entities (using google dialogflow v2 library):
$names = [....array of strings....];
$parent = 'projects/inim-prova/agent/sessions/' . $sessionId;
$client = new SessionEntityTypesClient(['credentials' => $keyfile]]);
$entities = array_map(function($item) { return new Entity(['value' => $item, 'synonyms' => [$item]]); }, array_unique($names));
$entityType = new SessionEntityType([
'name' => $parent . "/entityTypes/$displayName",
'entity_override_mode' => EntityOverrideMode::ENTITY_OVERRIDE_MODE_SUPPLEMENT,
'entities' => $entities
]);
$client->createSessionEntityType($parent, $entityType);
this code runs with no exception thrown.
After a few lines I'm querying the server to see if everything is ok:
$req = $client->listSessionEntityTypes($this->webhookRequest->getSession());
foreach ($req as $element) {
Logger::log(Logger::DEV, __METHOD__, "SessionEntityType: " . $element->getName());
$entities = $element->getEntities();
foreach ($entities as $entity) {
$synonyms = [];
foreach ($entity->getSynonyms() as $synonym) $synonyms[] = $synonym;
Logger::log(Logger::DEV, __METHOD__, ">> " . $entity->getValue() . ": " . implode(', ', $synonyms));
}
}
and this is an extract from the debug log:
SessionEntityType: projects/inim-prova/agent/sessions/ABwppHHhgwxi5OGznpUtUq2D7BQrOKWB5Y5UYr20HRKI14iASKugPw2dL2VKMwfvZ193Mq_DUb2emQ/entityTypes/NomiLuoghiUscite
>> sala: sala
>> cucina: cucina
>> giardino: giardino
SessionEntityType: projects/inim-prova/agent/sessions/ABwppHHhgwxi5OGznpUtUq2D7BQrOKWB5Y5UYr20HRKI14iASKugPw2dL2VKMwfvZ193Mq_DUb2emQ/entityTypes/NomiUscite
>> luci: luci
>> irrigazione: irrigazione
>> cappa: cappa
therefore all the entities seem to be in the right place.
This is the intent training phrase:
(please note that ArticoliDeterminativi and Preposizioni are static entities which I'm ignoring).
and these are the parameters I get on webhook request when I say Accendi le luci in cucina:
'parameters' => array (
'NomiUscite.original' => '',
'Preposizioni.original' => '',
'NomiLuoghiUscite' => '',
'NomiUscite' => '',
'Preposizioni' => '',
'ArticoliDeterminativi.original' => 'le',
'NomiLuoghiUscite.original' => '',
'ArticoliDeterminativi' => 'il',
)
As you can see, NomiUscite and NomiLuoghiUscite are empty. I expect them to be luci and cucina.
I'm really clueless.
It looks like it really was a dialogflow bug, not a flaw in my code.
After a couple of week, Support guys from Google replied me telling that the issue has been resolved.
I've run again tests with no modification on code at all, and now it works.
You should add words 'uscita' and 'luogo' to the Session Entities. I can how the parameters can be empty if you annotate words that are not part of the entity.
You also can try adding 'Accendi le luci in cucina' as a Training Phrase.
Given that I have a WHMCS addon that I call 'my_addon'. I created the main addon file 'my_addon.php' which does contain nothing than:
<?php
function my_addon_clientarea($vars) {
$client = null;
return array(
'pagetitle' => 'My Addon',
'breadcrumb' => array('index.php?m=my_addon'=>'My Addon'),
'templatefile' => 'views/myaddon_view',
'vars' => array(
'client' => $client
)
);
}
This does basically work. It does give me my template file, everything is passed through. My question is: How do I get the currently logged in client from within that function?
I didn't find any API method and I can't see any constant which does hold this information.
There must be a way to get the current client within the clientarea? Thanks for your help!
For those who do come after me and have the same problem: it's easy to solve. Turned out, that I just had to think it through... I found the client id to be available in the $_SESSION-variable.
So, if you are looking for the client's id:
<?php
function my_addon_clientarea($vars) {
$clientid = $_SESSION['uid'];
// And so on...
}
The official way to get current user information is:
$currentUser = new \WHMCS\Authentication\CurrentUser;
$user = $currentUser->user();
You can find more information here
Im new to coding and web development as it is and diving into the deep end with API's is a thing i wish i never had done! However being said i have progressed further than expected. I am now having problems when trying to add custom fields to the add contact feature. Im trying to get the code to add the hidden form input fields when the user hits my thankyou page. I dont want to use Getresponses own Form builder for my main page so it was better to use the API. I have the code running perfectly when it comes to just adding the contact however when i add the set_contact_customs the code does not execute and fails with the following error: (Request have return error: Array) So i understand its to do with the set_contact_customs array however im clueless as to what it is i have done wrong.. Any advice and help is greatly appreciated as i am still learning the basics so picking up on what you experts say is a great learning curve. Thanks.
--- Below is the working version without the set_contact_customs ----
<?php
// Add contact to selected campaign id
try{
$result_contact = $client->add_contact(
$api_key,
array (
'campaign' => 'My-Camp-ID',
'name' => $fullname,
'email' => $emailaddress
)
);
echo "<p style='color: blue; font-size:24px;'>No Errors, Contact and Custom Fields have been added...</p>";
}
catch (Exception $e) {
echo $e->getMessage();
}
?>
--- Here is the code that causes the problems (with set_contact_customs) ----
<?php
// Add contact to selected campaign id
try{
$result_contact = $client->add_contact(
$api_key,
array (
'campaign' => 'My-Camp-ID',
'name' => $fullname,
'email' => $emailaddress
)
);
$result_contact = $client->set_contact_customs(
$api_key,
array(
'Survey Type' => $surveytype,
'Survey Cost' => $surveycost
)
);
echo "<p style='color: blue; font-size:24px;'> Contact Added </p>";
}
catch (Exception $e) {
echo $e->getMessage();
}
?>
API 2 doesn't really exist: in GetResponse they say version "1.5.0 - this is last JSON/RPC version of our API", especially if you were speaking 10 months ago. Now they are preparing to beta-test v3. So I will assume you were speaking about 1.5 and answer about it (I'm not familiar with v3, maybe there it's different).
You must send contact id with set_contact_customs, and you didn't.
When it says, "request error: array", it doesn't relate to your array (even though the problem is in your array, because you don't send in it contact id), they are sending an array as a response with error messages.
I'd love to tell you, where to get the contact id in order to send it, but I'm looking for it myself now. :)
UPDATE:
Ok, I combined it from pieces all over the internet, and now here's the working format.
You don't need to add_contact and then update it, you can do it in one go, adding the 'customs' parameter to the add_contact call (GR say, that we shouldn't expect for the contact to be added immediately, so you might not even get whom to update, if you call that function right away).
The fields for add_contact are described here.
The 'customs' parameter should look differently. Instead of:
array(
'Survey Type' => $surveytype,
'Survey Cost' => $surveycost
)
it should be:
array(
array( 'name' => 'Survey Type', 'content' => $surveytype ),
array( 'name' => 'Survey Cost', 'content' => $surveycost )
)
By the way, from what I tested, - blessedly, you don't need to define in GR UI those custom fields first, whatever you send, will be added or updated (in their limits for the custom field names and values).
I got error, when tried to send one custom field with empty content, when calling add_contact. When I sent it with set_contact_customs, I didn't get any error; I wanted to see, if it would delete the field or field value - it didn't do a thing.
If you still wish to update the existing contact, here's how to send the contact id with the update call:
$result = $client->set_contact_customs(
$api_key, array(
'contact' => $contact_id,
'customs' => $custom_fields_array
)
);
To first find contact id, you should call get_contacts. And since it's been said (I haven't tested it), that in different campaigns contacts with the same email address have different contact id, you should pass both the campaign, and the email with it.
As you can see, campaign can be sent in 'campaigns' parameter (then campaign id, that you got for add_contact, should be used), or in 'get_campaigns' (then the campaign name or even prefix can be used).
Here's the call with campaign id, for your code:
$result = $client->get_contacts(
$api_key, array(
'campaigns' => array( 'My-Camp-ID' ),
'email' => array( 'EQUALS' => $emailaddress )
)
);
To retrieve contact id from get_contacts, do the same as recommended for retrieving campaign id:
$contact_id = array_pop( array_keys( $result ) );
if ( empty( $contact_id ) ) {
//still not ok
}
else {
//you can call set_contact_customs
}
In order for that error message to be more descriptive, instead of just 'Request have return error: Array', open your jsonRPCClient.php, which you most surely include in your file with these GR function calls, and look for the following line:
!is_null($response['error']) => 'Request have return error: ' . $response['error'],
and replace it with the following, at least:
!is_null($response['error']) => 'Request have returned error: ' . var_export($response['error'], true),
Now your code will use the beloved var_export function and if you make a mistake, you will see in your error log something like:
Request have returned error: array (
'message' => 'Invalid params',
'code' => -32602,
)
I dedicate this thorough answer to all those, who helped me endlessly here on StackOverflow, just giving their answers to someone else's questions, sometimes years ago. Thank you! Hopefully my answer will save someone time, efforts, and mood, too. :)
I am using the codeigniter rest server api library.
When I enter http://localhost/projects/myapi/key/index_put.php and hit enter gives me the following error:
<xml>
<status>0</status>
<error>Invalid API Key</error>
</xml>
When I give a dummy string in the url, like:
http://localhost/projects/myapi/key/index_put.php?X-API-KEY=asldfj9alsdjflja97979797997
I get the same problem. Any idea?
index_put.php:
public function index_put() {
// Build a new key
$key = self::_generate_key();
// If no key level provided, give them a rubbish one
$level = $this->put('level') ? $this->put('level') : 1;
$ignore_limits = $this->put('ignore_limits') ? $this->put('ignore_limits') : 1;
// Insert the new key
if (self::_insert_key($key, array('level' => $level, 'ignore_limits' => $ignore_limits))) {
$this->response(array('status' => 1, 'key' => $key), 201); // 201 = Created
} else {
$this->response(array('status' => 0, 'error' => 'Could not save the key.'), 500); // 500 = Internal Server Error
}
}
i faced the same issue .don't mention put/get/post in URL ,RestServer itself recognizes the request nature base on parameter you pass two step required to solve your problem .
1st Step :
http://localhost/projects/myapi/key/index_put.php
must change to :
http://localhost/projects/myapi/key/index.php
2nd step:
create an api kay using sha1(max 40 character) in the keys table (table structure show in config/rest.php file),
enter 1 in is_private_key field and ::1 in ip_address field.
create the record ,and check it again .
This question is old but for those who finds this, the answer is:
The library https://github.com/chriskacerguis/codeigniter-restserver when using PUT method, the API KEY should be in the put header variables as x-www-form-urlencoded type.
Use google chrome postman and fill like image below: